In C#, GetLength(dimension) returns how many elements exist along one dimension of the array. Dimension 0 is the first dimension.
For a 1D array, GetLength(0) matches Length. For 2D arrays, use GetLength(0) and GetLength(1) instead of assuming a single Length splits evenly.
This is an instance member of System.Array. You call it on an array variable with a dot, such as arr.GetLength(...). Arrays in C# have a fixed length after creation; use List<T> when the count must grow.
Syntax
Call GetLength with the dimension index starting at 0.
C#
int rows = grid.GetLength(0);
int cols = grid.GetLength(1);
Call
What it does
grid.GetLength(0)
Number of elements in dimension 0 (often “rows”).
grid.GetLength(1)
Number of elements in dimension 1 (often “columns”).
Total elements across all dimensions is still available as Length (product for rectangular arrays).
Library declarations
C#
public int GetLength(int dimension);
Parameters
Parameter
Description
dimension
Required. 0-based dimension index. Must be < Rank.
Return Value
Return Value
Description
int
Length of that dimension.
C# Examples
Example 1 — Rows and Columns
Print both dimensions of a rectangular array.
C#
using System;
class Program {
static void Main() {
int[,] grid = new int[2, 3];
Console.WriteLine("Rank: " + grid.Rank);
Console.WriteLine("GetLength(0): " + grid.GetLength(0));
Console.WriteLine("GetLength(1): " + grid.GetLength(1));
Console.WriteLine("Length: " + grid.Length);
}
}
Output
Rank: 2
GetLength(0): 2
GetLength(1): 3
Length: 6
How It Works
Rank 2. Two dimensions exist.
2 rows. GetLength(0) is 2.
3 columns. GetLength(1) is 3.
Length 6. Total cells = 2 × 3.
Example 2 — Loop With GetLength
Visit every cell using dimension lengths.
C#
using System;
class Program {
static void Main() {
string[,] grid = {
{ "A", "B", "C" },
{ "D", "E", "F" }
};
for (int r = 0; r < grid.GetLength(0); r++) {
for (int c = 0; c < grid.GetLength(1); c++) {
Console.Write(grid[r, c] + " ");
}
Console.WriteLine();
}
}
}
Output
A B C
D E F
How It Works
Outer rows. r runs to GetLength(0).
Inner cols. c runs to GetLength(1).
Safe bounds. Loops stay inside the matrix.
Print rows. Newline after each row.
Example 3 — GetLength(0) Matches Length
On a vector, dimension 0 is the only length.
C#
using System;
class Program {
static void Main() {
int[] nums = { 1, 2, 3, 4 };
Console.WriteLine(nums.GetLength(0));
Console.WriteLine(nums.Length);
}
}
Output
4
4
How It Works
One dimension. Rank is 1.
Same number. GetLength(0) equals Length.
Prefer Length. For 1D, Length is the usual property.
API consistency. GetLength still works.
Frequently Asked Questions
The number of elements in the specified dimension as an int.
Length is the total number of elements. GetLength(d) is the size of one dimension.
0 for the first dimension, 1 for the second, and so on, up to Rank - 1.
Yes. GetLength(0) equals Length.
When a dimension might exceed Int32.MaxValue (rare). GetLongLength returns long.