In C#, GetUpperBound(dimension) returns the largest valid index for that dimension. For a normal 1D array of length N starting at 0, the upper bound is N - 1.
Use it with GetLowerBound when writing loops that must support arrays with custom bounds.
This is an instance member of System.Array. You call it on an array variable with a dot, such as arr.GetUpperBound(...). Arrays in C# have a fixed length after creation; use List<T> when the count must grow.
Syntax
Call GetUpperBound with the dimension index.
C#
int last = nums.GetUpperBound(0);
Call
What it does
nums.GetUpperBound(0)
Last valid index of dimension 0.
grid.GetUpperBound(1)
Last column index for a 2D array.
Upper bound is an index, not a length. Length 3 → upper bound 2 when lower bound is 0.
Library declarations
C#
public int GetUpperBound(int dimension);
Parameters
Parameter
Description
dimension
Required. 0-based dimension index.
Return Value
Return Value
Description
int
Last valid index for that dimension.
C# Examples
Example 1 — Last Index of a 1D Array
Print upper bound beside Length.
C#
using System;
class Program {
static void Main() {
string[] names = { "Ann", "Bob", "Cara" };
Console.WriteLine("Length: " + names.Length);
Console.WriteLine("Upper: " + names.GetUpperBound(0));
}
}
Output
Length: 3
Upper: 2
How It Works
Three elements. Length is 3.
Last index 2. Upper bound is Length - 1 here.
Do not loop to Upper wrongly. for (i = 0; i <= upper; i++) works; i < Length also works.
Zero-based. Lower bound is 0.
Example 2 — Upper Bounds of a Matrix
Show last row and column indexes.
C#
using System;
class Program {
static void Main() {
int[,] grid = new int[2, 4];
Console.WriteLine(grid.GetUpperBound(0));
Console.WriteLine(grid.GetUpperBound(1));
}
}
Output
1
3
How It Works
2 rows → upper 1. Indexes 0 and 1.
4 cols → upper 3. Indexes 0..3.
Not lengths. Lengths are 2 and 4 via GetLength.
Loop inclusive. for (c = 0; c <= GetUpperBound(1); c++).
Example 3 — Loop From Lower to Upper
Inclusive bounds loop style for dimension 0.
C#
using System;
class Program {
static void Main() {
int[] nums = { 7, 8, 9 };
int lo = nums.GetLowerBound(0);
int hi = nums.GetUpperBound(0);
for (int i = lo; i <= hi; i++) {
Console.Write(nums[i] + " ");
}
Console.WriteLine();
}
}
Output
7 8 9
How It Works
Inclusive end. Use <= with upper bound.
Lower start. Works even if lower bound were non-zero.
All elements. 7, 8, 9 print.
Alternative. for (i = 0; i < Length; i++) on zero-based arrays.
Frequently Asked Questions
The last valid index for the given dimension.
No. For a zero-based array, upper bound is typically Length - 1 for that dimension’s size.
for (int i = arr.GetLowerBound(d); i <= arr.GetUpperBound(d); i++).
Yes. Pass the dimension you care about.
Upper bound can be less than lower bound for empty dimensions in some cases—check Length first.