Generic constraint in C#

When you define a generic class, you can apply the generic type independent on a certain feature. In other word you help the client code by using constraint to not got error when instantiate the base Type which is not allowed in constraint condition. By constraining the type parameter, you increase the number of allowable operations and method calls to those supported.

Different kinds of constraints could be like these:

  1. Where T: Class
  2. Where T: struct
  3. Where T: new()
  4. Where T:<ClassName> , new()
  5. Where T:<InterfaceName> , new()

 

Where constraint :

Where clause:  specifies that constraints on the types that can be used as arguments for a type parameter defined in a generic declaration.

  1. Public Class GenericClass<T,U>  where T: BaseClass1 where U: BaseClass2
  2. {
  3. }
  4.  
  5. Public Class GenericClass<T> : where T: IBaseInterface<T>
  6. {
  7. }

 

New constrains:

New constraints means that  any type argument supplied must have an accessible parameterless constructor.

  1. Public Class MyClass<T> where T:new()
  2. {
  3. }

 

Note that The new() constraint appears last in the where clause. 

  1. Public Class MyClass<T> where T:Icomparable , new()
  2. {
  3. }

 

  1. Public Class MyClass <T> where T: BaseClass, IBaseInterface, IComparable<T> , new()
  2. {
  3. }

 

  1. Public Class MyClass <T,U> where T: class where : IBaseInterface , new()
  2. {
  3. }

 

I have used Generic constraints in a real world application sample before here . For more information you can see these References:

  1. http://msdn.microsoft.com/en-us/library/d5x73970.aspx
  2. http://www.dotnetperls.com/generic


Tags: C#


comments powered by Disqus