What are Constraints in C# Generics

In the previous post, What are Generics in C#?, you learned that Generics allow you to define a class or method with placeholders for the type of its fields, methods, parameters, etc.

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.

Comments

Popular posts from this blog

Why can't Microsoft install IIS on Window Operating Systems by default?

Exam 70-487: Accessing Data - How to choose the Appropriate Data Access Technology - Entity Framework?

Exam 70-487: Accessing Data - How to choose the Appropriate Data Access Technology - Azure Cosmos DB?