Generic Constraints in C#

In c#, generics are used to define a class or structure or methods with 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 a 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 the above class, we created a class (GenericClass) with one parameter (msg) and method (genericMethod) using type parameter (T) as a 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.

 

If we want to restrict a generic class to accept only the particular type of placeholder, then we need to use Constraints. Using Constraints, we can specify what type of placeholder the generic class can accept, and the compiler will throw a compile-time error. 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 the where keyword. The 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 of 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 the 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 the above code, we created an instance of GenericClass using reference type arguments such as string and class. If we uncomment the commented code, we will get a compile-time error because int is a value type, not a reference type.

C# Multiple Generic Constraints

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

 

public class GenericClass<T, X> where T: class where X: struct
{
    // Your Implementation
}

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

C# Generic Methods with Constraints

In c#, you can also apply constraints on generic methods based on our requirements. Following is the example of adding constraints on generic methods 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 the c# programming language.

 

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