What is the difference between shallow copy and deep copy?
10 minintermediatecopyingcloningmemoryobjects
Quick Answer
Shallow copy creates a new object but copies references to nested objects (shared references). Deep copy creates a new object and recursively copies all nested objects (independent copies). Shallow copy is faster but can lead to unintended sharing. Deep copy is safer but more expensive. Use ICloneable or custom methods to implement copying.
Detailed Answer
Shallow Copy creates a new object but copies only the reference of nested objects. Changes to nested objects affect both the original and copied object.
Deep Copy creates a new object and recursively copies all nested objects. Changes to the copy don't affect the original.
Example:
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public Address Clone()
{
return new Address
{
Street = this.Street,
City = this.City
};
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
// Shallow Copy using MemberwiseClone
public Person ShallowCopy()
{
return (Person)this.MemberwiseClone();
}
// Deep Copy - manually copying all reference types
public Person DeepCopy()
{
return new Person
{
Name = this.Name,
Age = this.Age,
Address = this.Address?.Clone() // Clone nested object
};
}
}
// Demonstration
class Program
{
static void Main()
{
// Original object
var person1 = new Person
{
Name = "John",
Age = 30,
Address = new Address { Street = "123 Main St", City = "New York" }
};
// Shallow Copy
var shallowCopy = person1.ShallowCopy();
shallowCopy.Name = "Jane"; // Changing value type
shallowCopy.Address.City = "Los Angeles"; // Changing reference type
Console.WriteLine("After Shallow Copy:");
Console.WriteLine($"Original: {person1.Name}, {person1.Address.City}");
// Output: Original: John, Los Angeles (City changed!)
Console.WriteLine($"Shallow Copy: {shallowCopy.Name}, {shallowCopy.Address.City}");
// Output: Shallow Copy: Jane, Los Angeles
Console.WriteLine();
// Deep Copy
var person2 = new Person
{
Name = "Bob",
Age = 25,
Address = new Address { Street = "456 Oak Ave", City = "Chicago" }
};
var deepCopy = person2.DeepCopy();
deepCopy.Name = "Alice";
deepCopy.Address.City = "Boston";
Console.WriteLine("After Deep Copy:");
Console.WriteLine($"Original: {person2.Name}, {person2.Address.City}");
// Output: Original: Bob, Chicago (City unchanged!)
Console.WriteLine($"Deep Copy: {deepCopy.Name}, {deepCopy.Address.City}");
// Output: Deep Copy: Alice, Boston
}
}