In C#, Array.LastIndexOf searches from the end of the array (or from a starting index backward) and returns the last position that equals your value.
If the value is absent, the result is -1. Use it when duplicates exist and you care about the rightmost match.
This is a static member of System.Array. You call it with the class name, such as Array.LastIndexOf(...). Arrays in C# have a fixed length after creation; use List<T> when the count must grow.
Syntax
Pass the array and value. Compare the result with -1.
C#
int ix = Array.LastIndexOf(nums, 30);
Call
What it does
Array.LastIndexOf(nums, 30)
Last index of 30, or -1.
Array.LastIndexOf(nums, 30, 3)
Search backward starting from index 3.
Pair with IndexOf when you need both the first and last positions.
Library declarations
C#
public static int LastIndexOf(Array array, object value);
public static int LastIndexOf<T>(T[] array, T value);
Parameters
Parameter
Description
array
Required. Array to search.
value
Required. Value to find.
startIndex
Optional. Index to start searching backward from.
Return Value
Return Value
Description
index
Last matching position.
-1
Not found.
C# Examples
Example 1 — Find the Last Duplicate
Two 30s exist; LastIndexOf returns the later one.
C#
using System;
class Program {
static void Main() {
int[] nums = { 30, 10, 30, 20 };
int ix = Array.LastIndexOf(nums, 30);
Console.WriteLine("Last 30 at " + ix);
Console.WriteLine("First 30 at " + Array.IndexOf(nums, 30));
}
}
Output
Last 30 at 2
First 30 at 0
How It Works
Rightmost win. Scanning from the end finds index 2 first.
IndexOf contrast. The first match is still at 0.
Duplicates. LastIndexOf shines when values repeat.
Unsorted OK. No Sort call is required.
Example 2 — Return -1 When Absent
Search for a string that is not present.
C#
using System;
class Program {
static void Main() {
string[] colors = { "red", "blue" };
int ix = Array.LastIndexOf(colors, "green");
Console.WriteLine(ix);
}
}
Output
-1
How It Works
Same sentinel. Missing values use -1, just like IndexOf.
Check before use. Never index with -1.
Short array. Both ends were checked; nothing matched.
Case rules. Default string compare is case-sensitive.
Example 3 — Limit the Backward Search
Start from a middle index so earlier matches are ignored.
C#
using System;
class Program {
static void Main() {
int[] nums = { 7, 3, 7, 3, 7 };
// start at index 3, search toward 0
int ix = Array.LastIndexOf(nums, 7, 3);
Console.WriteLine(ix);
}
}
Output
2
How It Works
Start at 3. Position 3 holds 3, so the search continues left.
Finds index 2. That is the last 7 at or before index 3.
Skips final 7. The 7 at index 4 is outside the search window.
Useful for ranges. Combine with count overloads for tighter windows.
Frequently Asked Questions
It returns -1.
No. It works on any order.
When you want the rightmost match among duplicates.
Yes. Overloads accept a startIndex and optional count for a backward window.