Tuesday, March 24, 2009

Use Constraints in Generics

We use where clause to apply a constraints to a generic.

ex

class CompGen where T: IComparable
{
public T t1;
pbulic T t2;

public CompGen(T _t1, T _t2)
{
t1=_t1;
t2=_t2;
}

public T Max()
{
if(t2.CompareTo(t1)<0)
return t1;
else
return t2;

}
}

If we remove the where constraints clause, the compiler will return an error because generic type T does not contain a definition of CompareTo.

No comments: