6

I have base classes like this:

public class Scene
{
    public IList<SceneModel> Models {get; set;}
}

public class SceneModel { }

and derived classes like this:

public class WorldScene : Scene
{
    public override IList<WorldModel> Models {get; set;}
}

public class WorldModel : SceneModel { }

So my question is, how do I manage this. As it stands the compiler isn't happy with this (and to be honest it looks a bit weird to me anyway). So is what I'm trying to do impossible? And if so, why? Or is it possible and I'm just going about it the wrong way?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
kaykayman
  • 373
  • 2
  • 13
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – John Saunders Nov 06 '12 at 00:31

2 Answers2

10

You can use generics

public class BaseScene<T>
    where T : SceneModel
{
    public IList<T> Models {get; set;}
}

public class Scene : BaseScene<SceneModel>
{
}

public class WorldScene : BaseScene<WorldModel>
{    
}

Each type of scene will be parametrized by corresponding model type. Thus you will have strongly typed list of models for each scene.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
2

This is fundamentally impossible.

What would happen if you write

Scene x = new WorldScene();
x.Models.Add(new OtherModel());

You just added an OtherModel to a List<WorldModel>.

Instead, you should make the base class generic.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964