Export (0) Print
Expand All
13 out of 19 rated this helpful - Rate this topic

where (C# Reference)

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 { }

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.

// cs_where.cs
// compile with: /target:library
using System;

class MyClassy<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:

// 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 last in the where clause.

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

// 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, 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.

For more information, see the following sections in the C# Language Specification:

  • 19.1.4 Constraints

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

© 2014 Microsoft. All rights reserved.