I have problem when using static variable in my project (force using static variable)
public static List<int> a = new List<int>();
public static List<List<int>> list = new List<List<int>>();
public Form1()
{
for (int i = 0; i < 5;i++ )
a.Add(i);
list.Add(a);
Console.WriteLine(list[0].Count); // **count = 5**
a.RemoveAt(0);
list.Add(a);
Console.WriteLine(list[0].Count); // **count = 4**
Console.WriteLine(list[1].Count); // count = 4
}
When I use a.RemoveAt(0) , it makes list[0] change. Why does it do this and how can I fix it?
list[0]containsaso if you remove sth fromalist[0].Countis different. It's not because of static, it's becauselist[0]contains reference to objectaainlist[0], then make a copy:list.Add(a.ToList());(make sure to add ausing System.Linq;directive)AddRange.