Cornelius Cornelius - 1 month ago 16
C# Question

Difference between array.GetLength(0) and array.GetUpperBound(0)

What is the difference between these two methods and when would you use one instead of the other?

int[,] array = new int[4,3];
int length0 = array.GetLength(0);
int upperbound0 = array.GetUpperBound(0);


MSDN says that GetLength return the number of elements where as GetUpperBound determine the max index, but how could this be different since arrays are initialized with elements for each index?

Answer

Take a look at this (rarely used) method. From MSDN:

public static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)

Creates a multidimensional Array of the specified Type and dimension lengths, with the specified lower bounds.

With it, you can create an array with indices from -5 ... +5. If you ever use this kind of array, then GetUpperBound() suddenly becomes a lot more useful than GetLength()-1. There also exists a GetLowerBound().

So, formally, all our

 for(int i = 0; i < a.Length; i++) 

loops should be

 for(int i = a.GetLowerBound(); i <= a.GetUpperBound(); i++)

but please don't do that.