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

后端 未结 6 1365
攒了一身酷
攒了一身酷 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: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]);
    }
    

提交回复
热议问题