How DeepClone and ShallowClone differ
developThe primary difference is how related objects are handled:
- DeepClone: Guarantees that all changes to the cloned object (including nested properties) do not affect the original object.
- ShallowClone: Only copies the top-level object. Nested objects are shared between the original and the clone.
// public class A { public B B; }
// public class B { public int X; }
var b = new B { X = 1 };
var a = new A { B = b };
// Deep Clone Example
var deepClone = a.DeepClone();
deepClone.B.X = 2;
Console.WriteLine(a.B.X); // Output: 1
// Shallow Clone Example
var shallowClone = a.ShallowClone();
shallowClone.B.X = 2;
Console.WriteLine(a.B.X); // Output: 2