tags:

views:

102

answers:

2

I know I can cast an object from its own type to its interface type like so:

IMyInterface myValue = (IMyInterface)MyObjectThatImplementsMyInterface;

How can I cast IList<MyClassThatImplementMyInterface> to IList<IMyInterface>?

+6  A: 

I answered the same question yesterday, although for base classes rather than interfaces.

The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:

IList<A> listOfA = new List<C>().ConvertAll(x => (A)x);

You could also use Linq:

IList<A> listOfA = new List<C>().Cast<A>().ToList();
Mark Byers
A: 

This doesn't help you now, but note that C# 4.0 will introduce co/contravariance for interfaces so you'll be able to directly cast certain collection interfaces. Though I'm not sure if IList<> will be one of them (the interface has to be 'safely' covariant/contravariant)

Some links:

Use Covariance and Contravariance in VS 2010 Part I?

Use Covariance and Contravariance in VS 2010 Part II?

Phil