2

For some context - this is an extension of an earlier question.

override List<baseClass> with List<derivedClass>

Anyway,

I have a generic base class "Scene"

public class Scene<T> where T: SceneModel { }

I also have two classes which inherit from this:

public class WorldScene : Scene<WorldModel> { }
public class BattleScene : Scene<BattleModel> { }

Now what I need to do is have a List<Scene<SceneModel>> which contains a mixture of WorldScene and BattleScene. Where I need the list I am obviously only needing to use the properties/methods common to WorldScene and BattleScene.

I get that they are two distinctly different objects - but given that they inherit from the same thing - I'm hoping there's some clever way of grouping them in this way without manually casting them to some third type.

Community
  • 1
  • 1
kaykayman
  • 373
  • 2
  • 13
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Nov 06 '12 at 00:31
  • Can you not just create a list of the parent class of both battlescene and worlscene. The parent would contain the common methods. Since both battelscene and worldscene are also their parent you can store them in the list and call the common methods. – yu_ominae Nov 06 '12 at 00:37

2 Answers2

5

If the methods and properties of Scene<T> allow for it, you can define a covariant generic interface IScene<out T> which Scene<T> implements:

public interface IScene<out T> where T : SceneModel { }
    // use of T is limited to return values and out parameters

public class Scene<T> : IScene<T> where T : SceneModel { }

List<IScene<SceneModel>> list = new List<IScene<SceneModel>>();
list.Add(new WorldScene());
list.Add(new BattleScene());

foreach (IScene<SceneModel> scene in list) ...

If not, you can use a non-generic interface or a non-generic base class, but then cannot include generic members in the definition:

public interface IScene { }
    // no T

public class Scene<T> : IScene where T : SceneModel { }

List<IScene> list = new List<IScene>();
list.Add(new WorldScene());
list.Add(new BattleScene());

foreach (IScene scene in list) ...
dtb
  • 213,145
  • 36
  • 401
  • 431
0

The problem is that WorldScene and BattleScene do not derive from the same common class: Scene<WorldModel> and Scene<BattleModel> are two different classes.

I would introduce a base class - or an interface - that declares the functionality you need to use:

public class Scene<T> : BaseScene where T: SceneModel { }

and then declare the list as List<BaseScene>

MiMo
  • 11,793
  • 1
  • 33
  • 48