C# Array.LastIndexOf

Array

Array.LastIndexOf finds the last matching element. It searches from the end of an array. It returns the index of the element that contains the specified value. It has limitations—it may be of limited value.

Example

Return keyword

We call Array.IndexOf once, and Array.LastIndexOf twice. When IndexOf finds the value 6, it returns the int value 2. When LastIndexOf finds the value 6, it returns the index 4. The two methods search from opposite starting points.

Int
Based on:

.NET 4.5

C# program that uses Array.LastIndexOf

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
Framework: NET

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 at first confusing. This is a sign of a non-ideal method signature in the .NET Framework.

Note:Error conditions are most logically represented by a separate true/false value, not the value -1.

Discussion

Note

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

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 improve your algorithm by combining multiple loops into one (loop jamming).

Loop JammingList

Also: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. They are not good for performance-critical code.

Array.IndexOf

Summary

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


C#: Array