Generic Constraints thougths

There are 3 types of constraints.


A derivation constraint indicates to the compiler that the generic type parameter derives from a base type such an interface or a particular base class.

class LinkedList where K : IComparable

A default constructor constraint indicates to the compiler that the generic type parameter exposes a default public constructor (a public constructor with no parameters).

class Node where T : new()

A reference/value type constraint constrains the generic type parameter to be a reference or a value type.

class MyClass where T : struct class MyClass where T : class


 

2 comments:

Swami said...

Is it possible to restrict a particular type being used for a .NET Generic type.
say

class < T > {
...
}
I want to make sure that T cannot be an integral type. I would want to restrict T from being an integral type

.peter.gfader. said...

why you should restrict the usage of your class like this?

if you find an interface that all those "other types" have in common, then you can do it with the derivation constraint.

Or you can say no structs...

public class TestImpl < T > where T : class
{
...
}

Post a Comment

Latest Posts

Popular Posts