Josh Siegl
Josh Siegl

Reputation: 735

Is there any way to access variables from a child class given a list of objects defined as the parent?

i'm currently working on a little game and I have a question about OOP practices. My question is is there any way to access variables from child classes if you have a list or an array of objects which are of the parent type.

I'm currently in a CS course at school right now so I don't have my source code on me but it's been bugging me, I'm not quite sure what i'm supposed to be looking for here either, possibly a cast? my OOP knowledge is a little scattered (it's pretty hard to find good resources on OOP other than Stack Overflow, point me in the direction of a good tutorial if you know of one) but I want to implement good practices so I don't run into problems down the road (it's a rather large project)

Let me illustrate what I mean here (again I don't have my source on me, but it's something like this):

    List<Tile> Tiles = new List<Tile>(); 
    Tiles.add(new Water()); 
    Tiles.add(new Sand()); 

    foreach(Tile tile in Tiles)
    {
         tile.variable_fromsand = 10; //hypothetical, how could I access a public
                                      //member from sand here, if at all
    }

where water and sand are sub-classes of the base class Tile.

I'm sorry if this has been answered before, I'm not sure what it is that i'm looking for. Please point me to the correct thread if this has been answered adequately in the past.

Upvotes: 2

Views: 1232

Answers (4)

Khan
Khan

Reputation: 18162

Casting would work.

foreach(Tile tile in Tiles)
{
    if (tile is Sand)
         ((Sand)tile).variable_fromsand = 10; 
}

Upvotes: 3

user27414
user27414

Reputation:

If I understand you correctly, Sand inherits from Tile, and you want to read one of its properties when iterating through a list of Tiles.

You can cast to do this in your foreach loop:

var sand = Tile as Sand;
if (sand != null)
{
    // do something with the property of Sand.
}

By using as, you're casting to Sand only if the tile variable is actually of type Sand. If you have Water objects in there, the as will return null, and you won't have the property your're looking for.

Upvotes: 2

Austin Salonen
Austin Salonen

Reputation: 50235

You could do something like this but I would question the abstraction. Since you don't specify what you're actually doing, it's quite a bit harder to give a "this is what you should do answer."

foreach(var sand in Tiles.OfType<Sand>())
{
}

Upvotes: 1

Zbigniew
Zbigniew

Reputation: 27614

You can try casting it, or selecting just Sand tiles:

// if tile is Sand then use casting
foreach(Tile tile in Tiles)
{
     if(tile is Sand)
     {
         ((Sand)tile).variable_fromsand = 10;
     }
}

// select only tiles which are of Sand type
foreach(Sand tile in Tiles.OfType<Sand>())
{
     tile.variable_fromsand = 10;
}

Upvotes: 3

Related Questions