What are Constraints in C# Generics
Remember the following generic class?
GenericList is up to a lot of unknown things during instantiation ( it can be primitive or non-primitive type, or an interface or custom class etc.), and to limit the type of "Whatever" T is, as we discussed previously, GenericList can decide to limit the field of possibilities for T.
For instance, the following will no longer allow a collection of int to be instantiated: the "where T: class" is called a Constraint on the GenericList class.
Below is a list of all the possible constraints. Once again:
- Constraints specifies the kind of types allowed with the generics.
- Constraints can be applied using the where keyword.
- Six types of constraints can be applied: class, struct, new(), base class name, interface and derived type.
- Multiple constraints also can be applied.