Why does List<T>.ToArray throw ArgumentException?

Why am I getting an argument exception telling me the destination array was not long enough while trying to make an array copy from a list?

List<MyCustomClass> asList = new List<MyCustomClass>();

// populate list etc etc.
// ...
// ...

// BANG!
// ArgumentException: Destination array was not long enough.
// Check destIndex and length, and the array's lower bounds.

MyCustomClass[] asArray = asList.ToArray();


Update:

It seems that another thread was updating the contents of the list unsynchronized so it could have been the cause of the bug. I can't tell for sure since we have since then moved on with another implementation but I am positive we had other bugs due to syncronization issues. It makes sense to think something bad can happen if the contents are changed while one thread is busy making the array. I'll hold off a couple more days until the deadline pressure release and report back if this was the sole cause in case anyone else happens to stumble across this same problem.

You need to check your code is thread safe. Use locks or other concurrent techniques.

// asynchronous access ahead, use locks:
// one thread is doing:
lock (asList)
{
    asList.Add(new MyCustomClass());
}

// other thread is doing:
lock (asList)
{
    MyCustomClass[] asArray = asList.ToArray();
}