-3

I am trying to assign values to a 2D array using 2 for loops. Here is my code:

void Test()
    {
        int[,] grid = { { 0 } };

        for (int x = 0; x <= 7; x++)
        {
            for (int y = 0; y <= 7; y++)
            {
                grid[x, y] = x * y;
            }
        }
    }

However, I get a System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' after the for loops. What is causing this and how can I fix it?

1 Answers1

0

As stated in the comments: you are initializing the array as a 1x1 array but you are trying to access its elements from 0-7 in both dimensions. You can simply initialize the array as int[,] grid = new int[8,8]; and then access the elements the way you are doing it right now.

In case you need it: C# initializes int arrays with the value 0 (since you are explicitly intializing it with 0).

For value types, the array elements are initialized with the default value, the 0-bit pattern; the elements will have the value 0

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/

Bronzila
  • 1
  • 1