Hi there I have a bit of a noob question about creating unique variable names in C#.
I would like to make an ArrayList of Enemy objects and I want to call each enemy “enemy[1]”
I would like to make a for loop and I would like to use the value of “i” to add on to the end of the word enemy.
so for instance:
forloop
{
Enemy enemy1 = new Enemy(actual parameters of the enemy class)
Enemy enemy2 = new Enemy();
Enemy enemy3 = new Enemy();
}
Any help would be appreciated.
Variables cannot be dynamically named as you desire, but by using arrays or lists (but please don’t use ArrayLists, more below!), you can access via indexes.
Create a
List<Enemy>(List<T>is found in System.Collections.Generic)Or if the collection does not need to be dynamically sized, you could use a simple array, of which there are several legal syntaxes for creation.
Then you can write your loop and access via the index
Or write a foreach loop
Your notion about using an
ArrayListis outdated as of C# 2.0+ (the current release on the market is C# 4.0), or Visual Studio 2005 (2010 is the current market version). It is preferrable to use the strongly typed generic collections found in the aforementioned System.Collections.Generic namespace.