✅ 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
You can create a List that contains whatever you like
Not sure what you're asking to be honest.
Not constructor, but method yes. Look into interfaces
For creating objects people often use e.g. a factory delegate or class
Something like this?
It would just be
List<Foo>
I mean that List contains
InheritedFoo1
and InheritedFoo2
inside same list. both of them have same Update()
and Draw()
functions but with different parameters.not if they have different parameters
then they wouldn't be valid overrides
they have same parameters and declarations, but different definitions
that's valid
I know, I just need to somehow put 2 classes with same function declarations inside one list
If you declare
List<Foo> foos;
, you can add objects of any of the three typesReally? Do I need any cast or anything?
can
List<Foo>
contain InheritedFoo1
without any fancy shenanigans?you might have to cast i forget
man is there a linqpad equivalent for linux
yeah you don't need a cast
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
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)
Thanks for help. I guess not everything needs fancy lines to work
yw
how does the bot know 👀