Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 975
Cornelius Avatar asked Aug 26 '11 09:08

Cornelius


People also ask

What does GetLength 0 mean?

An example of GetLength is GetLength(0) , which returns the number of elements in the first dimension of the Array.

What is the difference between an array's GetLength method and an array's length property in C#?

Length property returns the number of elements in an array, whether it be one dimensional or multidimensional. That is a 2x6 array will have length of 12. The . GetLength(0) method returns number of elements in the row direction in a multidimensional array.

What is GetUpperBound in VB?

GetUpperBound(0) returns the last index in the first dimension of the array, and GetUpperBound(Rank - 1) returns the last index of the last dimension of the array. This method is an O(1) operation.

What is GetLength C#?

GetLength(Int32) Method is used to find the total number of elements present in the specified dimension of the Array. Syntax: public int GetLength (int dimension);


1 Answers

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

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().

But the C# support for this kind of arrays is low, you cannot use []. You would only need those methods in combination with the Array.GetValue() and SetValue() methods.

like image 72
Henk Holterman Avatar answered Oct 14 '22 16:10

Henk Holterman