1

Can we define an array of 2D array in C# of this manner? Or any alternate approach to obtain similar dataset?

double[][,] testArray = new double[a][b,c];

Note: All the three indices - a,b and c are obtained in runtime.

Thanks

1
  • 1
    You can only declare one array dimension at a time. new double[a][,] is valid, while your declaration is not. You can then loop across the outer dimension to populate the inner arrays. Commented Sep 13, 2017 at 20:12

2 Answers 2

8

You can do it, but you have to initialize each 2D array separately :

double[][,] testArray = new double[a][,];
for(int i = 0; i < a; i++)
{
    testArray[i] = new double[b, c];
}

Another way is to just declare a 3D array:

double[,,] testArray3D = new double[a, b, c];

That is, you can make that change if every 2D array you wanted in the beginning is to have the same dimensions

Sign up to request clarification or add additional context in comments.

Comments

4

Sure.

int[][,] arrayOf2DArrays = 
{
    new int[,] {{1, 2, 3}, {4, 5, 6}},
    new int[,] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}},
    new int[,] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13, 14, 15}}
};

This is essentially a one-dimensional jagged array that contains three two-dimensional arrays, each of different size.

The elements can be accessed in the following manner:

var element = arrayOf2DArrays[0][0, 0]; // etc
Console.WriteLine(element);

..and arrayOf2DArrays.Length will, in the example above, return 3, as arrayOf2DArrays contains three two-dimensional arrays.

Jagged Arrays (C# Programming Guide) - MSDN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.