Hi I have a list with Person class as follows
public class person
{
public int age;
public string name;
}
I am trying to do the following.
static void Main(string[] args)
{
List<person> person1 = new List<person>();
person1.Add(new person { age = 10, name = "P1" });
person1.Add(new person { age = 11, name = "Q1" });
person1.Add(new person { age = 12, name = "R1" });
List<person> person2 = new List<person>(person1);
person2[0].name = "P2";
Console.WriteLine("---------Person1---------");
foreach (person P in person1)
{
Console.WriteLine("Age=" + P.age);
Console.WriteLine("Name=" + P.name);
}
Console.WriteLine("---------Person2---------");
foreach (person P in person2)
{
Console.WriteLine("Age=" + P.age);
Console.WriteLine("Name=" + P.name);
}
}
The Output is that the value of first object in both the lists is changed to P2 while I expect to change it only in person2
list. I thought the list items would be copied into person2
list.
MSDN here says that the elements are copied to the new list which is not happening in above case. what am I missing here?