In c#, Copy Constructor is a parameterized constructor that contains a parameter of the same class type. The copy constructor in c# is useful whenever we want to initialize a new instance to the values of an existing instance.
In simple words, we can say copy constructor is a constructor that copies the data of one object into another object. Generally, c# won’t provide a copy constructor for objects but we can implement ourselves based on our requirements.
Following is the syntax of defining a copy constructor in c# programming language.
class User
{
// Parameterized Constructor
public User(string a, string b)
{
// your code
}
// Copy Constructor
public User(User user)
{
// your code
}
}
If you observe the above syntax, we created a copy constructor with a parameter of the same class type and it helps us to initialize a new instance to the values of an existing instance.
Following is the example of creating a copy constructor to initialize a new instance to the values of an existing instance in c# programming language.
using System;
namespace Tutlane
{
class User
{
public string name, location;
// Parameterized Constructor
public User(string a, string b)
{
name = a;
location = b;
}
// Copy Constructor
public User(User user)
{
name = user.name;
location = user.location;
}
}
class Program
{
static void Main(string[] args)
{
// User object with Parameterized constructor
User user = new User("Suresh Dasari", "Hyderabad");
// Another User object (user1) by copying user details
User user1 = new User(user);
user1.name = "Rohini Alavala";
user1.location = "Guntur";
Console.WriteLine(user.name + ", " + user.location);
Console.WriteLine(user1.name + ", " + user1.location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we created an instance of copy constructor (user1) and using an instance of user object as a parameter type. So the properties of user object will be send to user1 object and we are changing the property values of user1 object but those will not effect the user object property values.
When you execute the above c# program, you will get the result as shown below.
If you observe the above result, we initialized a new instance to the values of an existing instance but those changes not effected the existing instance values.
This is how you can use a copy constructor in c# programming language to create a constructor with the parameter of the same class type based on our requirements.