Wednesday, August 29, 2007

NET: Introduction to Generic Constraint Type

Generic constraint allow you to specify constraint/rule that limit what .net type can be used as type argument when you instantiate a generic type.

In this post, I will show a short code sample of how to use the various generic constraint.
For more explaination about Generic Constraint, visit msdn

How to specify constraint value type

Value type constraint allow you to specify that the type parameter must be of value type.

class GenericValueType<T> where T : struct
public T Value;
static void InstantiateValueType()
// This code will compile fine.
GenericValueType<System.Drawing.Point> vt =
new GenericValueType<System.Drawing.Point>();
// This code will give compile error
//because StringBuilder is not value type.
GenericValueType<System.Text.StringBuilder> vt2 =
new GenericValueType<StringBuilder>();

where keyword is used to specify a generic constraint in C#. In the above code sample, I specify that type parameter T has to be of value type (indicate by where T : struct).

Labels: , ,


Post a Comment

<< Home