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:
2> T should be a value type
Example:
Example
4> T should inherit from a particular class or interface
Example
This means T should inherit from the StreamReader class and implement IEnumerable interface
5>Where T should inherit from another generic type
In my personal experience, the 4th constraint is the constraint that is used most often.
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( );
This means you can call new on T without any parameters.
var x=new T( );
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
{
}
No comments:
Post a Comment
Comments will appear once they have been approved by the moderator