When accessing list data with indices, the most common problem we can run into is exceeding the list's bounds.
Remember, the items of a List are indexed from 0 to Count - 1. Any index which is not in this range is invalid.
When you try to access an item with an invalid index, C# throws an ArgumentOutOfRangeException:
List<int> ourArray = new List<int>(new[] {50, 40, 30});
// Valid indices: 0, 1, 2
Console.WriteLine(ourArray[0]); // Output: 50
Console.WriteLine(ourArray[2]); // Output: 30
// Invalid indices: 3, 30, -1
Console.WriteLine(ourArray[3]); // throws ArgumentOutOfRangeException
Console.WriteLine(ourArray[30]); // throws ArgumentOutOfRangeException
Console.WriteLine(ourArray[-1]); // throws ArgumentOutOfRangeException
As programmers, we always want to make sure that we don't exceed a list's bounds in our programs.
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
