Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting variables from inherited class in c#

I have a problem where i have a list of one class (DrawableGameComponent) with many instances of different types of classes inherited from DrawableGameComponent.

The thing is i want to access a variable from one of those classes, but since they are declared as a DrawableGameComponent, i can't access any other variable than DrawableGameComponent has.

main class:

List<DrawableGameComponent> entities = new List<DrawableGameComponent>();

"player" class:

public Color color;
public int score;

any idea of how i can access these variables from the main class?

like image 357
Ask I. Nator Avatar asked Jan 30 '26 14:01

Ask I. Nator


1 Answers

If DrawableGameComponent is base for Player you can do this:

foreach(DrawableGameComponent entity in entities)
{
    Player player = entity as Player;
    if(player != null)
    {
        Color col = player.color;
        int score = player.score;
    }
}

Beacause 'is', 'as' and casting are relatively expensive it is preferred to do it just once - as above.

like image 115
Maciej Avatar answered Feb 01 '26 14:02

Maciej



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!