Pranay Rana: Constrain on custom generic type

Monday, December 20, 2010

Constrain on custom generic type

Generics is most important topic included in C# 2.0. Generics are use full in number of way when we do coding in project. One of the most important use is we want to use collections with type safety and without boxing/unboxing.

But here I am going to discuss about the type of constrain we apply one the custom type we create using generics.

Reference Type
Constrain ensure that type argument is Reference Type. i.e Class, Interface, Delegates, Array etc.
Syntax
       Class A<T> where T : class 
Example
Valid InValid
A<MyClass>
A<InterfaceME>    
A<float[]>

A<int>
A<float>
Note :
Always come first when multiple constrain applied.

Value Type
Constrain ensure that type argument is Value Type. i.e int, float, struct, enum etc. But not nullable types.
Syntax
       Class A<T> where T : struct
Example
Valid
InValid
A<int>
A<float>     
A<Myclass>
A<InterfaceME>
Note :
Always come first when multiple constrain applied.

Constructor Type
Constrain ensure that type argument must have parameterless constructor to create instance of type argument. i.e any value type; nonstatic, nonabstract with parameterless constructor.
Syntax
       Class A<T> where T : new() 
Note :
Always come last when multiple constrain applied.
Derived Type
Constrain ensure that type argument must derived or implemented form specified type.
Syntax
       Class A<T> where T : MyClass
       Class A<T> where T : InterfaceME
Example
class A<T> where T : Stream
ValidInValid

A<MemoryStream> 
A<object>
A<string>
class A<T> where T : IDisposible
ValidInValid
A<DataTable> A<StringBuilder>
Points to remeber
You can specify multiple interface for type argument in this constrain but only one. Because no type can derived from more than once class.
ValidInValid
class A<T> where T : 
Stream,IDisposible,IEnumerable<T>
class A<T> where T :   
Stream,ArrayList,IEnumerable<T>
Note:
Specified class must not be struct, a sealed class
or not belonging to special type
System.Object
System.Enum
System.ValueType
System.Delegate

Summary
Its good to focus on Constrain type when you are implementing own custom types. This Constrain also applicable to generic methods with type argument.

2 comments: