C# Array.LastIndexOf Tips

Array type

You want to find the last element in your array that contains the specified value. With Array.LastIndexOf, the search begins from the last array element and proceeds in reverse. We look at Array.LastIndexOf.

Example

In this program, we call Array.IndexOf once, and Array.LastIndexOf twice. Please notice how when IndexOf finds the value 6, it returns the index 2. When LastIndexOf finds the value 6, it returns the index 4. This is because the two methods search from opposite starting points.

This C# example program uses the Array.LastIndexOf method. It searches an array.

Program that uses Array.LastIndexOf [C#]

using System;

class Program
{
    static void Main()
    {
	int[] array = { 2, 4, 6, 8, 6, 2 };

	int result1 = Array.IndexOf(array, 6);
	Console.WriteLine(result1);

	int result2 = Array.LastIndexOf(array, 6);
	Console.WriteLine(result2);

	int result3 = Array.LastIndexOf(array, 100);
	Console.WriteLine(result3);
    }
}

Output

2
4
-1
.NET Framework information

Not found condition. Array.LastIndexOf, like Array.IndexOf, uses a magic error code of negative one to indicate a not-found condition. This can be confusing at first. This can be seen as just a sign of a non-ideal method signature in the .NET Framework. Error conditions are most logically represented by a separate true/false value.

Criticism

Note (please read)

Arrays are lower level types than other types such as the List in the .NET Framework. Because of this, when you use arrays directly you should expect to have to do some looping on your own.

List Examples

In my opinion, methods such as LastIndexOf on arrays are superfluous in most programs. My reasoning is that if you were to use a for-loop, you could possibly improve your algorithm by combining multiple loops into one (loop jamming). Additionally, if you wanted a high-level collection it would be better to use the List type. Finally, IndexOf and LastIndexOf reduce performance even in simple situations.

Loop Jamming Array.IndexOf Method: Search Arrays

Summary

The C# programming language

We tested the Array.LastIndexOf method on an int array in a C# program. Although the LastIndexOf method may be useful in certain situations, it also introduces a confusing error code (-1) and can impair certain optimizations in C# programs.

Array Types
.NET