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.
Practice
Solution
Step 1: Understand array index rules in C#
Array indexes must be between 0 and array length - 1.Step 2: Behavior on invalid index
Accessing an index less than 0 is outside valid range and causes an exception.Final Answer:
It throws an IndexOutOfRangeException. -> Option AQuick Check:
Invalid index access = IndexOutOfRangeException [OK]
- Thinking negative index returns first element
- Assuming negative index returns null
- Believing index auto-corrects to 0
numbers in C#?Solution
Step 1: Recall zero-based indexing in C# arrays
Array indexes start at 0, so the first element is numbers[0].Step 2: Identify the third element index
The third element is at index 2 (0,1,2).Final Answer:
int value = numbers[2]; -> Option DQuick Check:
Third element index = 2 [OK]
- Using index 3 for third element
- Confusing element position with index
- Accessing index 1 or 0 for third element
int[] arr = {10, 20, 30};
Console.WriteLine(arr[3]);Solution
Step 1: Check array length and valid indexes
Array has 3 elements with indexes 0, 1, 2.Step 2: Accessing index 3
Index 3 is outside the array bounds, causing an exception.Final Answer:
IndexOutOfRangeException -> Option BQuick Check:
Accessing arr[3] = IndexOutOfRangeException [OK]
- Expecting last element value instead of error
- Assuming default zero value returned
- Confusing index 3 with valid index
int[] data = new int[5]; data[5] = 100;
What is the issue and how to fix it?
Solution
Step 1: Analyze array size and valid indexes
Array size is 5, valid indexes are 0 to 4.Step 2: Identify invalid index usage
Accessing data[5] is outside bounds, causing IndexOutOfRangeException.Step 3: Correct the index
Use data[4] to access the last element safely.Final Answer:
IndexOutOfRangeException because index 5 is invalid; fix by using index 4. -> Option CQuick Check:
Index 5 invalid, max index 4 [OK]
- Assuming index 5 is valid for length 5
- Confusing syntax error with runtime error
- Thinking array is uninitialized
int[] scores = {5, 10, 15};. You want to safely print the element at index i without causing an exception. Which code snippet correctly checks bounds before accessing?Solution
Step 1: Understand valid index range for array
Valid indexes are from 0 up to Length - 1.Step 2: Check each condition
if (i >= 0 && i < scores.Length) Console.WriteLine(scores[i]); else Console.WriteLine("Invalid index"); correctly checks i >= 0 and i < Length, ensuring safe access.Step 3: Identify incorrect conditions
Other options exclude index 0 or allow invalid upper bounds.Final Answer:
if (i >= 0 && i < scores.Length) Console.WriteLine(scores[i]); else Console.WriteLine("Invalid index"); -> Option AQuick Check:
Bounds check: 0 ≤ i < Length [OK]
- Using > 0 instead of >= 0
- Allowing index equal to length
- Ignoring zero index as valid
Ready to prove it?
Pass the test and this pattern moves unknown
