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?
An example of GetLength is GetLength(0) , which returns the number of elements in the first dimension of the Array.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With