Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a interface as a type parameter of generic class with the limitation of "class" in C#

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?

like image 425
Tommy T Avatar asked Dec 29 '25 20:12

Tommy T


2 Answers

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.

like image 140
Lee Avatar answered Dec 31 '25 11:12

Lee


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'

like image 40
Jan Köhler Avatar answered Dec 31 '25 09:12

Jan Köhler