Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override List<baseClass> with List<derivedClass>

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?

like image 665
kaykayman Avatar asked Oct 27 '12 23:10

kaykayman


People also ask

How to add override keyword in C#?

In C#, a method in a derived class can have the same name as a method in the base class. You can specify how the methods interact by using the new and override keywords. The override modifier extends the base class virtual method, and the new modifier hides an accessible base class method.

Where to use override in C#?

The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into a derived class. The new keyword is used to hide a method, property, indexer, or event of base class into derived class.

How to inherit a base class in C#?

Inheritance (Derived and Base Class) In C#, it is possible to inherit fields and methods from one class to another. We group the "inheritance concept" into two categories: Derived Class (child) - the class that inherits from another class. Base Class (parent) - the class being inherited from.

Why we need overriding in C#?

If derived class defines same method as defined in its base class, it is known as method overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the method which is already provided by its base class.


2 Answers

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.

like image 187
Sergey Berezovskiy Avatar answered Oct 04 '22 02:10

Sergey Berezovskiy


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.

like image 39
SLaks Avatar answered Oct 04 '22 01:10

SLaks