I have a class called Foo that has a function that looks like the following
List<Bar> LoadData();
Both Foo and Bar are in a library that I want to reuse in other projects. Now I am working on a new project and I want to subclass Bar. Let’s call it NewBar.
What is a simple and flexible way to get Foo.LoadData to return a list of NewBar? I think that a factory is needed or perhaps just a delegate function. Can anyone provide an example?
Thanks, Andy
There are a few problems here. Since you are using
List<Bar>this would not work if you returnList<Baz>sinceList<>does not do covariance.My suggestion is to redesign it to return
IEnumerable<Bar>and make itvirtualso that in the new project create aSubFooand you can returnIEnumerable<Baz>.UPDATE
OK, according to the new information you provided (you use it for populating list from XML), I would create a
virtual protected CreateBar()which creates a new bar object and is called by LoadData() to create newBarin the loop. In theSubFooI override and returnBazinstead. In theSubFooI will callbase.LoadData()and populate theBazlist and then add the logic to populate new properties ofBazwhich are not inBar.Or perhaps
just use XML Serilization and I get all of that for free!