In my game I have an Enemy class, and in that I have a constructor which I use to make Enemy objects.

How do I add all Enemy objects to a list or loop through all of them using a foreach loop?

I have tried various variations of this:

foreach(object E in Enemy){
        //Do collision detection, set AIs next move, etc.

However, it always rejects the second part of the foreach loop, saying that Enemy is a type but is used as a variable.


1 Answer 1


The error you state is correct, 'Enemy' is a type. What you have there is equivalent to 'foreach (object E in integer)' or 'foreach (object E in string)'.

You need to add the enemy instances to a list or array. It should be roughly:

//Creating enemies
List<Enemy> enemyList = new List<Enemy>();

Enemy e = new Enemy();


then to iterate:

foreach (Enemy anEnemy in enemyList)
 if (anEnemy.IsDoingWhatever)

  • \$\begingroup\$ I take it there is no automatic way to add all enemys to enemyList? \$\endgroup\$
    – James G.
    Commented Jan 5, 2014 at 4:48
  • 1
    \$\begingroup\$ There's no magical way, no. The simplest way might be to use a factory sort of pattern when you create them (an EnemyManager class or something like that). The 'Enemy' class is just another class... each enemy object just another object. \$\endgroup\$
    – DrHeinous
    Commented Jan 5, 2014 at 5:04
  • 3
    \$\begingroup\$ @JamesG You wouldn't want to do this. There are many scenarios where you want to have more than one list. So which list do they get added to? Best to make it explicit, as per the answer. \$\endgroup\$ Commented Jan 5, 2014 at 5:04

Not the answer you're looking for? Browse other questions tagged .