Concept of Deep Copy in C#

Mannan Ul Haq
0
In the world of programming, there's often a need to create an exact copy of an object – where altering one doesn't affect the other. This is known as a 'deep copy' and plays a crucial role when working with classes in C#. 

In C#, classes are reference types. This means that when you create an object of a class and assign it to another object, they both point to the same location in memory. Consequently, modifying one object results in changes to the other as well. To avoid this scenario and ensure the objects are independent, we need to perform a 'deep copy'.

One simple and intuitive way to achieve a deep copy is through the manual copying approach, also known as the copy constructor method. 

Let's illustrate this with an easy-to-understand example. Consider a class `Student`:

class Student
{
    public string name;
    public int age;
}

The `Student` class has two fields: `name` and `age`. We can create a `Student` object like so:

Student student1 = new Student();
student1.name = "Alice";
student1.age = 20;

Now, if we try to copy `student1` to a new `Student` object `student2`:

Student student2 = student1;

It is important to note that `student1` and `student2` will both point to the same object in memory. Consequently, any modification in `student2` will also reflect in `student1`.

However, if we want to create a separate copy of the `student1` object, we can add a copy constructor to our `Student` class. The copy constructor is a special constructor that takes an object of the same class as a parameter and copies its fields to the new object.

Here's how we modify our `Student` class to include a copy constructor:

class Student
{
    public string name;
    public int age;

    // Copy constructor.
    public Student(Student previousStudent)
    {
        name = previousStudent.name;
        age = previousStudent.age;
    }
}

This constructor takes an existing `Student` object and copies its fields into a new instance.

With this in place, we can now create a deep copy of `student1`:

Student student1 = new Student();
student1.name = "Alice";
student1.age = 20;

// Use the copy constructor to create a new object.
Student student2 = new Student(student1);

// Change a field on student2. This won't affect student1.
student2.name = "Bob";

Console.WriteLine(student1.name);  // Outputs: "Alice"
Console.WriteLine(student2.name);  // Outputs: "Bob"

In this example, altering the `name` on `student2` does not affect `student1`, because they are now two separate objects in memory.

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !