System.Array.IndexOf Method

Searches for the specified object and returns the index of the first occurrence within the range of elements in the one-dimensional Array that starts at the specified index and contains the specified number of elements.

Syntax

[System.Runtime.ConstrainedExecution.ReliabilityContract(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.MayFail)]
public static int IndexOf (Array array, object value, int startIndex, int count)

Parameters

array
The one-dimensional Array to search.
value
The object to locate in array.
startIndex
The starting index of the search. 0 (zero) is valid in an empty array.
count
The number of elements in the section to search.

Returns

The index of the first occurrence of value within the range of elements in array that starts at startIndex and contains the number of elements specified in count, if found; otherwise, the lower bound of the array minus 1.

Exceptions

TypeReason
ArgumentNullException array is null.
ArgumentOutOfRangeException

startIndex is less than array.GetLowerBound(0).

-or-

count is less than zero.

-or-

startIndex + count is greater than array.GetLowerBound(0) + array.Length.

RankException array has more than one dimension.

Remarks

The one-dimensional Array is searched forward starting at startIndex and ending at startIndex plus count minus 1, if count is greater than 0.

The elements are compared to the specified value using the object.Equals(object) method. If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Since most arrays will have a lower bound of zero, this method would generally return –1 when value is not found. In the rare case that the lower bound of the array is equal to int.MinValue and value is not found, this method returns int.MaxValue, which is System.Int32.MinValue - 1.

Passing the Array.Length of the array as the startindex will result in a return value of -1, while values greater than Length will raise an ArgumentOutOfRangeException.

This method is an O(n) operation, where n is count.

In the .NET Framework version 2.0, this method uses the object.Equals(object) and IComparable.CompareTo(object) methods of the Array to determine whether the object specified by the value parameter exists. In the earlier versions of the .NET Framework, this determination was made by using the object.Equals(object) and IComparable.CompareTo(object) methods of the value object itself.

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0