Hi all,
I'm still very new with C# and I have just started to get my head round objects.
What I would like to know is how would I program a way of making any number of objects and give each object a name like "Person_1" and "Person_2".
Is this even possible? I have tried the following but it doesn't work:
for (int i = 0; i < count; i++)
{
Player ("Player_" + i) = new Player();
}
Is there a better way to go about doing this? The big picture (if its any use) is my program reading from a text file using streamreader and creating an object every 6 lines (my object has 6 parameters). There will be a maximum of around 100 objects so I really would like a much more efficient way of creating these objects.
Many Thanks and Kind Regards,
James Webb
P.S. Please remember I'm a beginner, try to keep it as simple as possible and explain as much as you can, it would be very much appreciated!
VulpesPosted Jun 28, 2014, 2:38 PM
For example:
// array
int count = 100;
Player[] players = new Player[count]; // 100 elements from 0 to 99
for (int i = 0; i < count; i++)
{
players[i] = new Player();
// suppose the Player class has a Name property
players[i].Name = "Player_" + (i + 1);
}
// or list
List
for (int i = 0; i < count; i++)
{
Player player = new Player();
player.Name = "Player_" + i;
players.Add(player);
}
If you want to access, say, the 50th Player object, you can then do in either case:
Player Player_50 = players[49];