Tuesday, 9 June 2009

Generic Classes

You can declare a class with a generic type so that you can later instantiate it specifying the type at that point.

public abstract class genericListClass<t>
{
protected virtual add(T value)
{
...
}
}

You can then instantiate a GenericListClass for different type as follows;

genericListClass<int> integerList = new genericListClass<int>()
genericListClass<long> LongList = new genericListClass<long>()
genericListClass<string> stringList = new genericListClass<string>()

You can also accept different generic types as parameters to methods in a generic class

public abstract class genericClass<t>
{
protected virtual CheckBoxOption[] WrapCheckBoxOptions<u>(string id, IEnumerable<checkboxoption> options)
{
...
}
}

The use of the <u> is to ensure it is taken as different from the type reperesented by <t>. <u> is a new different type.
In addition to this you can constrain the type of the class to a specific interface or behaviour;

public abstract class genericListClass<t>
{
protected virtual CheckBoxOption[] WrapCheckBoxOptions<u>(string id, IEnumerable<checkboxoption> options) where U : new()
{
}
}

This allows you to constrain the type <U> to a specific type or more usefully, Interface. You can also use it, as in this case,

where U : new()

to constrain the type to one that can be instantiated with a default constructor. In other words it does not require parameters to be passed to the constructor. So

U newInstance = new U();

will not raise an error.

No comments: