System.ArgumentOutOfRangeException – Index was out of range. Must be non-negative and less than the size of the collection

Loading

The System.ArgumentOutOfRangeException – Index was out of range. Must be non-negative and less than the size of the collection is a runtime exception in C# that occurs when you try to access an element of a collection (e.g., an array, list, or string) using an index that is outside its valid range. This typically happens when:

  1. The index is negative.
  2. The index is greater than or equal to the size of the collection.
  3. The collection is empty.

Here’s how you can troubleshoot and fix this issue:


1. Check Index Bounds

  • Ensure that the index is within the valid range of the collection (i.e., non-negative and less than the size of the collection). Example:
   int[] numbers = { 1, 2, 3 };
   int value = numbers[3]; // Error: Index 3 is out of range

Fix:

   int[] numbers = { 1, 2, 3 };
   if (3 < numbers.Length)
   {
       int value = numbers[3]; // Safe: Check index bounds
   }
   else
   {
       Console.WriteLine("Index is out of range");
   }

2. Use for Loops Correctly

  • When iterating over a collection, ensure that the loop condition is correct. Example:
   int[] numbers = { 1, 2, 3 };
   for (int i = 0; i <= numbers.Length; i++) // Error: 'i <= numbers.Length' is out of bounds
   {
       Console.WriteLine(numbers[i]);
   }

Fix:

   int[] numbers = { 1, 2, 3 };
   for (int i = 0; i < numbers.Length; i++) // Correct: 'i < numbers.Length'
   {
       Console.WriteLine(numbers[i]);
   }

3. Check for Empty Collections

  • Ensure that the collection is not empty before accessing its elements. Example:
   List<int> numbers = new List<int>();
   int value = numbers[0]; // Error: Collection is empty

Fix:

   List<int> numbers = new List<int> { 1, 2, 3 };
   if (numbers.Count > 0)
   {
       int value = numbers[0]; // Safe: Collection is not empty
   }

4. Use foreach Loops

  • Use foreach loops to avoid manual index management and prevent out-of-bounds errors. Example:
   int[] numbers = { 1, 2, 3 };
   foreach (int number in numbers) // No need to manage indices
   {
       Console.WriteLine(number);
   }

5. Check for Multidimensional Arrays

  • When working with multidimensional arrays, ensure that all indices are within bounds. Example:
   int[,] matrix = new int[2, 2];
   int value = matrix[2, 2]; // Error: Indices (2, 2) are out of bounds

Fix:

   int[,] matrix = new int[2, 2];
   int value = matrix[1, 1]; // Correct: Indices (1, 1) are within bounds

Example of Correct Code

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main(string[] args)
    {
        // Example 1: Check index bounds
        int[] numbers = { 1, 2, 3 };
        if (2 < numbers.Length)
        {
            Console.WriteLine(numbers[2]); // Output: 3
        }
        else
        {
            Console.WriteLine("Index is out of range");
        }

        // Example 2: Use 'for' loops correctly
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine(numbers[i]); // Output: 1, 2, 3
        }

        // Example 3: Check for empty collections
        List<int> emptyList = new List<int>();
        if (emptyList.Count > 0)
        {
            Console.WriteLine(emptyList[0]);
        }
        else
        {
            Console.WriteLine("Collection is empty"); // Output: Collection is empty
        }

        // Example 4: Use 'foreach' loops
        foreach (int number in numbers)
        {
            Console.WriteLine(number); // Output: 1, 2, 3
        }

        // Example 5: Check multidimensional arrays
        int[,] matrix = new int[2, 2];
        matrix[1, 1] = 10;
        Console.WriteLine(matrix[1, 1]); // Output: 10
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *