I've seen <:
, >:
, <%
, etc. Can someone give (or locate) a good description of these? What are the possible constraints, what do they do, and what's an example of when to use them?
C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.
Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.
The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.
A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)
S <: T
means that S
is a subtype of T
. This is also called an upper type bound. Similarly, S >: T
means that S
is a supertype of T
, a lower type bound.
S <% T
is a view bound, and expresses that S
must come equipped with a view that maps its values into values of type T
.
It's confusing for me too, and I have a Masters in programming languages from Berkeley.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With