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?
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.
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!
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.
void
or T
. MyMethod(1)
because it requires reference type to T
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With