Finding the last index of an array

后端 未结 11 2192
不思量自难忘°
不思量自难忘° 2020-12-10 00:43

How do you retrieve the last element of an array in C#?

11条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 01:00

    To compute the index of the last item:

    int index = array.Length - 1;
    

    Will get you -1 if the array is empty - you should treat it as a special case.

    To access the last index:

    array[array.Length - 1] = ...
    

    or

    ... = array[array.Length - 1]
    

    will cause an exception if the array is actually empty (Length is 0).

提交回复
热议问题