It is a common mistake (see answers here) to think that adding where T : class to the generic method / type declaration achieves this, but it is wrong. This actually means that " T must be a reference type", which also includes delegates and interfaces (plus arrays, etc., for example string ).
If you need a class, there are two ways; the easiest way is to insist on where T : class, new() , since neither an interface nor a delegate can have constructors. This has false negatives, though, in terms of discarding classes without public constructors without parameters.
The only other way is at runtime:
if(!typeof(T).IsClass) throw new InvalidOperationException("T must be a class");
Equally, where T : struct does not mean that " T must be a value of type", either! This means that T must be a non-nullable value-type "; types with Nullable<> do not satisfy T : struct , even though Nullable<Foo> a struct .
source share