Condividi tramite


where (generic type constraint) (C# Reference)

In a generic type definition, the where clause is used to specify constraints on the types that can be used as arguments for a type parameter defined in a generic declaration. For example, you can declare a generic class, MyGenericClass, such that the type parameter T implements the IComparable<T> interface:

public class MyGenericClass<T> where T:IComparable { }

Note

For more information on the where clause in a query expression, see where clause (C# Reference).

In addition to interface constraints, a where clause can include a base class constraint, which states that a type must have the specified class as a base class (or be that class itself) in order to be used as a type argument for that generic type. If such a constraint is used, it must appear before any other constraints on that type parameter.

class MyClass<T, U>
    where T : class 
    where U : struct
{ }

The where clause may also include a constructor constraint. It is possible to create an instance of a type parameter using the new operator; however, in order to do so the type parameter must be constrained by the constructor constraint, new(). The new() Constraint lets the compiler know that any type argument supplied 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 last in the where clause.

With multiple type parameters, use one where clause for each type parameter, for example:

interface IMyInterface
{
}

class Dictionary<TKey, TVal>
    where TKey : IComparable, IEnumerable
    where TVal : IMyInterface
{
    public void Add(TKey key, TVal val)
    {
    }
}

You can also attach constraints to type parameters of generic methods, like this:

public bool MyMethod<T>(T t) where T : IMyInterface { }

Notice that the syntax to describe type parameter constraints on delegates is the same as that of methods:

delegate T MyDelegate<T>() where T : new()

For information on generic delegates, see Generic Delegates.

For details on the syntax and use of constraints, see Constraints on Type Parameters.

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Reference

Introduction to Generics (C# Programming Guide)

new Constraint (C# Reference)

Constraints on Type Parameters (C# Programming Guide)

Concepts

C# Programming Guide

Other Resources

C# Reference