Different ways to implement Shallow Copy in C#

Ahmed Elmehalawi - Oct 11 - - Dev Community

In C#, reference types are objects that are stored in the heap. When these types are assigned or passed, they share the same memory location. This behavior can lead to unintended consequences, as modifying one reference affects all other references pointing to the same object. In certain scenarios, it may be necessary to create a separate value copy from a reference type to avoid such side effects.


Consider the following class, which contains several value-type properties:

    public class Employee
    {
        public string FirstName { get; private set; }
        public string LastName { get; private set; }
        public string Title { get; private set; }


        public Employee(string firstName, string lastName, string title)
        {
            FirstName = firstName;
            LastName = lastName;
            Title = title;
        }
        public void UpdateName(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }

        public void UpdateTitle(string title)
        {
            Title = title;
        }
    }
Enter fullscreen mode Exit fullscreen mode

Suppose we create an instance of the Employee class:
Employee employeeInfo = new Employee("Ahmed", "Elmehalawi", "Software Engineer");

If we then create another Employee object by copying the employeeInfo data:
Employee copiedEmployeeInfo = employeeInfo;

Any changes made to employeeInfo will be reflected in copiedEmployeeInfo. For example, updating the title using the UpdateTitle method:
employeeInfo.UpdateTitle("Project Manager")

This update will change the title to "Project Manager" for both employeeInfo and copiedEmployeeInfo, as both variables reference the same memory location on the heap.
However, if the intention is to create a copy of the object rather than share the same reference, we need to perform a shallow copy. A shallow copy creates a new object but copies the original object’s properties, ensuring that changes made to one do not affect the other.

Ways to implement Shallow Copy in C#:


1. MemberwiseClone
The MemberwiseClone method creates a shallow copy of the object:

public Employee ShallowCopy()
{
    return (Employee)this.MemberwiseClone();
} 
Enter fullscreen mode Exit fullscreen mode

Usage:-
Employee copiedEmployeeInfo = employeeInfo.ShallowCopy();
In this case, any changes made to one instance will not reflect on the other.

2. ICloneable interface
Implementing the Clone method using the ICloneable interface, which also utilizes MemberwiseClone:

public object Clone()
{
    return (Employee)this.MemberwiseClone();
}
Enter fullscreen mode Exit fullscreen mode

3. Copy Constructor
A copy constructor explicitly creates a new instance by copying the values of the original object's properties:

public Employee(Employee employee)
{
    FirstName = employee.FirstName;
    LastName = employee.LastName;
    Title = employee.Title;
}
Enter fullscreen mode Exit fullscreen mode

Usage:
Employee copiedEmployeeInfo = new Employee(employeeInfo);

4. JSON Serialization and Deserialization
Another approach is to use JSON serialization and deserialization to create a copy:

Employee copiedEmployeeInfo = JsonConvert.DeserializeObject<Employee>(JsonConvert.SerializeObject(employeeInfo));
Enter fullscreen mode Exit fullscreen mode

5. Manual Property Copying
You can manually create a new object and assign values from the original object’s properties:

Employee copiedEmployeeInfo = new Employee(employeeInfo.FirstName, employeeInfo.LastName, employeeInfo.Title);
Enter fullscreen mode Exit fullscreen mode
. .
Terabox Video Player