casting generic list to generic list of interfaces  
Author Message
Lehmberg





PostPosted: .NET Base Class Library, casting generic list to generic list of interfaces Top

I have a class looking somwhat like this:

public class TestClass : IMyInterface

{

}

and a generic list:

List<TestClass> list = new List<TestClass>();

list.Add(new TestClass());

Now I want to cast my list to a list of interfaces:

List<IMyInterFace> list1 = (List<IMyInterFace>)list;

That doesn't work

List<IMyInterFace> list1 = list;

Doesn't work either. It is easy to cast the individual elements in the list but not the entire list. Howcome

Best regards

Alex



.NET Development1  
 
 
Mattias Sjogren





PostPosted: .NET Base Class Library, casting generic list to generic list of interfaces Top

Because there's no inheritance relation between List<X> and List<Y> even if there is one between X and Y.

Also keep in mind that if such a cast was possible, you would then be able to do list1.Add(new SomeOtherIMyInterfaceImplementation()) which would violate the type of your list object.

As a workaround, perhaps you can create a new list with List<T>.ConvertAll