Covariance in interfaces and collections

Viewed 50

I'm trying to understand why the following doesn't work. Would anybody please care to explain?

The compiler warns that it "cannot convert from SomethingImpl to ISomething<IParam>", but the covariant definition of ISomething<TParam> does specify that TParam implements IParam , and the definition of ParamImpl implements IParam, hence I would conclude that ISomething<ParamImpl> can be stored in the list that expects elements of type ISomething<IParam>

void Main()
{
    var list = new List<ISomething<IParam>>();
    
    var myThing = new SomethingImpl();
    list.Add(myThing); // compiler complains about this line.
    list.Dump();
}

interface IParam {
}

interface ISomething<in TParam> where TParam : IParam 
{
}

class ParamImpl : IParam
{
}

class SomethingImpl : ISomething<ParamImpl>
{
}
0 Answers
Related