How to resize multidimensional (2D) array in C#?

Most methods in the array class only work with one-dimensional arrays, so you have to perform the copy manually:

T[,] ResizeArray<T>(T[,] original, int rows, int cols)
{
    var newArray = new T[rows,cols];
    int minRows = Math.Min(rows, original.GetLength(0));
    int minCols = Math.Min(cols, original.GetLength(1));
    for(int i = 0; i < minRows; i++)
        for(int j = 0; j < minCols; j++)
           newArray[i, j] = original[i, j];
    return newArray;
}

To understand why it doesn’t work with Array.Copy, you need to consider the layout of a multidimensional array in memory. The array items are not really stored as a bidimensional array, they’re stored contiguously, row after row. So this array:

{ { 1, 2, 3 },
  { 4, 5, 6 } }

Is actually arranged in memory like that: { 1, 2, 3, 4, 5, 6 }

Now, assume you want to add one more row and one more column, so that the array looks like this:

{ { 1, 2, 3, 0 },
  { 4, 5, 6, 0 },
  { 0, 0, 0, 0 } }

The layout in memory would now be as follows: { 1, 2, 3, 0, 4, 5, 6, 0, 0, 0, 0, 0 }

But Array.Copy treats all arrays as one-dimensional. MSDN says:

When copying between multidimensional arrays, the array behaves like a long one-dimensional array, where the rows (or columns) are conceptually laid end to end

So when you try to copy the original array to the new one, it just copies one memory location to the other, which gives, in one-dimensional representation:

{ 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }.

If you convert that to a two-dimensional representation, you get the following:

{ { 1, 2, 3, 4 },
  { 5, 6, 0, 0 },
  { 0, 0, 0, 0 } }

This is why you’re getting a screwed up array… Note that it would work property if you changed the number of rows, but not the number of columns.

Leave a Comment