Common Type System—Special Runtime Constraints


Jump to: navigation, search
CSharp-Online.NET:Articles
.NET Articles

Common Type System

© 2006 Wiley Publishing Inc.

Special Runtime Constraints

The second way to constrain type parameters is to use one of the special constraints offered by the CLR. There are three. Two indicate whether the type argument is a reference or value type (class and struct) and use the same syntax as above, differing only in that the keyword class or struct takes the place of the type name, for example:

class OnlyRefTypes<T> where T : class {}
class OnlyValTypes<T> where T : struct {}

One interesting thing to note is that both the class and struct constraints intentionally exclude the special type System.Nullable<T>. This is because Nullable is somewhere in between a reference and value type in the runtime, and neither was deemed appropriate by the designers. Thus, it is not valid for a type parameter constrained to take on the Nullable<T> type argument at construction time.

Lastly, you may constrain a type parameter to only arguments with default constructors. This enables the generic code to create instances of them using the default coinstructor. For example:

class Foo
{
   public void Bar<T>() where T : new()
   {
      T t = new T(); // This is possible only because of T : new()
      // ...
   }
}

The emitted IL code uses the Activator.CreateInstance API to generate an instance of T, binding to the default constructor at runtime. This API is also used for reflection- and COM-based instantiation. It utilizes dynamic information available within internal CLR data structures to construct a new instance for you. This is mostly transparent, although if the constructor throws an exception, you will notice the call to CreateInstance in the call-stack.


Previous_Page_.gif Next_Page_.gif





AbeBooks.com &#8211; Textbooks