Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the keyword "where" in a class declaration do?

Tags:

c#

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?

like image 763
Bialecki Avatar asked Apr 29 '10 18:04

Bialecki


2 Answers

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)

like image 143
Oded Avatar answered Sep 27 '22 22:09

Oded


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.

like image 26
Danvil Avatar answered Sep 27 '22 23:09

Danvil