0

I'm doing some Pluralsight training. The instructor specified several function declarations in an interface, one of which looks like this:

void Add<T>(T entity) where T : class;

So generics are being used, the data type is of type "T", it's declaring a parameter named "entity" which is of type T. What I don't understand if the clause:

"where T : class"

What does that mean?

LB2
  • 4,802
  • 19
  • 35
Rod
  • 4,107
  • 12
  • 57
  • 81

3 Answers3

1

it is a constraint which says your T should be a reference Type.

From MSDN: where T : class

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

Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
1

This is called a generic constraint. It means that the type of T must be a class.

cfbarbero
  • 1,607
  • 2
  • 14
  • 26
1

It's ensuring that the generic type T is of type class.

So as an example yourClass.Add<int>(2) would show a compile time error because int is not a class/reference type.

cheesesharp
  • 543
  • 3
  • 11