1.

Why index out of range exception occur in C#?

Answer»

IndexOutOfRangeException occurs when an element is tried to access with an index, which is outside the bounds of the array.

The following error MESSAGE is visible:

System.IndexOutOfRangeException: Index was outside the bounds of the array

An example displays the same exception that occurs because we are trying to access an element with an index outside the bounds of the array:

using System; namespace Example {   class One {      static void MAIN(string[] ARGS) {          try {                 int i;                 int [] val = new int[2] {97, 49};                 for (i = 0; i < 5; i++ ) {                    Console.WriteLine(val[i]);                 }           }           catch (System.IndexOutOfRangeException indexException)            {                Console.WriteLine(indexException);            }      }   } }

It displays the same error as output:

97 49 System.IndexOutOfRangeException: Index was outside the bounds of the array


Discussion

No Comment Found