What does "where T : class, new()" mean?

Rawhi  picture Rawhi · Jan 19, 2011 · Viewed 127k times · Source

Can you please explain to me what where T : class, new() means in the following line of code?

void Add<T>(T item) where T : class, new();

Answer

NerdFury picture NerdFury · Jan 19, 2011

That is a constraint on the generic parameter T. It must be a class (reference type) and must have a public parameter-less default constructor.

That means T can't be an int, float, double, DateTime or any other struct (value type).

It could be a string, or any other custom reference type, as long as it has a default or parameter-less constructor.