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.
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#.
Constraint | Description |
---|---|
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. |
Following is the example of defining a generic class with constraint using where contextual keyword in c# programming language.
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#.
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.
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.
If you observe the above code snippet, we added multiple constraints on generic class (GenericClass) using where keyword.
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.
Following are the important points which we need to remember about generic constraints in the c# programming language.