We found something interesting happening recently at work when reviewing the web exception logs on our servers.  There seemed to be an inordinate number of “Index out of range” errors occurring, and they were all coming from one class.

Digging into the code, we found that the error was occurring on a ArrayList.Contains(item) method, which seemed very odd. As I understood it, the whole point of the Contains() method is to check for the item before you try and access it, thereby avoiding the index out of range error.

A workmate thought that it may be a race condition problem, as this class is called on pretty much every page load (it sits in the page header) and the ArrayList itself was a static variable.  We weren’t sure how this could happen, so he cracked out Reflector and disassembled the Contains() method on the ArrayList object. And we found something interesting.

(more…)