Search code examples
c#.netconsole-application

Assigning an Array from a Two-Dimensional Array - C#


I'm not understanding why the following code is raising CS0022: Wrong number of indices inside []; expected 2.

int[] oneArray; 
int[,] twoArray = { { 1, 2, 3 }, { 3, 2, 1 } };

oneArray = twoArray[0]; 

I have declared an array and am unable to assign it to an array from my two-dimensional array.

Maybe I'm too used to Python...I'd appreciate any information on the topic!


Solution

  • If you use Jagged Arrays then your above code would work.

    A jagged array is an array whose elements are arrays, possibly of different sizes. A jagged array is sometimes called an "array of arrays."

    A jagged array is typed using 2 sets of square brackets, eg. int[][], where each entry is an array that can be directly accessed and assigned to/from your variable.

    int[] oneArray;
    int[][] jaggedArray = { new int[] { 1, 2, 3 }, new int[] { 3, 2, 1 } };
    
    oneArray = jaggedArray[0];
    jaggedArray[0] = oneArray;