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>
?
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>
?
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();
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: