Real Time Example of Copy Constructor in C#
Understanding Copy Constructors in C#: Real-Time Example
A copy constructor in C# is a constructor used to create a new object as a copy of an existing object. It enables the duplication of an object’s properties while keeping the original and new objects independent. This is particularly useful when you want to create a separate instance without referencing the original object, avoiding unintended changes to the original object’s state.
Code Implementation: Copy Constructor in Action
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
// Example of how a copy constructor works
Employee objEmp = new()
{
EmpId = 1,
FirstName = "lal ju"
};
Console.WriteLine("Original Object (objEmp):");
Console.WriteLine($"EmpId: {objEmp.EmpId}, FirstName: {objEmp.FirstName}");
// Creating a new object using the copy constructor
Employee objEmp2 = new Employee(objEmp);
Console.WriteLine("Copied Object (objEmp2):");
Console.WriteLine($"EmpId: {objEmp2.EmpId}, FirstName: {objEmp2.FirstName}");
// Modifying the original object
objEmp.EmpId = 2;
objEmp.FirstName = "ladli ju";
Console.WriteLine("Modified Original Object (objEmp):");
Console.WriteLine($"EmpId: {objEmp.EmpId}, FirstName: {objEmp.FirstName}");
Console.WriteLine("Copied Object Remains Unchanged (objEmp2):");
Console.WriteLine($"EmpId: {objEmp2.EmpId}, FirstName: {objEmp2.FirstName}");
}
}
public class Employee
{
public int EmpId { get; set; }
public string FirstName { get; set; }
// Default constructor
public Employee()
{
}
// Copy constructor
public Employee(Employee objEmp)
{
this.EmpId = objEmp.EmpId;
this.FirstName = objEmp.FirstName;
}
}
Explanation of the Code:
- Default Constructor: The
Employeeclass contains a parameterless default constructor to initialize new objects. - Copy Constructor: The copy constructor
Employee(Employee objEmp)accepts an existingEmployeeobject as a parameter and assigns its properties (EmpIdandFirstName) to the new object. - Object Duplication: In the
Mainmethod, theobjEmpobject is initialized and printed. A new objectobjEmp2is created using the copy constructor, duplicatingobjEmp’s properties at the time of creation. - Independence of Objects: Changes to the
objEmpobject’s properties (e.g.,EmpIdandFirstName) do not affectobjEmp2, demonstrating the independence of the two objects.
Use Case:
Copy constructors are ideal when working with complex objects where simple assignment may lead to shared references, causing unexpected changes in the original object.
You may also like: Arcserve Backup Solutions | Reliable Dealer & Data Recovery Partner
Leave a Reply
Please log in to comment on this post.