I am not sure where is the problem with the code below where value of one class instance change the value of another. It seems that I have problem property of type class where the value set in one class affects the value of another class of the same type. Example is below. What I want to achieve is after the assignment of value from one class (Result 2) , the subsequent manipulation of the the other class does not effect the previous one.
public class Address {
public string Street {
get;
set;
}
}
public class Person {
public string Name {
get;
set;
}
public List<Address> Addresses {
get;
set;
} = new List<Address>();
public int Age {
get;
set;
}
}
public class Employee {
public string EmpID {
get;
set;
}
public Person EmployeePerson {
get;
set;
}
}
var emp = new Employee {
EmpID = "1",
EmployeePerson = new Person {
Name = "Alice", Addresses =
new List<Address> {
new Address {
Street = "123 Street"
}
}
}
};
var per = new Person {
Name = emp.EmployeePerson.Name, Addresses = emp.EmployeePerson.Addresses };
per.Addresses[0].Street = "New Street";
per.Name = "New Name";
Console.WriteLine("Result 1: {0} , {1}",
emp.EmployeePerson.Name, per.Name);
Console.WriteLine("Result 2: {0} , {1}",
emp.EmployeePerson.Addresses[0].Street, per.Addresses[0].Street);
Result 1: Alice , New Name
Result 2: New Street , New Street