When you define a generic class, you can apply the generic type independent on a certain feature. In other words, you help the client code by using constraint to not got the error when instantiating the base Type which is not allowed in constraint condition. By constraining the type parameter, you increase the number of allowable operations and method calls to those supported.
Different kinds of constraints could be like these:
- Where T: Class
- Where T: struct
- Where T: new()
- Where T:<ClassName> , new()
- Where T:<InterfaceName> , new()
Where constraint :
Where clause: specifies that constraints on the types that can be used as arguments for a type parameter defined in a generic declaration.
Public Class GenericClass<T,U> where T: BaseClass1 where U: BaseClass2 { } Public Class GenericClass<T> : where T: IBaseInterface<T> { }
New constraints:
New constraints mean that any type argument supplied must have an accessible parameterless constructor.
Public Class MyClass<T> where T:new() { }
Note that The new() constraint appears last in the where clause.
Public Class MyClass<T> where T:Icomparable , new() { } Public Class MyClass <T> where T: BaseClass, IBaseInterface, IComparable<T> , new() { } Public Class MyClass <T,U> where T: class where : IBaseInterface , new() { }
I have used Generic constraints in a real-world application sample before here. For more information you can see these References: