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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With