Reputation: 913
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?
Upvotes: 12
Views: 28732
Reputation: 588
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.
Upvotes: 12
Reputation: 12226
void
or T
. MyMethod(1)
because it requires reference type to T
Upvotes: 1
Reputation: 38515
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!
Upvotes: 6
Reputation: 3544
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.
Upvotes: 1