- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Understanding IndexOutOfRangeException Exception in C#
It occurs when Index is outside the bounds of the array.
Let us see an example. We have declare an array with 5 elements and set the size as 5.
int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50;
Now, we try to add the value of an element that extends the size of our array i.e.
arr[5] = 60;
Above, we are trying to add element at 6th position.
Example
using System; using System.IO; using System.Collections.Generic; namespace Demo { class Program { static void Main(string[] args) { int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; arr[5] = 60; // this shows an error } } }
Output
The following is the output. It shows the following error −
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
Advertisements