I have a interface that inherits from IList:
public interface IBase {}
public class Derived : IBase {}
public interface IMyList : IList<IBase> {}
I want to cast a variable of type IMyList to type IList<Derived> or List<Derived>, whichever is easier or makes the most sense. What’s the best way to do this?
Note that I’m using .NET 3.5
A direct cast isn’t going to be suitable since there are numerous problems that could occur (
IMyListmay contain types other thanDerived, etc.)As long as you’re not modifying the list (in which case,
IEnumerable<Derived>would work) you could simply:And then iterate over the result.
Edit
Based on the OP’s comment below, there are two other things to mention:
1) If you need an
IList<Derived>, you could simply add to the above and callmyList.Cast<Derived>().ToList();2) If those are truly the requirements, then your code doesn’t make any sense. If
IMyListshould only ever containDerivedobjects thenIMyListshould derive fromIList<Derived>. Remember that while you know that there is only one type implementing theIBaseinterface, the compiler doesn’t so be specific.Using interfaces everywhere just for the sake of using interfaces doesn’t help anybody!