Search code examples
c#arraysmultidimensional-arrayinitialization

Initializing multidimensional arrays in c# (with other arrays)


In C#, it's possible to initialize a multidimensional array using constants like so:

Object[,] twodArray = new Object[,] { {"00", "01", "02"}, 
                                      {"10", "11", "12"},
                                      {"20", "21", "22"} };

I personally think initializing an array with hard coded constants is kind of useless for anything other than test exercises. Anyways, what I desperately need to do is initialize a new multidimensional array as above using existing arrays. (Which have the same item count, but contents are of course only defined at runtime).

A sample of what I would like to do is.

Object[] first  = new Object[] {"00", "01", "02"};
Object[] second = new Object[] {"10", "11", "12"};
Object[] third  = new Object[] {"20", "21", "22"};
Object[,] twodArray = new Object[,] { first, second, third };

Unfortunately, this doesn't compile as valid code. Funny enough, when I tried

Object[,] twodArray = new Object[,] { {first}, {second}, {third} };

The code did compile and run, however the result was not as desired - a 3 by 3 array of Objects, what came out was a 3 by 1 array of arrays, each of which had 3 elements. When that happens, I can't access my array using:

Object val = twodArray[3,3];

I have to go:

Object val = twodArray[3,1][3];

Which obviously isn't the desired result.

So, is there any way to initialize this new 2D array from multiple existing arrays without resorting to iteration?


Solution

  • This would work if you switched to jagged arrays:

    int[] arr1 = new[] { 1, 2, 3 };
    int[] arr2 = new[] { 4, 5, 6 };
    int[] arr3 = new[] { 7, 8, 9 };
    
    int[][] jagged = new[] { arr1, arr2, arr3 };
    
    int six = jagged[1][2];
    

    Edit To clarify for people finding this thread in the future

    The code sample above is also inadequate as it results in an array of arrays (object[object[]]) rather than a jagged array (object[][]) which are conceptually the same thing but distinct types.