C
C#2y ago
arch_il

✅ List of inherited objects

I know that C# is strongly typed programming language and there are some limitations when it comes to what you can put in lists, but can you create a list of objects where each object is inherited from single class and have same constructor and function?
16 Replies
mtreit
mtreit2y ago
You can create a List that contains whatever you like Not sure what you're asking to be honest.
Anton
Anton2y ago
Not constructor, but method yes. Look into interfaces For creating objects people often use e.g. a factory delegate or class
arch_il
arch_ilOP2y ago
public class Foo
{
public virtual void Update() { }

public virtual void Draw() { }
}


public class InheritedFoo1 : Foo
{
public override void Update() { }

public override void Draw() { }
}

public class InheritedFoo2 : Foo
{
public override void Update() { }

public override void Draw() { }
}
public class Foo
{
public virtual void Update() { }

public virtual void Draw() { }
}


public class InheritedFoo1 : Foo
{
public override void Update() { }

public override void Draw() { }
}

public class InheritedFoo2 : Foo
{
public override void Update() { }

public override void Draw() { }
}
List<T> foos; where T : Foo
List<T> foos; where T : Foo
Something like this?
mg
mg2y ago
It would just be List<Foo>
arch_il
arch_ilOP2y ago
I mean that List contains InheritedFoo1 and InheritedFoo2 inside same list. both of them have same Update() and Draw() functions but with different parameters.
mg
mg2y ago
not if they have different parameters then they wouldn't be valid overrides
arch_il
arch_ilOP2y ago
they have same parameters and declarations, but different definitions
mg
mg2y ago
that's valid
arch_il
arch_ilOP2y ago
I know, I just need to somehow put 2 classes with same function declarations inside one list
mg
mg2y ago
If you declare List<Foo> foos;, you can add objects of any of the three types
arch_il
arch_ilOP2y ago
Really? Do I need any cast or anything? can List<Foo> contain InheritedFoo1 without any fancy shenanigans?
mg
mg2y ago
you might have to cast i forget man is there a linqpad equivalent for linux yeah you don't need a cast
SinFluxx
SinFluxx2y ago
I think List<Foo> is fine for the declaration, it will just be when you're accessing members that you'd need to cast to their concrete type
mg
mg2y ago
yeah, which will also involve checking if they are in fact the concrete type you expect them to be which you can do with pattern matching e.g. if (myFoo is InheritedFoo1 inherited1)
arch_il
arch_ilOP2y ago
Thanks for help. I guess not everything needs fancy lines to work
mg
mg2y ago
yw how does the bot know 👀
Want results from more Discord servers?
Add your server