tags:

views:

1140

answers:

5

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

+3  A: 

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).

sharptooth
+1  A: 

say your array is called arr

do

arr[arr.Length - 1]
Cambium
A: 

The following is torretant of empty arrays and will return NULL if the array is empty, else the last element.

var item = (arr.Length == 0) ? null : arr[arr.Length - 1]
Nippysaurus
+2  A: 

The array has a Length property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1.

string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;

When declaring an array in C#, the number you give is the length of the array:

string[] items = new string[5]; // five items, index ranging from 0 to 4.
Fredrik Mörk
+1  A: 

Use Array.GetUpperBound(0). Array.Length contains the number of items in the array, so reading Length -1 only works on the assumption that the array is zero based.

Simon Svensson