Avatar ·

Deep cloning of objects in C#: how to make a full copy?

Hello everyone! I'm new to C# and encountered a problem when copying objects. I have a class that contains reference types (e.g., lists and other classes). When I assign one instance to another, changes in the copy affect the original. I want to create a completely independent copy of the object so that I can modify it without changing the original data.\n\nHere is an example code that demonstrates the problem:\n\n```csharp\npublic class Person\n{\n public string Name { get; set; }\n public List Hobbies { get; set; }\n}\n\npublic class Program\n{\n public static void Main()\n {\n Person original = new Person { Name = "Ivan", Hobbies = new List { "Reading", "Swimming" } };\n Person shallowCopy = original; // This is a shallow copy\n\n shallowCopy