Monday, March 9, 2009

Copy Construtor Myth

Unlike some languages, C# does not provide a copy constructor.
If you create a new object and want to copy the values from an existing object, you have to write the appropriate method yourself.

Copy constructor implementation support ‘Deep Copy’. i.e Change in one does not affect the other.

class Employee
        public int age;
        public string city;

        // Instance constructor
        public Employee(int age, string city)
            this.age = age;
   = city;

        // Copy constructor
        public Employee(Employee obj)
            age = obj.age;
            city =;

        public string Details
                return " Age is: " + age.ToString() + " City is: " + city;
void main()
    Employee emp1 = new Employee(55,"Boston");
    Employee emp2 = new Employee(emp1); // Explicit call to Copy Constructor

    MessageBox.Show(emp1.Details); // 55 & Boston
    emp2.age = 66;

    MessageBox.Show(emp1.Details); // 55 & Boston – No Change
   // Here  No Change as its a Deep copy

Note –  The C++ approach below.

Employee emp2;
emp2 = emp1;

In C++, this assignment statement automatically makes call to Copy Constructor and will provide a Shallow copy.
But in C# this approach will not call the defined Copy Constructor. Reason - C# does not provide a copy constructor. Hence this will result in Shallow Copy.

Arun Manglick

No comments:

Post a Comment