Translate

Sunday, January 13, 2013

c# Generics type constraints tutorial

When you declare a generic method or a class there are 5 types of constraints that you can put on the generic type. I demonstrate all 5 with examples

1> T should be a reference type
Example:

class Person<T> where T:class
{

}


2>  T should be a value type
Example:

class Person<T> where T:struct
{

}

3>  T should have a public parameterless constructor.
Example


class Person<T> where T:new( )
{

}

This means you can call new on T without any parameters.

var x=new T( );

4>  T should inherit from a particular class or interface
Example

class Person<T> where T : StreamReader,IEnumerable
{


}


This means T should inherit from the StreamReader class and implement IEnumerable interface

5>Where T should inherit from another generic type

class Person<T1,T2> where T1 :T2
{


}

In my personal experience, the 4th constraint is the constraint that is used most often.

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator