I’ve come across a problem where I’d like to create an Array table. That is a 2 dimensional array where the number of rows and columns are known at runtime before the table needs to be created. The number of columns is the same for all rows.
Once the array is created I’d like to operate on just 1 dimension of that array. Perhaps pass a reference to an method.
Here is a fictional example:
// Create a table 3x3 table.
int[,] DistanceTable = new int[3, 3];
DistanceTable[0, 0] = 0;
DistanceTable[1, 1] = 0;
DistanceTable[2, 2] = 0;
DistanceTable[0, 1] = 10;
DistanceTable[0, 2] = 40;
DistanceTable[1, 0] = 10;
DistanceTable[1, 2] = 25;
DistanceTable[2, 0] = 40;
DistanceTable[2, 1] = 25;
// Why can't I do this?
int[] twos = DistanceTable[2];
If I were to use a JaggedArray (Array-of-Arrays) it lets me do this. But I don’t need a JaggedArray because my multidemsional array always has the same number of columns for each row.
Is it possible to do this? If not why?
Thanks
No. Multidimensional arrays differ from Jagged arrays in that they are stored sequentially, in one block of memory, using Row-Major ordering.
Because of this, pulling out one “column” of data requires skipping in order to pull this out.
Jagged arrays, on the other hand, are an array of references to a second array. This makes it easy to pull out individual “arrays” from the jagged array.
Jagged arrays in .NET have some huge performance optimizations. They often outperform multidimensional arrays. This is why most code analysis routines will suggest conversion to a jagged array from a two dimensional array. It would be worth considering this even if you don’t “need” it.