Generic Constraints in C#

In c#, generics are used to define a class or structure or methods with a placeholders (type parameters) to indicate that they can use any of the types.

 

Following is the example of defining a generic class with type parameter (T) as placeholder with an angle (<>) brackets.

 

public class GenericClass<T>

{

    public T msg;

    public void genericMethod(T name, T location)

    {

        Console.WriteLine("{0}", msg);

        Console.WriteLine("Name: {0}", name);

        Console.WriteLine("Location: {0}", location);

    }

}

If you observe above class, we created a class (GenericClass) with one parameter (msg) and method (genericMethod) using type parameter (T) as placeholder with an angle (<>) brackets. Here the defined GenericClass doesn’t know anything about the defined placeholder and it will accept any type either string or int or class, etc. based on our requirements.

 

In case, if we want to restrict a generic class to accept only the particular type of placeholder, then we need to use Constraints. By using Constraints, we can specify what type of placeholder the generic class can accept and the compiler will throw a compile-time error in case, if we try to instantiate a generic class with the placeholder type that is not allowed by a constraint.

 

In c#, constraints are specified by using where keyword. Following table lists a different type of constraints available in c#.

 

ConstraintDescription
where T : struct The type argument must be a value type.
where T : unmanaged The type of argument must not be a reference type.
where T : class The type argument must be a reference type.
where T : new() The type argument must have a public parameterless constructor.
where T : <base class name> The type argument must be or derive from the specified base class.
where T : <interface name> The type argument must be or implement the specified interface.
where T : U The type argument supplied for T must be or derive from the argument supplied for U.

C# Generic Class with Constraints Example

Following is the example of defining a generic class with constraint using where contextual keyword in c# programming language.

 

public class GenericClass<T> where T: class

{

    public T msg;

    public void genericMethod(T name, T location)

    {

        Console.WriteLine("{0}", msg);

        Console.WriteLine("Name: {0}", name);

        Console.WriteLine("Location: {0}", location);

    }

}

If you observe above code, we defined a class (GenericClass) with where T: class constraint so the GenericClass will accept only reference type arguments.

 

Following is the example of instantiating a generic class with valid reference type arguments such as string or class in c#.

 

// Instantiate Generic Class with Constraint

GenericClass<string> gclass = new GenericClass<string>();

GenericClass<User> gclass1 = new GenericClass<User>();

// Compile Time Error

//GenericClass<int> gclass11 = new GenericClass<int>();

If you observe above code, we created an instance of GenericClass using reference type arguments such as string and class. In case, if we uncomment the commented code, then we will get a compile time error because int is a value type, not a reference type.

C# Multiple Generic Constraints

In c#, we can apply a multiple constraints on generic classes based on our requirements. Following is the code snippet of adding a multiple constraints to generic class.

 

public class GenericClass<T, X> where T : class where X : struct

{

    // Your Implementation

}

If you observe above code snippet, we added a multiple constraints on generic class (GenericClass) using where keyword.

C# Generic Methods with Constraints

In c#, we can also apply a constraints on generic methods based on our requirements. Following is the example of adding a constraints on generic method using where keyword.

 

public class GenericClass<T> where T : class

{

    public T msg;

    public void genericMethod<X>(T name, T location) where X : class

    {

        Console.WriteLine("{0}", msg);

        Console.WriteLine("Name: {0}", name);

        Console.WriteLine("Location: {0}", location);

    }

}

C# Generic Constraints Overview

Following are the important points which we need to remember about generic constraints in c# programming language.

 

  • In c#, constraints are used to restrict a generics to accept only the particular type of placeholders.
  • By using where keyword, we can apply a constraints on generics.
  • In c#, we can apply a multiple constraints on generic class or methods based on our requirements.
  • In c#, we have a different type of constraints available, those are classstructure, unmanaged, new(), etc.
 

PREVIOUS

Generics in C#