In C#, the copy constructor allows us to create a new instance of an object with the same values as an existing object.
This article will take you through the fundamentals of copy constructors in C# with code examples.

Table of Contents
- 1 What is a Copy Constructor in C#?Â
- 2 Syntax of a Copy Constructor in C#:
- 3 Benefits of Using Copy Constructors:
- 4 How to create a copy constructor in C#?
- 5 How to write a copy constructor using ICloneable Interface?
- 6 Rules for copy constructors in C#
- 7 Types of constructors in C#
- 8 FAQs
- 8.1 Q1: What is the purpose of a copy constructor in C#?
- 8.2 Q2: Can a copy constructor have a different name than the class or structure?
- 8.3 Q3: Can a copy constructor return a value?
- 8.4 Q4: Can a copy constructor be inherited in C#?
- 8.5 Q5: Is it possible to declare a copy constructor as static?
- 8.6 Q6: Can I modify the values of the copy without affecting the original object?
- 9 Conclusion:
What is a Copy Constructor in C#?Â
A copy constructor is a special constructor that creates a new object by copying the values of an existing object of the same class. It enables the creation of an independent object with the same values as the original, which can be modified without affecting the original object.
In other words, a copy constructor is a parameterized constructor that accepts objects of the same type as its parameters. Its purpose is to generate a new object that retains the same data values as the original while leaving the original object unaffected.
Syntax of a Copy Constructor in C#:
In C#, a copy constructor is declared using the class name followed by the constructor keyword, taking an instance of the same class as a parameter.Â
class MyClass
{
//Copy constructor
public MyClass(MyClass original)
{
// Assign values from 'original' to the current object
}
}
We are passing the same class type ‘MyClass’ as a parameter in the copy constructor in the above syntax. It will create a new object with the same values as the existing object.
Benefits of Using Copy Constructors:
- Object Cloning: Copy constructors allow us to clone objects easily, ensuring independent copies with identical values.
- Immutable Objects: Copy constructors are useful when working with immutable objects, where you want to create new instances with the same state.
- Class Composition: When a class consists of other objects, a copy constructor ensures that all the composed objects are copied correctly.
How to create a copy constructor in C#?
The following code example demonstrates how to create a copy constructor.
using System;
namespace CopyConstructor
{ // C# program demonstrating how to use the copy constructor
// Class
public class User
{
//Instance variables
public int Id;
public string Name;
// Parameterized Constructor
public User(int id, string name)
{
this.Id = id;
this.Name = name;
}
//Copy Constructor
public User(User previousUser)
{
this.Id = previousUser.Id;
this.Name = previousUser.Name;
}
//Print person details
public void PrintDetail()
{
Console.WriteLine($"Id: {Id} Name: {Name}");
}
}
class Program
{
static void Main(string[] args)
{
// This will invoke instance constructor
User user1 = new User(10,"Shekh Ali");
// This will invoke copy constructor
// Creating another User object by copying user1
User user2 = new User(user1);
// Change user2 Id and Name
user2.Id = 20;
user2.Name = "Klara";
// Print details to verify that the
// Id and Name fields are unique.
user1.PrintDetail();
user2.PrintDetail();
Console.ReadLine();
}
}
/* Output:
Id: 10 Name: Shekh Ali
Id: 20 Name: Klara
*/
}

