views:

44

answers:

2

Why wouldn't DoesntWork() work below? The error is: Cannot implicitly convert type 'List' to 'IEnumerable'. An explicit conversion exists (are you missing a cast?). I know this is something about generic/templates I'm not getting, but List is IEnumerable and Implementer is an IInterface. I don't see why this needs to be casted (or if it really can be).

public interface IInterface
{
    // ...
}

public class Implementer : IInterface
{
    // ...
}

IEnumerable<IInterface> DoesntWork()
{
    List<Implementer> result = new List<Implementer>();
    return result;
}
+3  A: 

It has to do with covariance. Here's a nice blog post. If you are not using 4.0 you will have to cast the list using the System.Linq Cast method.

Adam Driscoll
+2  A: 

This works with Net 4.0: public interface IEnumerable<out T> : IEnumerable out is contravariant