Type parameter constraints
The type parameters in a generic type or method can be replaced by any valid type. However, there are scenarios when we want to restrict the types that can be used for a type parameter. Take, for instance, the generic Shape<T>
class or the IShape<T>
interface we saw earlier.
The type parameter T
was used for the type of the Area
property. We would expect that to be either an integral type or a floating-point type. But there is no restriction and someone could use bool
, string
, or any other type. Of course, depending on the way the type parameter is used, that could lead to various compiler errors. However, it is useful to be able to restrict the types used to instantiate generic types or call generic methods.
For this purpose, we can apply constraints to the type parameters. The constraints are used to inform the compiler about what kind of capabilities the type parameter must have. If we do not specify a constraint, then the type parameter...