Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LIST<> AddRange throwing ArgumentException

Tags:

c#

exception

list

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);
}
like image 868
Tim Avatar asked Apr 07 '10 14:04

Tim


People also ask

What does List AddRange do?

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.

What is AddRange in Linq?

List<T>. AddRange(IEnumerable<T>) Method is used to add the elements of the specified collection to the end of the List<T>.

How does AddRange work in c#?

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.

Is the AddRange feature used whenever adding multiple values to collection objects?

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.


1 Answers

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

like image 154
Jon Skeet Avatar answered Oct 17 '22 01:10

Jon Skeet