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.
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>());
This is supported in .NET 4.0 but not earlier.
http://msdn.microsoft.com/en-us/library/dd799517%28VS.100%29.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With