Search code examples
c#exceptionlist

List<T> AddRange throwing ArgumentException


I have a particular method that is occasionally crashing with an ArgumentException:

Destination array was not long enough. Check destIndex and length, and the array's lower bounds.:
at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
at System.Collections.Generic.List`1.CopyTo(T[] array, Int32 arrayIndex)
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)

The code that is causing this crash looks something like this:

List<MyType> objects = new List<MyType>(100);
objects = FindObjects(someParam);
objects.AddRange(FindObjects(someOtherParam);

According to MSDN, List<>.AddRange() should automatically resize itself as needed:

If the new Count (the current Count plus the size of the collection) will be greater than Capacity, the capacity of the List<(Of <(T>)>) is increased by automatically reallocating the internal array to accommodate the new elements, and the existing elements are copied to the new array before the new elements are added.

Can someone think of a circumstance in which AddRange could throw this type of exception?


Edit:

In response to questions about the FindObjects() method. It basically looks something like this:

List<MyObject> retObjs = new List<MyObject>();

foreach(MyObject obj in objectList)
{
   if(someCondition)
       retObj.Add(obj);
}

Solution

  • Are you trying to update the same list from multiple threads? That could cause problems... List<T> isn't safe for multiple writers.