C#, Generic Lists and Inheritance

Posted by Andy on Stack Overflow See other posts from Stack Overflow or by Andy
Published on 2011-03-16T00:07:42Z Indexed on 2011/03/16 0:10 UTC
Read the original article Hit count: 188

Filed under:
|
|
|
|

I have a class called Foo that defines a list of objects of type A:

class Foo {
    List<A> Items = new List<A>();
}

I have a class called Bar that can save and load lists of objects of type B:

class Bar {
    void Save(List<B> ComplexItems);
    List<B> Load();
}

B is a child of A. Foo, Bar, A and B are in a library and the user can create children of any of the classes.

What I would like to do is something like the following:

Foo MyFoo = new Foo();
Bar MyBar = new Bar();

MyFoo.Items = MyBar.Load();
MyBar.Save(MyFoo.Items);

Obviously this won't work. Is there a clever way to do this that avoids creating intermediate lists?

thanks, Andy

© Stack Overflow or respective owner

Related posts about c#

Related posts about design