Indexoutofrangeexception in C#

Can anyone help me to figure out the problem?

struct Player
{
    public string Name;
    public int X;
    public int Y;
}
static Player[] players = new Player[amountofPlayers];

static void ResetGame() {
    Console.WriteLine("Welcome to the game!");
    Console.Write("How many player will be taking part today: ");
    string playerNo = Console.ReadLine();
    amountofPlayers = int.Parse(playerNo);
    if (amountofPlayers <= 4)
    {
        for (int i = 0; i < amountofPlayers; i = i + 1)
        {
            int displayNumber = i + 1;
            Console.Write("Please enter the name of player " + displayNumber + ": ");
            players[i].Name = Console.ReadLine(); //error is here
        }
    }
    else
    {
        Console.WriteLine("Please enter a number of players less than 4!");
    }
}

static int amountofPlayers;
Jon Skeet
people
quotationmark

This line:

static Player[] players = new Player[amountofPlayers];

is executing before you assign a value to amountOfPlayers based on the user input. So amountOfPlayers has its default value of 0, and you're creating an array of 0 elements.

I suggest you just declare the variable:

 static Player[] players;

then make amountOfPlayers a local variable in your ResetGame method, initializing the array after you've asked how many players there are:

static void ResetGame() {
    Console.WriteLine("Welcome to the game!");
    Console.Write("How many player will be taking part today: ");
    string playerNo = Console.ReadLine();
    int amountofPlayers = int.Parse(playerNo);
    players = new Player[amountOfPlayers];
    ...
}

I' also suggest making Player a class instead of a struct, keeping fields private, and using properties instead.

people

See more on this question at Stackoverflow