How to get the length of row/column of multidimensional array in C#?

for 2-d array use this code :

var array = new int[,]
{
    {1,2,3,4,5,6,7,8,9,10 },
    {11,12,13,14,15,16,17,18,19,20 }
};
var row = array.GetLength(0);
var col = array.GetLength(1);

output of code is :

  • row = 2
  • col = 10

for n-d array syntax is like above code:

var d1 = array.GetLength(0);   // size of 1st dimension
var d2 = array.GetLength(1);   // size of 2nd dimension
var d3 = array.GetLength(2);   // size of 3rd dimension
.
.
.
var dn = array.GetLength(n-1);   // size of n dimension

Best Regards!


matrix.GetLength(0)  -> Gets the first dimension size

matrix.GetLength(1)  -> Gets the second dimension size

Have you looked at the properties of an Array?

  • Length gives you the length of the array (total number of cells).
  • GetLength(n) gives you the number of cells in the specified dimension (relative to 0). If you have a 3-dimensional array:

    int[,,] multiDimensionalArray = new int[21,72,103] ;
    

    then multiDimensionalArray.GetLength(n) will, for n = 0, 1 and 2, return 21, 72 and 103 respectively.

If you're constructing Jagged/sparse arrays, then the problem is somewhat more complicated. Jagged/sparse arrays are [usually] constructed as a nested collection of arrays within arrays. In which case you need to examine each element in turn. These are usually nested 1-dimensional arrays, but there is not reason you couldn't have, say, a 2d array containing 3d arrays containing 5d arrays.

In any case, with a jagged/sparse structure, you need to use the length properties on each cell.


Use matrix.GetLowerBound(0) and matrix.GetUpperBound(0).