Generic Type Constraints: Where Keyword in C#

Hi, it is another rainy and pleasant day here in INDIA.

Today, i am going to set focus on Generic Type Constraints in c#.

OK. now what is the Constraints! Constraints are keep things in place or things become out of control otherwise.programming is not exception to this rule.

By adding the constraints, our generic class can only be instantiated with the conditions specified using where keyword. It is also referred to as a constraint on the generic types.

Lets look at following sample code,

//line 1
namespace ConsoleApplication1
{
    //line 2
    class Program
    {
        //line 3
        static void Main(string[] args)
        {
            //line 4
            GenericClass<string> obj = new GenericClass<string>();
 
        }
    }
    //line 5
    public class GenericClass<T> where T : class
    {
 
    }
}

 

1.So, we have a generic class GenericClass with generic parameter type T.

2. we apply the constraint on it with the type parameter T, that is being used with the generic class that must be of class(reference type).

3.since we have restricted the use of this class with a class(reference) type only, by adding the where keyword i.e.

public class GenericClass<T> where T : class

.

4.suppose we change line no.4 as following,

//line 4
            GenericClass<int> obj = new GenericClass<int>();

 

here we break the constraint applied on generic class GenericClass, which is result in following error

The type ‘int’ must be a reference type in order to use it as parameter ‘T’ in the generic type or method ‘ConsoleApplication1.GenericClass<T>’.

Here, i am provide the basic of Generic Type Constraints. you can refer following link to go in  depth.

http://www.c-sharpcorner.com/UploadFile/b1df45/generic-type-constraint-where-keyword-in-C-Sharp/

 

Thanks.

 

One thought on “Generic Type Constraints: Where Keyword in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s