Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Most methods in the array class only work with one-dimensional arrays, so you have to perform the copy manually:</p> <pre><code>T[,] ResizeArray&lt;T&gt;(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 &lt; minRows; i++) for(int j = 0; j &lt; minCols; j++) newArray[i, j] = original[i, j]; return newArray; } </code></pre> <p>To understand why it doesn't work with <code>Array.Copy</code>, you need to consider the layout of a multidimensional array in memory. The array items are not <em>really</em> stored as a bidimensional array, they're stored contiguously, row after row. So this array:</p> <pre><code>{ { 1, 2, 3 }, { 4, 5, 6 } } </code></pre> <p>Is actually arranged in memory like that: <code>{ 1, 2, 3, 4, 5, 6 }</code></p> <p>Now, assume you want to add one more row and one more column, so that the array looks like this:</p> <pre><code>{ { 1, 2, 3, 0 }, { 4, 5, 6, 0 }, { 0, 0, 0, 0 } } </code></pre> <p>The layout in memory would now be as follows: <code>{ 1, 2, 3, 0, 4, 5, 6, 0, 0, 0, 0, 0 }</code></p> <p>But <code>Array.Copy</code> treats all arrays as one-dimensional. MSDN says:</p> <blockquote> <p>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</p> </blockquote> <p>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:</p> <p><code>{ 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }</code>.</p> <p>If you convert that to a two-dimensional representation, you get the following:</p> <pre><code>{ { 1, 2, 3, 4 }, { 5, 6, 0, 0 }, { 0, 0, 0, 0 } } </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload