Multi-dimensional Array Size in C#
By Tan Lee Published on Nov 10, 2024 255
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.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization