Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 535
Matt Whitfield Avatar asked Mar 22 '10 21:03

Matt Whitfield


2 Answers

This is going to work in C# 4.0! What you are talking about is called generic covariance.

In the meantime you can use the Cast extension method:

List<IMyBar> interfaceList = new List<IMyBar>(classList.Cast<IMyBar>());
like image 133
mmx Avatar answered Sep 28 '22 02:09

mmx


This is supported in .NET 4.0 but not earlier.

http://msdn.microsoft.com/en-us/library/dd799517%28VS.100%29.aspx

like image 28
John Buchanan Avatar answered Sep 28 '22 02:09

John Buchanan