Amit
Amit

Reputation: 1857

while adding element by 'AddRange()' in List of object following exception arrives

"Source array was not long enough. Check srcIndex and length, and the array's lower bounds."

I have not mentioned any size while creating destination list (in where I'm adding object) and source list (from where I'm adding objects in destination list)

Here is similar code what I'm doing.

List<Obj> sourceList = respObj.List;

if (sourceList  != null)
{
     destinationList.AddRange(sourceList);
}

here sourceList is being returned from a method calling and there also I'm not mentioning any size or index while creating it. it is as simple as this.

//destination list is globally declared, and initialized in constructor
public List<Obj> destinationList;
//Constructor
public Class()
{
    destinationList = new List<Obj>();
}

List<Obj> Method()
{
     List<Obj> sourceList = new List<Obj>();
     foreach(Obj obj in AlreadyGeneratedObjList)
     {
          if(SatisfyingCondition(obj))
          {
               sourceList.Add(obj);
          }  
     }
     return sourceList;
}

Exception occurs on "AddRange()" method

Upvotes: 3

Views: 2401

Answers (1)

Alex
Alex

Reputation: 1109

I assume destinationList is declared as

var destinationList = [?]{}; // ? being some size

The problem with this is that your array can't resize automatically which is what is needed for .AddRange() to be able to add contents of sourceList into it.

The way to solve this would be to either declare destinationList as a list

var destinationList = new List<obj>{};

or as an array with a correct size, ie. size that would accommodate the size of sourceList after it has been filtered. This may not be the best way to go about it though.

My personal recommendation would be to use a List<>.

Also don't forget to check that the filtered sourceList is not empty or null.

Edit

You should consider changing this as follows

if (sourceList != null && sourceList.Count > 0)
{
     destinationList.AddRange(sourceList);
}
else
{
     //destinationList = sourceList;
     // If the sourceList is ever null it will make every subsequent call
     // destinationList fail with a NullReference exception.

     destinationList.Clear();
}

Upvotes: 2

Related Questions