NET: Generic Constraint Type - Reference Constraint Type
Reference type constraint allow you to specify that the type parameter must be of reference type.
class GenericReferenceType<T> where T : class
{
public T Value;
}
static void InstantiateRefType()
{
// This code will compile fine.
GenericReferenceType<System.Text.StringBuilder> vt =
new GenericReferenceType<StringBuilder>();
// This code will give compile error
//because Point is not reference type.
GenericReferenceType<System.Drawing.Point> vt2 =
new GenericReferenceType<System.Drawing.Point>();
}
In the above sample, GenericReferenceType can only accept a reference type as its type parameter.
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 reference type (indicate by where T : class).
0 Comments:
Post a Comment
<< Home