The where clause is used to specify type constraints that can serve as variables for type parameters defined in generic declarations. 1. Interface constraints. For example, you can declare a generic class MyGenericClass, so that the type parameter T can implement the IComparable<T> interface:
public class MyGenericClass<T> where T:IComparable { }
2. Base class constraint: Indicates that a type must use the specified class as the base class (or the class itself) to be used as a type parameter for that generic type. Once such a constraint is used, it must appear before all other constraints on the type of parameter. class MyClassy<T, U> where T : class where U : struct
{
}
The 3.where clause can also include constructor constraints. You can use the new operator to create an instance of a type parameter; But the type argument must be constrained by the constructor constraint new() for this. The new() constraint lets the compiler know that any type of argument provided must have an accessible parameterless (or default) constructor. For example: public class MyGenericClass <T> where T: IComparable, new()
{ // The following line is not possible without new() constraint: T item = new T();
} The new() constraint appears at the end of the where clause.
4. For multiple type parameters, each type parameter uses a where clause, For example: interface MyI { } class Dictionary<TKey,TVal> where TKey: IComparable, IEnumerable where TVal: MyI
{ public void Add(TKey key, TVal val)
{
}
}
5. You can also attach constraints to type parameters of generic methods, such as:
public bool MyMethod<T>(T t) where T : IMyInterface { }
Note that the syntax for describing type parameter constraints is the same for both delegates and methods:
delegate T MyDelegate<T>() where T : new()
Generic Where
Generic Where can qualify type parameters. There are several ways.
·where T : struct restricts the type parameter T must inherit from System.ValueType.
·where T: class restricts type The parameter T must be a reference type, that is, it cannot be inherited from System.ValueType.
where T : new() restricts the type parameter T must have a default constructor
·where T : NameOfClass restricts the type parameter T must inherit from a class or implement an interface.
These qualifiers can be combined, such as: public class Point where T : class, IComparable, new() |