Copy Constructor in C#

Description:

In my previous post, I have explained about the Default constructorParameterized constructor, Static constructor and Private Constructor.

Now in this post, I’ll explain in details about the copy constructor with example.

Copy Constructor in C#

C# does not provide a copy constructor for the objects but as a developer, we can write one by ourselves based on our requirement.

Copy constructor: In C#, A parameterized constructor that takes the same type of object as a parameter is called a copy constructor.

The copy constructor is useful when we want to copy data from the existing object to the new object without affecting the values of the existing object.
In simple words, copy constructor means cloning of data from one object to the other object.

Note: To create a copy constructor we must have more than one constructor in a class.

Copy Constructor Syntax

Syntax to create a copy constructor in C#

   // Class
    public class User
    {
        // Parameterized Constructor
        public User(int id, string name)
        {
                  
        }

        //Copy constructor
       public User(User previousUser)
        {
           //Business logic code
        }
    }

In the above syntax, we are passing the same class type ‘User’ as a parameter in the copy constructor. It will create a new object with the same values from the existing object.

Example of Copy Constructor in C#

using System;
namespace CopyConstructor
{  
    // Class
    public class User
    {
        //Instance variables
        public int Id;
        public string Name;

        // Parameterized Constructor
        public User(int id, string name)
        {
            this.Id = id;
            this.Name = name;                
        }

        //Copy Constructor
       public User(User previousUser)
        {
            this.Id = previousUser.Id;
            this.Name = previousUser.Name;       
        }

        //Print person details
        public void PrintDetail()
        {
          Console.WriteLine($"Id: {Id} Name: {Name}");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

       // This will invoke instance constructor
            User user1 = new User(10,"Shekh Ali");

       // This will invoke copy constructor
       // Creating another User object by copying user1
            User user2 = new User(user1);

       // Change user2 Id and Name
            user2.Id = 20;
            user2.Name = "Klara";

       // Print details to verify that the 
       // Id and Name fields are unique.
            user1.PrintDetail();
            user2.PrintDetail();
            Console.ReadLine();
        } 
    }
    /* Output:
     Id: 10 Name: Shekh Ali
     Id: 20 Name: Klara

     */
}

Copy constructor output
The output of the above copy constructor program.

Here we have created a new instance ‘user2’ after passing the ‘User’ object as a parameter in the copy constructor.
All the instance field values from ‘user1’ object have been copied to the new object ‘user2’.
When we assign the new values in the object ‘user2’, it will not affect the values of the existing object ‘user1’.

Using ICloneable Interface to creates a copy of an existing object in C#

In the above program, we are using a copy constructor to clone one object to another, We can do the same thing by using the ICloneable Interface.

Below is the simple example of cloning by using ICloneable Interface in C#.

using System;
namespace ShallowCopy
{  
    //User Class implements ICloneable Interface
    public class User: ICloneable
    {
        //Instance variables
        public int Id;
        public string Name;

        // Parameterized Constructor
        public User(int id, string name)
        {
            this.Id = id;
            this.Name = name;                
        }

        //Using Shallow Copy
        public object Clone()
        {
            return this.MemberwiseClone();
        }

        //Print person details
        public void PrintDetail()
        {
          Console.WriteLine($"Id: {Id} Name: {Name}");
        }
       
    }
    class Program
    {
        static void Main(string[] args)
        {

       // This will invoke instance constructor
            User user1 = new User(10,"Shekh Ali");

       // Performing shallow copy of 'user1' and assign it to 'user2'.
            User user2 = (User)user1.Clone();

       // Change user2 Id and Name
            user2.Id = 20;
            user2.Name = "Klara";

       // Print details to verify that the 
       // Id and Name fields are unique.
            user1.PrintDetail();
            user2.PrintDetail();
            Console.ReadLine();
        } 
    }
    /* Output:
     Id: 10 Name: Shekh Ali
     Id: 20 Name: Klara
     
     */
}


In C#, The ICloneable interface has a single method Clone() to creates a copy of the existing object.
In the above example, In the Clone method we are using MemberwiseClone() method of the object class.
MemberwiseClone method is responsible to create a shallow copy by creating a new object. And then copying the non-static fields of the current object to the new object.

Hope you enjoyed this post. Thanks for visiting.

Leave a Reply