Alex Rivera | Logout

Why can I not assign a List of concrete types to a List of that concrete's interface?

Asked 2009-11-20T19:04:02.193
9

Why does this not compile?

public interface IConcrete { }

public class Concrete : IConcrete { }

public class Runner
{
    public static void Main()
    {
        var myList = new List<Concrete>();
        DoStuffWithInterfaceList(myList);  // compiler doesn't allow this
    }

    public static void DoStuffWithInterfaceList(List<IConcrete> listOfInterfaces) { }

}

And what's the quickest way to get myList to the correct type?

EDIT I messed up the DoStuffWithInterfaceList example

c#
Edit
Report

2 Answers

2

C# does not currently support converting generic types like that (it will be supported in C# 4, if I understand it correctly As wcoenen states in comments below, and Eric also clarifies in his answer, the only way to make it work in C#4 is to use IEnumerable<IConcrete>). For now you will need to convert your list in some way.

You could call the method like this:

DoStuffWithInterface(myList.ConvertAll<IConcrete>(n => n as IConcrete));

Update
I realized that you probably don't need the cast inside the lambda, even though I sort of like it for clarity. So this should also work:

DoStuffWithInterface(myList.ConvertAll<IConcrete>(n => n));
answered 2009-11-20T19:05:33.433
2

IList wouldn't work because IList isn't contravariant. It needs to be IEnumerable though again this only works in 4.0. You could also just use a ConvertAll with a lambda expression and that will work in 3.5

answered 2009-11-20T19:23:31.917

Your Answer