Array of Arrays

Bali C picture Bali C · Jun 19, 2011 · Viewed 29.3k times · Source

How do you create an array of arrays in C#? I have read about creating jagged arrays but I'm not sure if thats the best way of going about it. I was wanting to achieve something like this:

string[] myArray = {string[] myArray2, string[] myArray3}

Then I can access it like myArray.myArray2[0];

I know that code won't work but just as an example to explain what I mean.

Thanks.

Answer

love Computer science picture love Computer science · Jun 19, 2011

Simple example of array of arrays or multidimensional array is as follows:

int[] a1 = { 1, 2, 3 };
int[] a2 = { 4, 5, 6 };
int[] a3 = { 7, 8, 9, 10, 11 };
int[] a4 = { 50, 58, 90, 91 };

int[][] arr = {a1, a2, a3, a4};

To test the array:

for (int i = 0; i < arr.Length; i++)
{
    for (int j = 0; j < arr[i].Length; j++)
    {
        Console.WriteLine("\t" +  arr[i][j].ToString());
    }
}