Hi friends, In this tutorial, I am going to tell you about Index out of Range Exception. An Index out of range exception occurs when you tried to access an element in a collection, using a numeric index that exceeds the collection’s boundaries.

How indexing works in Arrays:

Suppose I have declared an array of six items like this:

string[] array=new string[5];

To access the first and last element from the array.

string sFirstElement=array[0];
string sLastElement=array[4];

To iterate through all the elements in an array.

for (int iCount= 0; iCount < array.Length; iCount++)
{
Console.WriteLine(array[iCount]);
}

Why does this error occur?

The Index out of Range Exception is thrown when you tried to access an element in a collection, using a numeric index that exceeds the collection’s boundaries.
The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you’re going to get an error.

C# Program to demonstrate Index out of range Exception:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


class Program
{
static void Main(string[] args)
{
int iDifference = 0;
int[] arrNumber = new int[5] { 1, 2, 3, 4, 5 };
try
{
for (int iCount = 1; iCount <= 5; iCount++)
{
iDifference = iDifference - arrNumber[iCount];
}
Console.WriteLine("The difference of the array is:" + iDifference);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}

Output:

Index was outside the bounds of the array.

You can see in the above program <= there? the index will now be out of range in the last loop iteration because the loop thinks that Length is a valid index, but it is not.

View More:

Conclusion:

I hope this is a useful tutorial for you. Please don’t hesitate to comment for any technical help. Your feedback and suggestions would be appreciated for me.

Thank You.

Leave a Comment