Array bounds checking helps prevent errors by making sure you don't access parts of an array that don't exist.
Array bounds checking behavior in C Sharp (C#)
class Program { static void Main() { int[] numbers = new int[3]; // Accessing elements within bounds int first = numbers[0]; // Accessing elements outside bounds throws an exception int invalid = numbers[3]; // This causes an error } }
C# automatically checks if the index is within the array size.
If you try to access an index less than 0 or greater than or equal to the array length, it throws an IndexOutOfRangeException.
int[] emptyArray = new int[0]; // Accessing any element will throw an exception int value = emptyArray[0];
int[] singleElementArray = { 42 }; int first = singleElementArray[0]; // Works fine int invalid = singleElementArray[1]; // Throws exception
int[] numbers = { 10, 20, 30 }; int last = numbers[2]; // Last valid element int invalid = numbers[3]; // Throws exception
This program prints all valid elements of the array. Then it tries to access an invalid index, which causes an exception. The exception is caught and its message is printed.
using System; class Program { static void Main() { int[] scores = { 85, 90, 78 }; Console.WriteLine("Scores array elements:"); for (int index = 0; index < scores.Length; index++) { Console.WriteLine($"Index {index}: {scores[index]}"); } try { Console.WriteLine("Trying to access index 3 (out of bounds):"); int invalidScore = scores[3]; } catch (IndexOutOfRangeException e) { Console.WriteLine("Error: " + e.Message); } } }
Array bounds checking happens automatically in C# for safety.
Time complexity for accessing an element is O(1), but checking adds a tiny overhead.
Common mistake: forgetting that arrays start at index 0, so the last valid index is length - 1.
Use bounds checking to avoid crashes, but if you need faster code and are sure about indexes, unsafe code can skip checks (advanced topic).
Array bounds checking prevents accessing invalid indexes.
Accessing outside the array throws an IndexOutOfRangeException.
Always use indexes between 0 and array length - 1.