What is “where T: class” in C # common methods?

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?

+4
source share
4 answers

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

See Type Parameter Limitations (C # Programming Guide) :

where T: class

Type must be a reference type [class]; this also applies to any class, interface, delegation, or array type.

+8
source

in the first case, you can call it using a non ref type, for example

 MyMethod<int>(10); 

which will not work with the second version, since it only accepts link types!

+4
source

no difference, but T is limited to a reference type. they differ only in compiletime, since the compiler checks that T is a ref type or not.

+1
source
  • Both will not compile. You must use either void or T
  • And the second method will not work for MyMethod(1) , because it requires a reference type T
+1
source

Source: https://habr.com/ru/post/1400883/


All Articles