0
0
CsharpHow-ToBeginner · 3 min read

How to Use Array.IndexOf in C# - Simple Guide

Use Array.IndexOf(array, value) in C# to find the first position of value in array. It returns the zero-based index or -1 if the value is not found.
📐

Syntax

The basic syntax of Array.IndexOf is:

  • array: The array to search.
  • value: The element to find in the array.
  • The method returns the zero-based index of the first occurrence of value or -1 if not found.
csharp
int index = Array.IndexOf(array, value);
💻

Example

This example shows how to find the index of a number in an integer array and handle the case when the number is not found.

csharp
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 10, 20, 30, 40, 50 };
        int valueToFind = 30;

        int index = Array.IndexOf(numbers, valueToFind);

        if (index != -1)
        {
            Console.WriteLine($"Value {valueToFind} found at index {index}.");
        }
        else
        {
            Console.WriteLine($"Value {valueToFind} not found in the array.");
        }
    }
}
Output
Value 30 found at index 2.
⚠️

Common Pitfalls

Common mistakes when using Array.IndexOf include:

  • Not checking if the returned index is -1 before using it.
  • Expecting the method to find multiple occurrences; it only returns the first match.
  • Using it on unsorted arrays when expecting sorted search behavior.
csharp
using System;

class Program
{
    static void Main()
    {
        string[] fruits = { "apple", "banana", "cherry" };

        // Wrong: Not checking if index is -1
        int index = Array.IndexOf(fruits, "orange");
        // This will cause an error if used directly
        // Console.WriteLine(fruits[index]); // Index -1 is invalid

        // Right: Check if found
        if (index == -1)
        {
            Console.WriteLine("Value not found.");
        }
        else
        {
            Console.WriteLine($"Found at index {index}.");
        }
    }
}
Output
Value not found.
📊

Quick Reference

MethodDescriptionReturn Value
Array.IndexOf(array, value)Finds first index of value in arrayIndex (0-based) or -1 if not found
Array.LastIndexOf(array, value)Finds last index of value in arrayIndex (0-based) or -1 if not found

Key Takeaways

Array.IndexOf returns the first position of a value or -1 if not found.
Always check if the returned index is -1 before using it.
It only finds the first occurrence, not multiple matches.
Works on any array type including strings and numbers.
Use Array.LastIndexOf to find the last occurrence instead.