Wednesday, August 29, 2007

NET: Generic Constraint Type - Inheritance Constraint Type

Inheritance type constraint allow you to specify that the type parameter must be derive from certain base class or interface. It is useful if you want to assume the type argument to be of certain type so that you can call method on the instance of the type argument. Visual Studio will give you full intellisense support.


public interface IPrint
{
void Print();
}
 
public class Printer : IPrint
{
public void Print()
{
// Do something
}
}
 
public class PhotoCopier
{
public void PhotoCopy()
{
// Do something.
}
}
 
public class DeviceWrapper<T> where T : IPrint
{
public T Device;
}
 
static void InstantiateDevice()
{
// This code will compile fine.
DeviceWrapper<Printer> vt =
new DeviceWrapper<Printer>();
 
// This code will give compile error
// because PhotoCopier is not derive from IPrint.
DeviceWrapper<PhotoCopier> vt2 =
new DeviceWrapper<PhotoCopier>();
}

In the above sample, DeviceWrapper can only accept a type argument that is derive from IPrint.
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 derive from IPrint (indicate by where T : IPrint).


Visual Studio Intellisense support
Visual Studio Intellisense support.

Labels: , ,

0 Comments:

Post a Comment

<< Home