Array.getLength() vs Array.getUpperBound()
-
getLength returns the total number of elements and getUpperBound returns the highest index number (getLength - 1) in most cases. getUpperBound can also be used on arrays of 2 or more dimensions to get the upper index of a dimension.
-
C++NewBe wrote:
Is there a difference between the two?
Yes. GetLength returns the number of items in the specified dimension. GetUpperBound returns the index of the last item in the specified dimension. For a one dimensional zero based array (which is the usual) that holds 10 items, GetLength(0) returns 10, while GetUpperBound(0) returns 9.
--- Year happy = new Year(2007);
-
Yes, GetUpperBound is used to get the boundaries of different dimensions of an array. Call GetUpperBound(0) to get the upper bound of the first dimension, GetUpperBound(1) for the second dimension and so on. It's in case you're using a 2-dimensional (or higher) array. Also, GetUpperBound returns the highest index of that array instead of the number of values in that array. So, whereas you would do
for (int i = 0; i < arr.Length; i++)
for length, you would do this for the upper bound:for (int i = 0; i <= arr.GetUpperBound(0); i++)