Since IEnumerable has a covariant parameter in C# 4.0 I am confused how it is behaving in the following code.
public class Test
{
IEnumerable<IFoo> foos;
public void DoTestOne<H>(IEnumerable<H> bars) where H : IFoo
{
foos = bars;
}
public void DoTestTwo(IEnumerable<IBar> bars)
{
foos = bars;
}
}
public interface IFoo
{
}
public interface IBar : IFoo
{
}
So basically the DoTestOne method doesn’t compile while DoTestTwo does. In addition to why it doesn’t work, if anyone knows how I can achieve the effect of DoTestOne (assigning an IEnumberable<H> where H : IFoo to an IEnumberable<IFoo>) I would appreciate the help.
If you know that H will be a class, this does work:
The issue here is that if H is a value type, the covariance is not exactly what you’d expect, as
IEnumerable<MyStruct>actually returns the value types whereasIEnumerable<IFoo>has to return boxed instances. You can use an explicitCast<IFoo>to get around this, if necessary.