Search code examples
c#.netlistienumerable

A Solution For (IEnumerable<Base>)Derive; Yet?


Possible Duplicate:
C# Cannot convert from IEnumerable<Base> to IEnumerable<Derived>

I have D1 and D2 which derive from B. When i write var ls = (IEnumerable<B>)(cond?lsD1:lsD2); I get a runtime cast error. IIRC this is a well known problem. My question is

1) Is this allowed yet? perhaps in .NET 4? I have 2010 but my project is a few months old, large and targets 3.5.

2) Is there a simple workaround? I only need to read the list not add anything or remove. Actually, ToArray() would probably work but is there another solution?


Solution

  • So if I'm reading your question correctly, this is an example of covarience. C# 4 supports this for some interfaces IEnumerable being one of them.

    The workaround in C# 3 would probably be something along the lines of:

    var ls = (IEnumerable<B>)(cond ? lsD1.Cast<B>() : lsD2.Cast<B>());
    

    Turning them into arrays would also work, but only because variance is "broken" (see section: Broken array variance) for arrays.