Here, we create a new user2 instance after passing the User1 object as a parameter in the copy constructor.
All instance field values ​​of the object User1 has been copied to the new object user2.
When we assign the new values in the object ‘user2’, it will not affect the existing object ‘user1’ values.
How to write a copy constructor using ICloneable Interface?
In the above program, we are using a copy constructor to clone one object to another, We can do the same thing by using the ICloneable
Interface.
Below is a simple example of cloning by using ICloneable Interface in C#.
using System;
namespace ShallowCopy
{
// C# program demonstrating how to use the copy constructor
// User Class implements ICloneable Interface
public class User: ICloneable
{
//Instance variables
public int Id;
public string Name;
// Parameterized Constructor
public User(int id, string name)
{
this.Id = id;
this.Name = name;
}
//Using Shallow Copy
public object Clone()
{
return this.MemberwiseClone();
}
//Print person details
public void PrintDetail()
{
Console.WriteLine($"Id: {Id} Name: {Name}");
}
}
class Program
{
static void Main(string[] args)
{
// This will invoke instance constructor
User user1 = new User(10,"Shekh Ali");
// Performing shallow copy of 'user1' and assign it to 'user2'.
User user2 = (User)user1.Clone();
// Change user2 Id and Name
user2.Id = 20;
user2.Name = "Klara";
// Print details to verify that the
// Id and Name fields are unique.
user1.PrintDetail();
user2.PrintDetail();
Console.ReadLine();
}
}
/* Output:
Id: 10 Name: Shekh Ali
Id: 20 Name: Klara
*/
}
In C#, The ICloneable interface has a single method Clone() to creates a copy of the existing object.
In the above example, In the Clone method we are using MemberwiseClone()
method of the object class.
The MemberwiseClone()
method is responsible for creating a shallow copy by creating a new object. Then copy the non-static fields from the current object to the new object.
Rules for copy constructors in C#
- Name: The copy constructor in C# must have the same name as the class or structure it belongs to.
- Return Type: Unlike regular constructors, the copy constructor does not have a return type, not even “void.” It is solely responsible for initializing the new instance.
- Inheritance: Copy constructors cannot be inherited in C#. Each class or structure must define its own copy constructor if needed.
- Static: Copy constructors cannot be declared as static. They are instance constructors and operate on specific objects.
- Purpose: The primary purpose of a copy constructor is to initialize a new instance of a class or structure with the values of an existing instance. It creates an independent copy that can be modified without affecting the original object.
Types of constructors in C#
There are five different types of constructors in C#.
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Static Constructor
- Private Constructor
FAQs
Here are some frequently asked questions (FAQs)
Q1: What is the purpose of a copy constructor in C#?
The main purpose of a copy constructor in C# is to create a new instance of a class or structure with the same values as an existing instance. It allows for the creation of independent copies that can be modified without affecting the original object.
Q2: Can a copy constructor have a different name than the class or structure?
No, in C#, the copy constructor must have the same name as the class or structure it belongs to.
Q3: Can a copy constructor return a value?
No, a copy constructor in C# has no return type, including “void.” Its purpose is to initialize the new instance, not return a value.
Q4: Can a copy constructor be inherited in C#?
No, copy constructors cannot be inherited in C#. Each class or structure must define its own copy constructor if needed.
Q5: Is it possible to declare a copy constructor as static?
No, copy constructors cannot be declared as static. They are instance constructors and operate on specific objects.
Q6: Can I modify the values of the copy without affecting the original object?
Yes, the copy constructor creates an independent copy, allowing you to modify the values of the copy without affecting the original object.
Conclusion:
In conclusion, understanding copy constructors in C# is important for creating independent copies of objects. This article has provided a comprehensive guide on copy constructors, explaining their purpose, rules, and usage with code examples. By implementing copy constructors, you can easily create new instances with the same values as existing objects, ensuring data integrity and modifiability.
Recommended Articles:
- Constructors in C# with Examples
- Array Vs List in C#
- Difference between var and dynamic in C#
- Generic Delegates in C# With Examples
- IEnumerable Interface in C# with examples
- Properties In C# with examples
- 10 Difference between interface and abstract class In C#
- Value Type and Reference Type in C#
- C# Dictionary with Examples
- C# Struct vs Class
- C# Hashtable vs Dictionary
- C# Events: Differences between delegates and events in C#
- Difference between Boxing and Unboxing in C#
We hope you find this article informative and helpful. If you have any questions, feel free to ask them in the comments section below.
- Program to find the maximum and minimum number in an array with examples - December 10, 2023
- Program to Remove Duplicate Elements from an Array with examples - December 8, 2023
- Program To Find Largest Number In An Array - December 8, 2023