public interface I {
}
public class A : I {
}
The compiler takes explicit IEnumerable<A> as IEnumerable<I> :
public void Test() {
IEnumerable<A> a = new List<A>();
new List<I>().AddRange(a);
}
But with generic constraints, we get:
public void Test<T>() where T : I {
IEnumerable<T> t = new List<T>();
new List<I>().AddRange(t);
}
^^^
Argument 1: cannot convert from 'IEnumerable<T>' to 'IEnumerable<I>'
However, this compiles fine.
public void Test<T>(T t) where T : I {
new List<I>().Add(t);
}
Hence the question: is this a correct behavior, or is it a bug?
The problem is that generic covariance only applies for reference types. For example, a
List<int>is not* anIEnumerable<Comparable>, but aList<string>is.So if you constrain
Tto be a reference type, it compiles: