Reputation: 3
This is a simplified version of the problem im trying to solve. Im trying to add an int[]
to a List
, but it updates all the arrays in the List
with the one from the last iteration. Why is that? And how does I solve this problem? This isn't a problem if it's just 1 int
for example.
intArray = new int[9];
for (int i = 0; i < 9; i++)
{
intArray[i] = i;
}
Test.Add(intArray);
for (int i = 0; i < 9; i++)
{
intArray[i] = i * 2;
}
Test.Add(intArray);
foreach (var item in Test)
{
for (int i = 0; i < 9; i++)
{
Console.WriteLine(item[i]);
}
}
Console.ReadKey();
}
public static int[] intArray { get; set; }
public static List<int[]> Test = new List<int[]>();
Upvotes: 0
Views: 77
Reputation: 374
after u added your intArray object into your arraylist ,simply create another object of that
intArray = new int[length];
hope it will works
Upvotes: 0
Reputation: 10695
Using new
keyword you create intArray
only once. Then there is only one reference. After that you add intArray
reference to collection List
for multiple times.
Try this,
intArray = new int[9];
for (int i = 0; i < 9; i++)
{
intArray[i] = i;
}
Test.Add(intArray);
intArray = new int[9]; // create new intArray here
for (int i = 0; i < 9; i++)
{
intArray[i] = i * 2;
}
Test.Add(intArray);
Upvotes: 1