In Java, it is possible to bind the type parameter of a generic type. It can be done like this:
class A<T extends B> {
...
}
So, the type parameter for this generic class of A should be B or a subclass of B.
I wonder if C# has a similar feature. I appreciate if somebody let me know.
Thanks
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).
Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
A type parameter can have multiple bounds.
The same in C# is:
class A<T> where T : B
{
}
Also see "Constraints on Type Parameters" (msdn) for a great overview of constraints in general.
Very similar:
public class A<T> where T : B
{
// ...
}
This can be used to constrain T to be a sub-class or implementation of B (if B is an interface).
In addition, you can constrain T to be reference type, value type, or to require a default constructor:
where T : class // T must be a reference type
where T : struct // T must be a value type
where T : new() // T must have a default constructor
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