Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "where T : class" in C# generic methods?

Tags:

c#

generics

What is the difference between these method signatures?

public void T MyMethod<T>(T parameter)

and

public void T MyMethod<T>(T parameter) where T : class

They seem to have the same result ... so what does where T : class do?

like image 720
Bip Avatar asked Mar 11 '12 20:03

Bip


Video Answer


4 Answers

In the second method the T can only be a class and cannot be a structure type.

See Constraints on Type Parameters (C# Programming Guide):

where T : class

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

like image 52
Sean Barlow Avatar answered Oct 14 '22 23:10

Sean Barlow


in the first one you can call it with a non ref type for example

MyMethod<int>(10);

that will not work with the second version as it only accepts ref types!

like image 31
Peter Avatar answered Oct 14 '22 23:10

Peter


there is no difference, but T is restricted to a reference-type. they differ only at compiletime, as the compiler checks wether T is a ref-type or not.

like image 39
mo. Avatar answered Oct 14 '22 23:10

mo.


  1. Both won't compile. You should use either void or T.
  2. And second method won't work for MyMethod(1) because it requires reference type to T
like image 29
the_joric Avatar answered Oct 15 '22 00:10

the_joric