Pavel

Pavel

  • 1.6k
  • 170
  • 51.1k

Cannot copy one List to another

Sep 24 2012 5:13 AM
Hello,

In my application I pass List lst1 into ProgressChanged handler of the a BackGroundWorker.
Inside of handler I need to exploit lst1 for refreshing datagridview. But lst1 is changing in permanence inside of background process.
So I can't directly use lst1, because it's reference-type object and any changes in background process will impact ProgressChanged handler, where lst1 is supposed to be constant.
The solution is: once inside of ProgressChanged handler, assign lst1 to some local list lst2.
Surprisingly, none of the List copying methods works.
I've tried the following:
1. List<SomeType1> lst2 = new List<SomeType1>(lst1);

2. List<SomeType1> lst2 = lst1.ToList();

3. List<SomeType1> lst2 = new List<SomeType1>();
    lst2.AddRange(lst1);

In all cases ArgumentException is generated with the following message:
Destination array was not long enough. Check destIndex and length, and the array's lower bounds.

Thanks in advance.

Pavel.

Answers (18)