Why does this not compile?
public interface IConcrete { }
public class Concrete : IConcrete { }
public class Runner
{
public static void Main()
{
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));
The accepted solution is quite inefficient for large lists, and completely unnecessary. You can change the signature of your method ever so slightly to make the code work without any conversions, either implicit or explicit:
public class Runner
{
public static void Main()
{
var myList = new List<Concrete>();
DoStuffWithInterfaceList(myList); // compiler doesn't allow this
}
public static void DoStuffWithInterfaceList<T>(List<T> listOfInterfaces)
where T: IConcrete
{ }
}
Notice that the method is now generic and uses a type constraint to ensure that it can only be called with lists of IConcrete
subtypes.