Why can you use an interface as the type parameter of a generic class where the constraint is class?
interface IB {}
class A<T> where T : class {}
...
A<IB> a; // why is IB allowed here?
Either a reference type or a value type can implement an interface, so you shouldn't be able to use an interface as the type parameter, since the interface declaration is not as "strong" as the limitation.
But in the above example it works without a problem. Why is this allowed? Is the actual object implementing the interface being boxed in the process if it is a value type?
Any variable typed as an interface type is a reference type, if the implementing type is a value type it will be boxed e.g.
IConvertible c = 3;
will cause the value 3 to be boxed when assigned to c.
If you have a generic type A<T> and T is an interface type, any reference to T inside A will also be a reference type so the class constraint is satisfied.
Have a look at the docs:
where T : class
The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
What you're probably looking for is the new()-constraint:
where T : new()
The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.
If you use that
class A<B> where B : new()
then IB cannot be used as a parameter:
Error CS0310 'IB' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'A'
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