I just had a unique error where a live site was throwing "Index was outside the bounds of the array" on login. I tracked the error down to an old "timing" file inherited from an old project. Here's the full class
public class TimingObject
{
public DateTime timestamp { get; set; }
public String call { get; set; }
public TimeSpan duration { get; set; }
// create a new timing object starting now
public TimingObject()
{
timestamp = DateTime.Now;
}
public TimingObject(String call)
{
timestamp = DateTime.Now;
this.call = call;
}
public void Stop()
{
List<TimingObject> timings;
if (HttpContextManager.Current.Cache["PageTimings"] == null)
timings = new List<TimingObject>();
else
timings = HttpContextManager.Current.Cache["PageTimings"] as List<TimingObject>;
this.duration = (DateTime.Now - this.timestamp);
timings.Add(this);
HttpContextManager.Current.Cache["PageTimings"] = timings;
}
}
The error was thrown by timings.Add(this)
. Why would Index was out of bounds
be thrown when adding an item to a list?
Could this happen if the list is too big? And how big would it have to be exactly?
The code is redundant, and has been removed. But I'd really like to know why this happened.