[c#] Finding the last index of an array

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

This question is related to c# arrays

The answer is


New in C# 8.0 you can use the so-called "hat" (^) operator! This is useful for when you want to do something in one line!

var mystr = "Hello World!";
var lastword = mystr.Split(" ")[^1];
Console.WriteLine(lastword);
// World!

instead of the old way:

var mystr = "Hello World";
var split = mystr.Split(" ");
var lastword = split[split.Length - 1];
Console.WriteLine(lastword);
// World!

It doesn't save much space, but it looks much clearer (maybe I only think this because I came from python?). This is also much better than calling a method like .Last() or .Reverse() Read more at MSDN

Edit: You can add this functionality to your class like so:

public class MyClass
{
  public object this[Index indx]
  {
    get
    {
      // Do indexing here, this is just an example of the .IsFromEnd property
      if (indx.IsFromEnd)
      {
        Console.WriteLine("Negative Index!")
      }
      else
      {
        Console.WriteLine("Positive Index!")
      }
    }
  }
}

The Index.IsFromEnd will tell you if someone is using the 'hat' (^) operator


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


Array starts from index 0 and ends at n-1.

static void Main(string[] args)
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int length = arr.Length - 1;   // starts from 0 to n-1

    Console.WriteLine(length);     // this will give the last index.
    Console.Read();
}

LINQ provides Last():

csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();              
5

This is handy when you don't want to make a variable unnecessarily.

string lastName = "Abraham Lincoln".Split().Last();

The following will return NULL if the array is empty, else the last element.

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

Also, starting with .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index type to keep array's indexes from end:

var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];

You can use this index to get last array value in any lenght of array. For example:

var firstArray = new[] {0, 1, 1, 2, 2};
var secondArray = new[] {3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5};
var index = ^1;
var firstArrayLastValue = firstArray[index]; // 2
var secondArrayLastValue = secondArray[index]; // 5

For more information check documentation


With C# 8:

int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5

Is this worth mentioning?

var item = new Stack(arr).Pop();

say your array is called arr

do

arr[arr.Length - 1]

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.