Monday, August 11, 2008

The "Default" keyword in C# Generics

Generics are very useful while creating reusable components and ensuring type safety. There may be times where one is unsure whether the type of T is a value type or a reference type.In such circumstances we could use the "default" keyword being provided by c#."default" will return null in case of reference types and will return 0 in case if value types. For structures "default" will initialise each item of an enum to null or 0 based on whether its a reference type or value type.


for eg:
Class GenericComparerClass where T: IComparable
{
public T t1;
public T t2;

public GenericComparerClass(T t1Type, T t2Type)
{
t1= t1Type;
t2= t2Type;
}

public T MaxT()
{
if(t1.CompareTo(t2)>0)
return T1;
else
default(T);
}


}

Happy coding....

No comments: