Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Array.IndexOf — index of the first occurrence

System.Array.IndexOf finds the first occurrence of a value in an array or a range and returns its index.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

Array.IndexOf<T>(T[] array, T value)
Array.IndexOf<T>(T[] array, T value, int startIndex)
Array.IndexOf<T>(T[] array, T value, int startIndex, int count)

System.Array.IndexOf searches a one-dimensional array. Generic overloads return a zero-based index or -1 when no match exists.

startIndex begins the range; count specifies its length. The result indexes the original array. Equality uses EqualityComparer<T>.Default; searching is O(n) in the searched range.

A null array throws ArgumentNullException; an invalid range throws ArgumentOutOfRangeException. Non-generic overloads accept Array and object?; multidimensional arrays cause RankException. Their not-found result is the array's lower bound minus one, usually -1.

Examples

using System;

int[] values = { 7, 4, 7, 9 };
Console.WriteLine(Array.IndexOf(values, 7));
Console.WriteLine(Array.IndexOf(values, 7, 1));
Console.WriteLine(Array.IndexOf(values, 7, 1, 1));

Result

0
2
-1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources