Search code examples
c#loopsconsolespace-efficiency

how to make a certain number of variables with a different name?


I've started programming in C# to develop some console applications and I was wondering how I could make a certain number of variables with a different name in a more efficient way. For now I'm doing something like this:

for(int i=1; i<=x; i++)
    switch(i) {
        case 1:
            Player player1=new Player(i, x);
            break;
        case 2:
            Player player2=new Player(i, x);
            break;
        case 3:
            Player player3=new Player(i, x);
            break;
        case 4:
            Player player4=new Player(i, x);
            break;
        case 5:
            Player player5=new Player(i, x);
            break;
        case 6:
            Player player6=new Player(i, x);
            break;
    }

I'm just wondering whether there are more effecient ways to solve this and what those ways are.


Solution

  • You'd be better off making an array:

    var players = new Player[x];
    for (int i = 0; i < x; i++)
    {
        players[i] = new Player(i, x);
    }
    

    or use Linq:

    var players = Enumerable.Range(0, x)
                            .Select(i => new Player(i, x))
                            .ToArray();
    

    You can then reference the players you created with.

    var player1 = players[0]; // Note: array indexes start at 0
    

    Of course, you may not actually need to use arrays, specifically. Many other collection classes might suit your problem better.

    Further reading: