O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required