C
C#13mo 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
mtreit13mo ago
You can create a List that contains whatever you like Not sure what you're asking to be honest.
Anton
Anton13mo 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_il13mo 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
mg13mo ago
It would just be List<Foo>
arch_il
arch_il13mo 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
mg13mo ago
not if they have different parameters then they wouldn't be valid overrides
arch_il
arch_il13mo ago
they have same parameters and declarations, but different definitions
mg
mg13mo ago
that's valid
arch_il
arch_il13mo ago
I know, I just need to somehow put 2 classes with same function declarations inside one list
mg
mg13mo ago
If you declare List<Foo> foos;, you can add objects of any of the three types
arch_il
arch_il13mo ago
Really? Do I need any cast or anything? can List<Foo> contain InheritedFoo1 without any fancy shenanigans?
mg
mg13mo ago
you might have to cast i forget man is there a linqpad equivalent for linux yeah you don't need a cast
SinFluxx
SinFluxx13mo 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
mg13mo 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_il13mo ago
Thanks for help. I guess not everything needs fancy lines to work
mg
mg13mo ago
yw how does the bot know 👀
Want results from more Discord servers?
Add your server
More Posts