Bip
Bip

Reputation: 913

What is "where T : class" in C# generic 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?

Upvotes: 12

Views: 28732

Answers (4)

Sean Barlow
Sean Barlow

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

the_joric
the_joric

Reputation: 12226

  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

Upvotes: 1

Peter
Peter

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

mo.
mo.

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

Related Questions