I figured I could pass an IList<ChildClass> as an IEnumerable<ParentClass>, since obviously each object in a ChildType list is also an instance of ParentType. But I’m gettin no love from the compiler. What am I missing?
EDIT: Added function Foo3 which does what I want. Thanks!
namespace StackOverflow { public class ParentClass { } public class ChildClass : ParentClass { } public class Test { // works static void Foo(ParentClass bar2) { } // fails static void Foo2(IEnumerable<ParentClass> bar) { } // EDIT: here's the right answer, obtained from the // Charlie Calvert blog post static void Foo3<T>(IEnumerable<T> bar) where T : ParentClass { } public static void Main() { var childClassList = new List<ChildClass>(); // this works as expected foreach (var obj in childClassList) Foo(obj); // this won't compile // Argument '1': cannot convert from // 'System.Collections.Generic.List<ChildClass>' // to 'System.Collections.Generic.IEnumerable<ParentClass>' Foo2(childClassList); // EDIT: this works and is what I wanted Foo3(childClassList); } } }
Because generics aren’t co/contra variant:
Eric Lippert’s blog has a great post on this.
Another article from Charlie Calvert is here.