Restriction to Value Types or Reference Types

Talking about different treatment for value types and reference types, one more way to constrain a generic type exists. Using the class and struct keywords, you can constrain a type parameter to accept only reference types or value types, respectively:

class HasRef<T> where T : class {    private T _reference;}class HasVal<T> where T : struct {    private T _value;}

For the reference type constraint, using the class keyword, any reference type can be used, including classes, interfaces, and delegates. For value types, using the struct keyword, you can use all value types (except for nullable value types).

Notice that based on the constraint, the compiler again rejects ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.