Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Size of a Three-dimensional array in C#
To get the size of a three-dimensional array in C#, you can use the GetLength() method to retrieve the size of individual dimensions, or the Length property to get the total number of elements across all dimensions.
Syntax
Following is the syntax for getting the size of specific dimensions −
array.GetLength(dimensionIndex)
Following is the syntax for getting the total number of elements −
array.Length
Parameters
-
dimensionIndex − A zero-based integer representing the dimension index (0 for first dimension, 1 for second dimension, 2 for third dimension).
Return Value
-
GetLength()returns anintrepresenting the number of elements in the specified dimension. -
Lengthreturns anintrepresenting the total number of elements in all dimensions combined.
Using GetLength() for Individual Dimensions
Example
using System;
class Program {
static void Main() {
int[,,] arr = new int[3, 4, 5];
Console.WriteLine("Dimension 0 (first): " + arr.GetLength(0));
Console.WriteLine("Dimension 1 (second): " + arr.GetLength(1));
Console.WriteLine("Dimension 2 (third): " + arr.GetLength(2));
Console.WriteLine("Total elements: " + arr.Length);
}
}
The output of the above code is −
Dimension 0 (first): 3 Dimension 1 (second): 4 Dimension 2 (third): 5 Total elements: 60
Using GetLength() with Dynamic Arrays
Example
using System;
class Program {
static void Main() {
string[,,] books = new string[2, 3, 4];
Console.WriteLine("Number of shelves: " + books.GetLength(0));
Console.WriteLine("Number of rows per shelf: " + books.GetLength(1));
Console.WriteLine("Number of books per row: " + books.GetLength(2));
int totalCapacity = books.GetLength(0) * books.GetLength(1) * books.GetLength(2);
Console.WriteLine("Library total capacity: " + totalCapacity);
Console.WriteLine("Using Length property: " + books.Length);
}
}
The output of the above code is −
Number of shelves: 2 Number of rows per shelf: 3 Number of books per row: 4 Library total capacity: 24 Using Length property: 24
Comparison of Methods
| Method | Purpose | Returns |
|---|---|---|
GetLength(0) |
Size of first dimension | Number of elements in dimension 0 |
GetLength(1) |
Size of second dimension | Number of elements in dimension 1 |
GetLength(2) |
Size of third dimension | Number of elements in dimension 2 |
Length |
Total array size | Product of all dimensions |
Conclusion
Use GetLength(dimensionIndex) to get the size of individual dimensions in a 3D array, where the dimension index ranges from 0 to 2. The Length property returns the total number of elements across all dimensions, which equals the product of all dimension sizes.
