C# Tips

C# Tip Article

C# Multi-dimensional Array Size

When it comes to multi-dimensional array, C# supports two kinds 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. Depending on this array type, we get array size differently.

To get the total size of Rectangular Array, simply get .Length property value of the array as the same way of getting single-dimensional array size. To get size of each dimension, call GetLength(dimensionIndex) method.

// Rectangular Array Size  
string[,] names = { { "Tim", "Jack" }, { "Jane", "Aaron" } };            
int nameSize = names.Length;      // Size: 4

// To get size of a specific dimension
int secondDimSize = names.GetLength(1);  // Size: 2

But Jagged Array is different. If we 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, we should call .Length of the array element such as jagged[2].Length, instead of GetLength() method.