Search code examples
c#arraysvisual-studiomultidimensional-array

Is it possible to change the dimensions of an array while a c# program is running?


You can specify the dimensions of an array using static ints like so:

static int VertRows = 3;
static int HorRows = 3;
int[,] gameBoard = new int[VertRows, HorRows];

But is there a way to change the dimensions of gameBoard when the script starts, or while it's running?


Solution

  • 'Static' doesn't mean that you can't alter the numbers. That would be 'const'. Static, basically, means that it can be accessed from anywhere in your project by saying something like:

    MyClass.gameBoard
    

    You can alter the dimensions of an array at runtime, static or not, but you must do it in a specific way. When you say

    int[,] gameBoard = new int[VertRows, HorRows];
    

    The gameBoard is set to whatever numbers are in VertRows and HorRows. If this is outside a method, the gameBoard is already in place before the program starts. If it is inside, this creates a temporary gameBoard that lasts until the end of the method. Though you can modify either one by invoking 'gameBoard' on its own. It is important for newbies to know that:

    new int[VertRows, HorRows];
    

    Is a command that fires once, not a persistent program running in the background that is constantly updated. That means that you can't simply alter the numbers set in VertRows and HorRows and have the gameBoard change as well. What you have to do is create a 'method' to reset the gameBoard. Like so:

    private void SetGameboard(int height, int width)
    {
        gameBoard = new int[height, width];
    }
    

    Note that this destroys the gameBoard totally and makes a new one, so you can also use this to clear the board.