I'm trying to create a new deep copy of a list, including the objects, but when I change the objects in the second list, the objects in the original list change too. I implemented the clone method, but this doesn't work at all.
I have an abstract class Person.
internal abstract class Person : ICloneable
{
protected string Name;
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public void sayMyName()
{
Console.WriteLine($"My name is {Name}");
}
public abstract object Clone();
}
A child class also:
internal class Student : Person, ICloneable
{
public int Grade { get; set; }
public Student(string name, int age, int grade) : base(name, age)
{
Grade = grade;
}
public override object Clone()
{
return new Student(Name, Age, Grade);
}
}
And this is the main method:
internal class Program
{
static void Main(string[] args)
{
Person s1 = new Student("Andrew", 20, 7);
Person s2 = new Student("John", 21, 8);
Person s3 = new Student("George", 19, 9);
List<Person> personList = new List<Person>();
personList.Add(s1);
personList.Add(s2);
personList.Add(s3);
for(int i = 0; i < 3; i++)
{
List<Person> secondList = new List<Person>(personList);
foreach(Person person in secondList)
{
person.sayMyName();
Console.WriteLine(person.Age);
person.Age--;
}
Console.WriteLine();
}
}
}
When I change the age of the persons in the second list, they also change in the original list. I implemented the clone method, why is this happening?