Copy Constructor In C# With Examples

In this article, we will learn more about the C# copy constructor through examples. In the previous article, we learned about the Default constructorParameterized constructor, Static constructor and Private Constructor.

‘Copy Constructor in C#’

In C#, The Copy constructor is a constructor that creates an object by cloning data from one object to another. It can be used to copy data from an existing object to a new object without changing the value of the existing object. The copy constructor is a parameterized constructor that accepts objects of the same type as parameters.

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

A class can have multiple constructors in order to create a copy constructor.

Syntax

The following is the syntax for declaring 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
        }
    }

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

How to write a copy constructor in C#?

The following code example demonstrates how to write a copy constructor.

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 create a new user2 instance after passing the User1 object as a parameter in the copy constructor.
All instance field values ​​of the object
User1 has been copied to the new object user2.
When we assign the new values in the object ‘user2’, it will not affect the existing object ‘user1’ values.

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 a 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.
The MemberwiseClone() method is responsible for creating a shallow copy by creating a new object. Then copy the non-static fields from the current object to the new object.

C# copy constructor rules

    • The copy constructor must have the same name as the name of the class or structure.
    • It does not contain a return type, not even void.
    • The copy constructor cannot be inherited in C#.
    • It cannot be static.
    • A class can have multiple constructors in order to create a copy constructor.
    • Its main purpose is to initialize a new instance with the value of an existing instance.

Recommended Articles

    1. Generic Delegates in C# With Examples
    2. IEnumerable Interface in C# with examples
    3. Constructors in C# with Examples
    4. Properties In C# with examples
    5. 10 Difference between interface and abstract class In C#
    6. Value Type and Reference Type in C#
    7. C# Dictionary with Examples

Hope you like this article, if you have any questions, please ask your questions in the comment section below.
Thank you for visiting. 🙂

Leave a Reply