What Are The 3 Main Constraints in .Net Generics ? Can You Briefly Explain Each ?

Answer

The 3 main .Net Generics constraints that I know of are

  1. Interface constraint
  2. Base class constraint (includes Reference and Value Type constraints)
  3. Constructor constraint

An interface constraint specifies an interface with which all type arguments to the parameter must be compatible. Any number of interface constraints can apply to a given type parameter.

A base class constraint is similar to an interface constraint, but each type parameter can only include a single base class constraint. If no constraint is specified for a type parameter, then the implicit base class constraint of System.Object is applied. There are two specializations of the base class constraint called the reference type constraint and the value type constraint. A reference type constraint specifies that the argument may specify any reference type, and the value type constraint indicates that the type argument is limited to value types.

The constructor constraint makes it possible for generic code to create instances of the type specified by a type parameter by constraining type arguments to types that implement a public default constructor.

, , , {0}

Leave a Reply