Why does a function that takes IEnumerable<interface> not accept IEnumerable<class>?

Posted by Matt Whitfield on Stack Overflow See other posts from Stack Overflow or by Matt Whitfield
Published on 2010-03-22T21:27:39Z Indexed on 2010/03/22 21:31 UTC
Read the original article Hit count: 350

Say, for instance, I have a class:

public class MyFoo : IMyBar
{
    ...
}

Then, I would want to use the following code:

List<MyFoo> classList = new List<MyFoo>();
classList.Add(new MyFoo(1));
classList.Add(new MyFoo(2));
classList.Add(new MyFoo(3));

List<IMyBar> interfaceList = new List<IMyBar>(classList);

But this produces the error:

`Argument '1': cannot convert from 'IEnumerable<MyFoo>' to 'IEnumerable<IMyBar>' 

Why is this? Since MyFoo implements IMyBar, one would expect that an IEnumerable of MyFoo could be treated as an IEnumerable of IMyBar. A mundane real-world example being producing a list of cars, and then being told that it wasn't a list of vehicles.

It's only a minor annoyance, but if anyone can shed some light on this, I would be much obliged.

© Stack Overflow or respective owner

Related posts about ienumerable

Related posts about generics