The where clause is used to specify type constraints. These constraints can be used as variables for type parameters defined in generic declarations. 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 {}
In addition to interface constraints, the where clause can also include base class constraints to indicate that a type must use the specified class as the base class (or the class itself ), can be used as a type parameter for this generic type.
This constraint must appear before all other constraints of this type of parameter.
// compile with: /target:library
using System;
class MyClassy<T, U>
where T : class
where U : struct
{
}
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:
Code
// cs_where_2.cs
// compile with: /target:library
using System;
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.
For multiple type parameters, each type parameter uses a where clause, for example:
Code
// cs_where_3.cs
// compile with: /target:library
using System;
using System.Collections;
interface MyI
{
}
class Dictionary<TKey,TVal>
where TKey: IComparable, IEnumerable
where TVal: MyI
{
public void Add(TKey key, TVal val)
{
}
}
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()