1

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 subclass 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

4
  • what does "B is a child of A" mean? In the code listing you've given, A and B are type parameters. Commented Mar 16, 2011 at 0:18
  • What do you mean by "child"? Do you mean "derived class"? Commented Mar 16, 2011 at 0:18
  • ok, but in your example, A and B are the type parameters used in the definitions of types Foo and Bar. This is quite confusing. Commented Mar 16, 2011 at 10:17
  • OK. Consider A = Shape and B = Circle. I want to load a list of circles into a list of shapes and save a list of shapes that I know are all circles. Circle is derived from Shape. Commented Mar 16, 2011 at 22:20

2 Answers 2

3

Use .NET 4.0 and IEnumerable<T> instead of List<T> (http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx), otherwise make Save generic on T (the list item type) as well.

Sign up to request clarification or add additional context in comments.

2 Comments

I see that IEnumerable is what I need but sadly I can't use .NET 4.0. Bah!
Then I'd make class Bar generic: class Bar<T> where T : A { void Save(List<T> ComplexItems); List<T> Load(); } and instantiate it with Bar<B>. Alternatively make just the methods themselves generic (may be easier especially with type inference): void Save<T>(List<T> ComplexItems) where T : A; List<T> Load<T>(); where T : A }
1

If you can change your save function to take an IEnumerable then you can :

void Save(IEnumerable<B> ComplexItems);
Save(MyFoo.Items.Cast<B>());

1 Comment

Thanks. What about the Load function?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.