C# Copy Constructor

We have read about Default constructor, Paramterized constructor and Static constructor until now, in this tutorial, we will learn about Copy constructor in C# with an example.

Copy Constructor is used to create object by copying all of it's members, data etc from another object, basically this type of constructors are used for initializing a new instance from an existing one.

So, main purpose of copy constructor is to initialize new instance from the values of an existing instance.

Example of Copy Constructor in C#

Let's take a look at an example for better understand it's concept.

using System;
					
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

	//default constructor
    public Person() { 
	}
	
   //parameterized constructor
    public Person(Person objPerson)
    {    
        this.Name = objPerson.Name;
        this.Age = objPerson.Age;
    }
}

public class CopyConstructor
{
	public static void Main()		
	{
		Person person1 = new Person();
		person1.Name = "John Wick";
		person1.Age = 30;
		Console.WriteLine("Name from First Object :"+person1.Name);
		Console.WriteLine("Age from First Object :"+person1.Age);
        Console.WriteLine(); 
		
		 //Copied value in second object, using Copy Constructor concept
		Person copiedPerson = new Person(person1);
		Console.WriteLine("Name from Second Object :"+copiedPerson.Name);
		Console.WriteLine("Age from Second Object :"+copiedPerson.Age);
	}
}

Output

Name from First Object :John Wick
Age from First Object :30

Name from Second Object :John Wick
Age from Second Object :30

As you can see in the above example, we have created a class named as "Person", and have also declared it's default constructor and parameterized constructor.

We are creating initial object and assigning Person class variables (Name and Age) values using First object (person1), but second object is copied from first one and hence contructor for this object, is called as copy contructor, we are copying values in second object (copiedPerson) in this line

Person copiedPerson = new Person(person1);

so when we try to print values of Age,Name it prints same details as first constructor.

You might also like to read:

C# Array

C# Multidimensional array

C# Jagged array

Abstract Class in C#

C# Class and Objects

C# Inheritance


Share Tweet