Search code examples
c#arraysinitializing

C# jagged array not initializing


Trying to make a 2D jagged array that has 10 columns and 10 rows. When I try to initialize the first column, it comes up with multiple errors and i'm not sure what i'm doing wrong.

class Program
{
    int[][] board = new int[10][];
    board[0] = new int[5];
    ...
}

Solution

  • You must place any code which is not a declaration into methods

    class Program
    {
        static int[][] board = new int[10][];
    
        static void Main()
        {
            board[0] = new int[10];
            ...
        }
    }
    

    Here board is a field of the class. You can also make it a local variable inside the method:

    class Program
    {
        static void Main()
        {
            int[][] board = new int[10][];
            board[0] = new int[10];
            ...
        }
    }
    

    The difference between a class field and a local variable is that the field can be accessed from outside if it is public and lives "forever" for static fields and as long the objects made from this class live for instance fields, while the local variable can be accessed only within the method and usually lives only as long as the method call lasts (not talking about special cases like iterator methods and so on).

    A jagged array is useful in two cases

    1. You have a structure which is not rectangular.
    2. You want to be able to assign it whole rows without using a loop.

    Otherwise I would use a 2-D array that you can initialize at once

    int[,] board = new int[10, 10];