How to Create Copy Constructor in C#

Leave a Comment
A copy constructor is used to create a copy of an existing object as new object. This constructor takes the reference of the object to be copied as an argument.

C# does not provide the copy constructor by default; however, you can have an identical copy of an existing object.

To create identical copies of an object having same value for properties and members as the source object, you need to write a separate method or copy a constructor, as shown in the following code snippet -
Class Example {
//Create a new CarDetails Object.
 Static CarDetails car1 = new CarDetails("Zen Estilo VXI", 15.7);
 //Create another new object, copying car1.
     CarDetails car2 = new CarDetails(Example.car1);
Class CarDetails
  {
    //Data Members
    public CarDetails(CarDetails MyCar)  //Copy constructor.
    {
        //Constructor Body
    }
public CarDetails(string ModelName, double Mileage)
     //Instance Constructor
    {
        //Constructor Body
    }
  }
}

In the preceding code snippet, the CarDetails constructor is called. A new car1 object is created and then another new object, car2, is created that copies the car1 object.

Example of the Copy Constructor

Open Visual Studio then create new Console Application named MyCopyConstructor and then replace the default code of the Program.cs file of the application with the code shown in below -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyCopyConstructor
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new CarDetails object.
            CarDetails car1 = new CarDetails("Zen Estilo VXI", 15.7);

            // Create another new object, copying car1.
            CarDetails car2 = new CarDetails(car1);
            Console.WriteLine(car2.Details);
          
        }
    }
    class CarDetails
    {
        private string ModelName;
        private double Mileage;
        // Copy constructor.
        public CarDetails(CarDetails MyCar)
        {
            ModelName = MyCar.ModelName;
            Mileage = MyCar.Mileage;
        }
        // Instance constructor.
        public CarDetails(string ModelName, double Mileage)
        {
            this.ModelName = ModelName;
            this.Mileage = Mileage;
        }
        public String Details
        {
            get
            {
                return ("Car " + ModelName + " has the Average of " + Mileage + "km/lit");
            }
        }
    }
}
In above Program, we first create an object of the CarDetails classs, car1, by passing two arguments to the constructor of the CarDetails class. Then, we create another object of the CarDetails class, car2, by copying the data of the car1 object.

0 comments:

Post a Comment