LIST<> AddRange throwing ArgumentException

Posted by Tim on Stack Overflow See other posts from Stack Overflow or by Tim
Published on 2010-04-07T14:28:46Z Indexed on 2010/04/07 14:33 UTC
Read the original article Hit count: 779

Filed under:
|
|

Hi all,

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about list