13

I'm looking at the source code for the MvcContrib Grid and see the class declared as:

public class Grid<T> : IGrid<T> where T : class

What does the where T : class bit do?

Garrett
  • 4,007
  • 2
  • 41
  • 59
Bialecki
  • 30,061
  • 36
  • 87
  • 109

7 Answers7

20

It is a generic type constraint.

In this case it means that the generic type (T) must be a reference type, that is class, interface, delegate, or array type.

Other constraints are listed here.

You can also constrain the generic type to inherit from a specific type (base class or interface)

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 3
    No, it has nothing to do with being derived from Object. It can be an interface or delegate, for example. – Gabe Apr 29 '10 at 18:45
4

Another examples would be

public A<T> where T : AnInterface

where AnInterface is a interface class. It means then, that T must implement this interface.

These constraints are important, so that the compiler knows the operations which are valid for the type. For example you can not call functions of T without telling the compiler what functions the type provides.

Danvil
  • 22,240
  • 19
  • 65
  • 88
3

From the Docs http://msdn.microsoft.com/en-us/library/d5x73970.aspx

where T : class

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

CaffGeek
  • 21,856
  • 17
  • 100
  • 184
2

It is a constraint on the type argument which says that T can either be a class or an interface but not an enum or a struct. So T must be a reference type and not a value type.

Best Regards,
Oliver Hanappi

Oliver Hanappi
  • 12,046
  • 7
  • 51
  • 68
1

It restricts T to be a reference type, including any class, interface, delegate, or array type.

Michael Madsen
  • 54,231
  • 8
  • 72
  • 83
1

you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class are called as Constraints on Type Parameters

E.g : where T : class

Here where T is the Type , The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

anishMarokey
  • 11,279
  • 2
  • 34
  • 47
1

It's a generic type constraint. It specifies that the type T has to be a reference type, i.e. a class and not a structure.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005