(This is .Net 3.5) I have a class FooList which implements IList and a class FooClass which implements IFoo. A user requires IList<IFoo>. In my implementation, I create a FooList<FooClass>, called X. How do I code my return so that my FooList<FooClass> X becomes his IList<IFoo>?
If I try
return X.Cast( ).ToList( );
he gets an IList<IFoo>, but it is not my FooList; it is a List, and a new one at that.
This isn’t going to work out, because a
FooList<FooClass>is not anIList<IFoo>. This is why:You need to either make a copy or use an interface that is actually covariant on the contained type, like
IEnumerable<T>instead ofIList<T>. Or, if appropriate, you should declare yourFooList<FooClass>as anFooList<IFoo>from the get-go instead.Here is a small implementation that demonstrates my second suggestion: