IndexOutOfRangeException

Another exception in the category of silly bug revealers is IndexOutOfRangeException, which indicates an array is accessed outside its boundaries. “Off-by-one” errors are a typical source of this exception:

int[] nums = new[] { 1, 2, 3 };for (int i = 0; i <= nums.Length; i++)    nums[i]++;

Bounds checks have been a historical source of bugs, which often went unnoticed in the world of native code, causing random program crashes because of memory corruption. Consider yourself lucky that the CLR catches this class of problems using runtime checks (to avoid its memory and type safety), but don’t write such bugs in the first place! Off-by-one errors can be subtle, but with a little bit of extra thought, you should be able ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.