Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create List<genericBaseClass<T>> from various List<derivedClass<T>>

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.

like image 549
kaykayman Avatar asked Jan 20 '26 03:01

kaykayman


1 Answers

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) ...
like image 175
dtb Avatar answered Jan 21 '26 17:01

dtb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!