How to properly deep copy an object in .NET (C#)?
Hi everyone! I'm a beginner C# developer and I've encountered a problem with copying objects. I have a Person class with several nested objects, for example, Address. When I try to copy an object through simple assignment, I get a reference to the same object, not its copy. When I change properties in the "copy", the original object also changes.
Here's an example code that illustrates the problem:
```csharp
public class Address
{
public string City { get; set; }
public string Street { get; set; }
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
}
// Usage
var original = new Person
{
Name = "Ivan",
Age = 30,
Address = new Address { City = "Moscow", St
No answers yet.
Log in to leave an answer
Blogs
Clean Code in JavaScript: Principles and Examples for Node.js