Thursday, August 30, 2007

NET: Generic Constraint Type - Default Constructor Constraint Type

Default Constructor constraint allow you to specify that the type parameter must have a default/parameterless constructor. This is useful if you want to create a new object instance of the type argument.

public class DefaultConstructorGenericType<T> where T : new()
public T Value;
public DefaultConstructorGenericType()
Value = new T();
public class ClassWithDefaultCon
public ClassWithDefaultCon() {}

public class ClassB
public int a;
public ClassB(int v) { a = v;}
static void InstantiateDefault()
// This code will compile fine.
DefaultConstructorGenericType<ClassWithDefaultCon> vt =
new DefaultConstructorGenericType<ClassWithDefaultCon>();
// This code will give compile error
// because ClassB does not have default constructor
DefaultConstructorGenericType<ClassB> vt =
new DefaultConstructorGenericType<ClassB>();

In the above sample, DefaultConstructorGenericType can only accept a type argument that has a default constructor. where keyword is used to specify a generic constraint in C#. In the above code sample, I specify that type parameter T has to have default constructor (indicate by where T : new()).

Labels: , ,


Post a Comment

<< Home