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

后端 未结 6 1282
攒了一身酷
攒了一身酷 2020-12-28 15:02

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(         


        
相关标签:
6条回答
  • 2020-12-28 15:24

    GetUpperBound returns the highest index in the array, the GetLength returns the number of elements of the array.

    i.e. GetUpperBound = GetLength - 1

    0 讨论(0)
  • 2020-12-28 15:31

    Array.Length returns the length of the array (number of elements) you need to subtract 1 from it to get the UpperBound.

    Array.GetUpperBound(0) returns the upper bound of the array, you can use it as is.

    0 讨论(0)
  • 2020-12-28 15:35

    Generally, array.GetUpperBound(0) = array.Length - 1, but since we can create arrays that have a Nonzero lower bound, that is not always true.

    0 讨论(0)
  • 2020-12-28 15:42

    if lower bound of your array is 0 then you can use either of them without any confusion but i would recommend array.length-1 as it is widely used. however, if the lower bound of your array is less than 0 then you should use array.GetUpperBound(0) because in this case array.length-1 != array.getUpperBound(0)

    0 讨论(0)
  • 2020-12-28 15:47

    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.

    0 讨论(0)
  • 2020-12-28 15:47

    I realise this is an old question but I think it's worth emphasising that GetUpperBound returns the upper boundary of the specified dimension. This is important for a multidimensional array as in that case the two functions are not equivalent.

    // Given a simple two dimensional array
    private static readonly int[,] USHolidays =
    {
        { 1, 1 },
        { 7, 4 },
        { 12, 24 },
        { 12, 25 }
    };
    

    The Length property will output 8 as there are 8 elements in the array.

    Console.WriteLine(USHolidays.Length);
    

    However, the GetUpperBound() function will output 3 as the upper boundary of the first dimension is 3. In other words I can loop over array indexes 0, 1, 2 and 3.

    Console.WriteLine(USHolidays.GetUpperBound(0));
    for (var i = 0; i <= USHolidays.GetUpperBound(0); i++)
    {
        Console.WriteLine("{0}, {1}", USHolidays[i, 0], USHolidays[i, 1]);
    }
    
    0 讨论(0)
提交回复
热议问题