Understanding Copy Constructor in C#

Dear reader,

Today we will learn about an interesting concept called as a copy constructor in C#. Now copy constructor is not an unique concept to C#. It is aslo available in other progamming languages such as C++ and Java

Let us quickly start adding some code and then try to understant the concept of copy constructory. For this use your Visual Studio to create a new console project and add a class called Employee to that.

class Employee
{

}

Now add two properties Name and Age

class Employee
{
        public string Name { get; set; }
        public int Age { get; set; }
}

Add a constructor that takes a string and an integer which initializes the class members

class Employee
{
        public string Name { get; set; }
        public int Age { get; set; }

        public Employee(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }
}

The constructor above takes two argument of name and age and initializes the class member. Now we will write our copy constructor. This copy constructor take an argument to Employee itself(or the type of the class) and initializes the values.

class Employee
{
        public string Name { get; set; }
        public int Age { get; set; }

        public Employee(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }
        public Employee(Employee e) // Copy Constructor
        {
            this.Name = e.Name;
            this.Age = e.Age;
        }

}

Now let us go to our Main method and create an instance of our Employee class.

Employee e1 = new Employee("Mike", 30);

Here we are creating an objec of class Employee as e1 and passing a string and a number as parameter which corresponds to name and age respectively. With e1 being created, let us create another object e2 using the assignment operator and e3 using our copy constructor.

// Creating employee by assignment
 Employee e2 = e1;

// Creating employee using copy construcor
Employee e3 = new Employee(e1);

Now here comes the insetesting part. Since e2 is created with assignment opertor, it holds a memory reference to that of e1. So if anything changes in e1 the same will be reflected in e2 as well and vice-versa is also true. Let us see the below code snippet for a better understanding.

Console.WriteLine(e1.Name);  // Output: Mike
e2.Name = "John";
Console.WriteLine(e1.Name);  // Output: John

Here in the first line I have printed the value of name from e1 object, which says Mike(as initialized). In the next line I have update the value of Name from object e2(see carefully, I have updated e2 and not e1). With that update, both e1 and e2 will be updated since both of them are pointing to the same memory location. Hence updating one will update the other as well.

This sometimes can be an advantage if used properly, but can be a real pain, if the concept is unknown. Hence comes our copy constructor to our rescue. Remember we created another object e3 by passing e1 as its constructor argument. Let us do the same experiment with e1 and e3 that we did for e1 and e2.

Console.WriteLine(e1.Name);  // Output: Mike
e3.Name = "John";
Console.WriteLine(e1.Name);  // Output: Mike

As you can see in the above example the name is not changed for e1 when we update the name value for e3. The reason is that it was not created with assignment operator and hence do not share the same memory location. They have both different memory locations.

Now you have to be very carefull while using a copy constructor because at first it might seem that it will save us lot of debugging time, but also will consume extra memory as both the object will occupy different memory. When the size of you application will grow, copy constructor will very quickly consume memory and might create performance issues for you application.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: