I have a dictionary
employeeDict = new Dict<int, Employee>();
If I do
var employee = dict[1];
and then
employee.Name = "Changed"
It gets affected in the original dictionary too. What to do if I don't want that to happen?
CodePudding user response:
There is no built in way to provide a deep copy of arbitrary objects. You need to provide that yourself.
My recommendation would be to avoid cloning and instead embrace immutable types. I.e. make all fields and properties of the class read only. Instead of changing a property you would be forced to create a new object. See this answer for more details about the benefit of immutability.
Record types in c# 9 makes this fairly easy, allowing you to write:
var employeeWithChangedName = employee with { Name = "Changed"};
c# 10 allows the same with syntax to be used for structs and anonymous types.
CodePudding user response:
I used something like this
Employee e = new Employee();
e.Id = employeeDict[1].Id;
e.Name = "Changed";
e.Address = employeeDict[1].Address;
This also works. Thank you others for your reply.