Post Details

Real Time Example of Copy Constructor in C#

np

Thu , Nov 23 2023

np
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 Employee class contains a parameterless default constructor to initialize new objects.
  • Copy Constructor: The copy constructor Employee(Employee objEmp) accepts an existing Employee object as a parameter and assigns its properties (EmpId and FirstName) to the new object.
  • Object Duplication: In the Main method, the objEmp object is initialized and printed. A new object objEmp2 is created using the copy constructor, duplicating objEmp’s properties at the time of creation.
  • Independence of Objects: Changes to the objEmp object’s properties (e.g., EmpId and FirstName) do not affect objEmp2, 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.

Leave a Reply

Please log in to Comment On this post.