views:

57

answers:

2

I have 3 different classes, a generic "entity" class, and then two classes that inherit this, a bullet class and an enemy class.

I then have a list of the entity class, with the bullets and enemies in the list, and a lot of the places I treat these the same. However, some times, I want to loop through just one of the classes, and not the other, e.g. Loop through each bullet, but not the enemies. Is there any way to do this?

I tried

foreach (Bullet tempBullet in entities)

But I get the error

Unable to cast object of type 'Enemy' to type 'Bullet'.

Anyone know if this is possible, or do I have to use seperate lists?

+4  A: 

You can probably use a little Linq:

foreach (var bullet in entities.OfType<Bullet>())
{

}
Matthew Abbott
Thanks, looks like that worked!
Darkfrost
+1  A: 

If you're using .NET 2:

foreach (Entity ent in entities) {
    Enemy e = ent as Enemy;
    Bullet b = ent as Bullet;

    if (e != null) {
        // process enemy
    }
    else if (b != null) {
        // process bullet
    }
}

or, using linq (and entities is an object that inherits IEnumerable<T>):

foreach (Bullet bullet in entities.OfType<Bullet>()) {
    // process bullets only
}
thecoop
Or you could use also if (ent is Enemy) ...
jv42
But then you're doing two casts, as you're presumably doing a `(Enemy)ent` later on.
thecoop