C # class method declaration where _ gift of zookeeper,
The where clause is used to specify type constraints. These constraints can be used as variables for type parameters defined in generic declarations.
1. Interface constraints.
For example, you can declare a generic class.MyGenericClassIn this way, the type parameterTYou can implement the IComparable <T> interface:
Public class MyGenericClass <T> where T: IComparable {}
2. base class constraints: indicates that a type must use the specified class as the base class (or the class itself) to be used as the type parameter of the generic type.
This constraint must appear before all other constraints of this type of parameter.
Class MyClassy <T, U>
Where T: class
Where U: struct
{
}
3. The where clause can also include constructor constraints.
You can use the new operator to create an instance of the type parameter. However, the type parameter must be subject to the constructor constraints of new. The new () constraint allows the compiler to know that any type of parameter provided must have an accessible, non-parameter (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, for example:
Public bool MyMethod <T> (T t) where T: IMyInterface {}
Note that for delegates and methods, the syntax for describing type parameter constraints is the same:
Delegate T MyDelegate <T> () where T: new ()