Copy Constructor in C#

Constructor is similar to method, which has same name of class name , which is invoked when an object an is create.
 we used this methods generally for intialisations;

Types of Constructors :

1)Default - doesnt have any arguments
2)Paramterized- have arguments 
3)copy constructor:

This copy constructor is invoked when an object is copied from other object.

When there is a copy constructor we need to write default constructor.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
       {
           employee e = new employee();
           e.ReadData();
            employee f = new employee(e);// classname obj = new classname(orj)
           f.getData();
            
           //Syntax to create array of objects
           Console.Read();
        }
    }
    class employee
    {
        private int eno;
        private string eName;
        private double sal;

        public employee()
        {

        }

        public employee(employee prev)
        {
            eno = prev.eno;
            eName = prev.eName;
            sal = prev.sal;
        }

        public void getData()
        {
            Console.WriteLine("Eno :-" + eno + " Ename :-" + eName+ " Ename :-" + eName);
        }
        public void ReadData()
        {
            Console.Write("enter Eno :");
            eno = Convert.ToInt32(Console.ReadLine());
            Console.Write("enter Ename :");
            eName = Console.ReadLine();
            Console.Write("enter Sal :");
            sal = Convert.ToDouble(Console.ReadLine());

        }
    }
}

Copy Constructor in C# Copy Constructor in C# Reviewed by Share less to Learn More on 6:47 PM Rating: 5

No comments