The exact instantiation is
List
- > xList = new List
- >();
Now, if I want to create a shallow copy of this Generic List, I would have to use the GetRange method...I've tried this....I've done a lot of different things to achieve this shallow copy, but what ends up happening is any edits I make to the shallow copy are reflected in the original List as well.
here's an example of what I'm talking about:
int[] x = new int[5] { 3, 5, 7, 9, 11 };
List
tList.Add(x);
List
yList[0][0] = 12;
In this case, xList[0][0] Also gets changed to the value of 12. Can anyone help me with this short of looping through the entire data list????

AlanRank #669 · 3.6K reputationPosted May 5, 2008, 12:34 PM EDT
As the List contains int[], which is a reference type, creating a shallow copy of the List just copies the references, not the array elements.
You therefore need to create shallow copies of the int[]'s themselves:
int[] x = new int[5] { 3, 5, 7, 9, 11 };
List tList = new List(); yList = new List();
tList.Add(x);
List
foreach(int[] ia in tList)
{
yList.Add((int[])ia.Clone());
}
yList[0][0] = 12;
Console.WriteLine(yList[0][0]); // 12
Console.WriteLine(tList[0][0]); // 3
Sherwin Hamidi19 reputationPosted May 5, 2008, 12:43 PM EDT
Any way around this?
Sherwin Hamidi19 reputationPosted May 5, 2008, 12:43 PM EDT
AlanRank #669 · 3.6K reputationPosted May 5, 2008, 12:51 PM EDT
Sherwin Hamidi19 reputationPosted May 6, 2008, 6:06 AM EDT
List
> xList = new List(); yList = new List(xList[0]);
//Populate xList with data here
List
yList[0] = 12;
Console.WriteLine(yList[0].ToString());
Console.WriteLine(xList[0][0].ToString());
results in different values.
The issue does exist, however, when I try to do:
List
>> xList = new List
>>();
//Populate xList
List
> yList = new List
>(xList[0]);
yList[0][0] = 12;
Console.WriteLine(yList[0][0].ToString());
Console.WriteLine(xList[0][0][0].ToString());
AlanRank #669 · 3.6K reputationPosted May 6, 2008, 7:27 AM EDT
I didn't follow your first example as yList is a list of int arrays and you can't therefore set the first element to 12.
However, when I did this, the results were the same as I'd have expected because the same int[] object is being referenced:
List
> xList = new List
>(); iList = new List(); yList = new List(xList[0]);
List
int[] x = new int[5] { 3, 5, 7, 9, 11 };
iList.Add(x);
xList.Add(iList);
List
yList[0][0] = 12;
Console.WriteLine(yList[0][0]); // 12
Console.WriteLine(xList[0][0][0]); // 12