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);
}
The AddRange method is called, with the list as its argument. The result is that the current elements of the list are added to the end of the list, duplicating all the elements.
List<T>. AddRange(IEnumerable<T>) Method is used to add the elements of the specified collection to the end of the List<T>.
In C#, AddRange adds an entire collection of elements. It can replace tedious foreach-loops that repeatedly call Add on List. Notes, argument. We can pass any IEnumerable collection to AddRange, not just an array or another List.
AddRange is used to add multiple elements. The add method inserts the item at the end of a collection. AddRange method is used to insert a set of records into a collection. The addRange method is also used to add an array of nodes that are previously created in the collection.
Are you trying to update the same list from multiple threads? That could cause problems... List<T>
isn't safe for multiple writers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With