The constructor which creates an object by coping variable from another object is called copy constructor. the purpose of copy constructor is to initialize a new instance to values of existing instance.
The copy constructor is invoked by instantiating an object of type employee and bypassing it the object to be copied
 using System;
                    
public class Program
{
    public static void Main()
    {
        Employee emp=new Employee(101,"Aman");
        
        Employee copyEmp=new Employee(emp);
        Console.WriteLine("Id of Employee {0}",copyEmp.Id);
        Console.WriteLine("Name of Employee {0}",copyEmp.name);
    }
}
public class Employee{
    public int Id;
    public string name;
    public Employee(int id,string empName){ //Instance constructor
        this.Id=id;
        this.name=empName;
    }
    public Employee(Employee emp){ //Declaring copy constructor
        this.Id=emp.Id;
        this.name=emp.name;
    }
    
} Output :  Id of Employee 101
Name of Employee Aman   
No comments:
Post a Comment