Techiehook Techiehook
Updated date Jun 12, 2024
We will learn how to clone objects in C# .NET Core. Also, explore various methods including shallow copy using MemberwiseClone, deep copy using JSON serialization, manual copying, and advanced reflection techniques.

How do you Clone Objects in C# .NET Core?

We will use multiple ways in C# .Net core to clone the objects. We will see the different methods one by one in this article.

1. Shallow Copy using MemberwiseClone

The MemberwiseClone method creates a shallow copy of the current object. This means it copies the object's non-static fields to the new object. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not.

using System;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person ShallowCopy()
    {
        return (Person)this.MemberwiseClone();
    }
}

public class Program
{
    public static void Main()
    {
        Person person1 = new Person { Name = "Mohan", Age = 25 };
        Person person2 = person1.ShallowCopy();

        Console.WriteLine($"Original Data: {person1.Name}, {person1.Age}");
        Console.WriteLine($"Shallow Copy Data: {person2.Name}, {person2.Age}");
        Console.ReadKey();
    }
}

Output:

Original Data: Mohan, 25
Shallow Copy Data: Mohan, 25

2. Deep Copy using Serialization

A deep copy is used to create a new object and recursively copy all objects referenced by the fields. We can perform a deep copy using serialization, specifically binary or JSON serialization.

Using JSON Serialization (System.Text.Json) - This method uses System.Text.Json for serialization and deserialization.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static class CloneObject
{
    public static T DeepCopy<T>(T obj)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(ms);
        }
    }
}

public class Program
{
    public static void Main()
    {
        Person person1 = new Person { Name = "Jagan", Age = 28 };
        Person person2 = CloneObject.DeepCopy(person1);

        Console.WriteLine($"Original Data: {person1.Name}, {person1.Age}");
        Console.WriteLine($"Deep Copy Data: {person2.Name}, {person2.Age}");
        Console.ReadKey();
    }
}

Output:

Original Data: Jagan, 28
Deep Copy Data: Jagan, 28

3. Deep Copy using Manual Copying

We can manually copy each field in this approach. This method is simple but complex for huge objects. 

using System;

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Address Address { get; set; }

    public Person DeepCopy()
    {
        return new Person
        {
            Name = this.Name,
            Age = this.Age,
            Address = new Address
            {
                Street = this.Address.Street,
                City = this.Address.City
            }
        };
    }
}

public class Program
{
    public static void Main()
    {
        var person1 = new Person
        {
            Name = "Sumit",
            Age = 35,
            Address = new Address { Street = "1 Abc Street", City = "Mumbai" }
        };

        var person2 = person1.DeepCopy();

        // Modify the original person's address
        person1.Address.Street = "20 Pitt Street";
        person1.Address.City = "London";

        // Display both persons to show that they are different
        Console.WriteLine("Original Person:");
        Console.WriteLine($"Name: {person1.Name}, Age: {person1.Age}, Address: {person1.Address.Street}, {person1.Address.City}");

        Console.WriteLine("Deep Copied Person:");
        Console.WriteLine($"Name: {person2.Name}, Age: {person2.Age}, Address: {person2.Address.Street}, {person2.Address.City}");
        Console.ReadKey();
    }
}

Output:

Original Person:
Name: Sumit, Age: 35, Address: 20 Pitt Street, London
Deep Copied Person:
Name: Sumit, Age: 35, Address: 1 Abc Street, Mumbai

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!