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
How to find the Rank of a given Array in C#?
The rank of an array in C# refers to the number of dimensions it has. A one-dimensional array has a rank of 1, a two-dimensional array has a rank of 2, and so on. To find the rank of any array, use the Rank property.
Syntax
Following is the syntax to get the rank of an array −
arrayName.Rank
Return Value
The Rank property returns an int value representing the number of dimensions in the array.
Using Rank Property with Different Array Types
Example 1: Single-Dimensional Array
using System;
class Demo {
static void Main() {
int[] singleArray = new int[5];
Console.WriteLine("Single-dimensional array rank: " + singleArray.Rank);
}
}
The output of the above code is −
Single-dimensional array rank: 1
Example 2: Multi-Dimensional Arrays
using System;
class Demo {
static void Main() {
int[,] twoDimensional = new int[3,3];
int[,,] threeDimensional = new int[2,3,4];
int[,,,] fourDimensional = new int[2,2,2,2];
Console.WriteLine("2D array rank: " + twoDimensional.Rank);
Console.WriteLine("3D array rank: " + threeDimensional.Rank);
Console.WriteLine("4D array rank: " + fourDimensional.Rank);
}
}
The output of the above code is −
2D array rank: 2 3D array rank: 3 4D array rank: 4
Example 3: Jagged Arrays vs Multi-Dimensional Arrays
It's important to note that jagged arrays (arrays of arrays) always have a rank of 1, regardless of how many levels of nesting they contain −
using System;
class Demo {
static void Main() {
int[][] jaggedArray = new int[3][];
int[,] multiDimArray = new int[3,3];
Console.WriteLine("Jagged array rank: " + jaggedArray.Rank);
Console.WriteLine("Multi-dimensional array rank: " + multiDimArray.Rank);
}
}
The output of the above code is −
Jagged array rank: 1 Multi-dimensional array rank: 2
Comparison: Jagged vs Multi-Dimensional Arrays
| Array Type | Declaration | Rank |
|---|---|---|
| Single-dimensional | int[] arr |
1 |
| Two-dimensional | int[,] arr |
2 |
| Jagged array | int[][] arr |
1 |
| Three-dimensional | int[,,] arr |
3 |
Conclusion
The Rank property in C# returns the number of dimensions in an array. Multi-dimensional arrays have ranks equal to their dimension count, while jagged arrays always have a rank of 1 since they are technically arrays of arrays, not true multi-dimensional structures.
