Multi-dimensional Array Size in C#

By FoxLearn 11/10/2024 2:26:30 AM   2
In C#, multi-dimensional arrays are arrays with more than one dimension. These arrays are declared using a comma-separated list of dimensions in square brackets.

C# supports two types of multi-dimensional arrays:

Rectangular Array which has fixed element size for each dimension and Jagged Array that can have different element size for each dimension.

To get the total size of a rectangular array in C# you can use the .Length property, just like a single-dimensional array. It returns the total number of elements across all dimensions.

To get the size of each individual dimension you can use the GetLength(dimensionIndex) method, where dimensionIndex specifies which dimension's size you want.

// Rectangular Array Size  
string[,] names = { { "John", "Tom" }, { "Jane", "Barron" } };            
int nameSize = names.Length;      // Size: 4
 
// To get size of a specific dimension
int secondDimSize = names.GetLength(1);  // Size: 2

A Jagged Array is different. If you check out .Length property of Jagged Array, it will return the size of the first array dimension. This is because Jagged Array is per se single-dimensional array that has array(s) in each element.

//Jagged Array Size            
int[][] jagged = new int[3][];            
jagged[0] = new int[2];
jagged[1] = new int[3] { 1, 2, 3 };
jagged[2] = new int[4] { 1, 2, 3, 4 };
 
int jaggedSize = jagged.Length;    // Size: 3
int thirdSize = jagged[2].Length;  // Size: 4  

And to get the size of a specific dimension of Jagged Array, you should call .Length of the array element such as jagged[2].Length, instead of GetLength() method.