Saturday, January 12, 2013

What is Copy Constructor in C#?


Copy constructor

Copy constructor is one type of constructor. It creates an object by coping value from another object.

C# does not provide a copy constructor. If you want to create an object of a class and want to copy value from the existing object, you have to write the appropriate method for that.

Example

The Employee class contains a constructor which takes Employee class object as a parameter and assign the value from the parameter object into another new object.
     
    public class Employee
    {
        private string _name;
        private int _sal;

        // Copy constructor.
        public Employee(Employee employeeObj)
        {
            _name = employeeObj._name;
            _sal = employeeObj._sal;
        }

        // Instance constructor.
        public Employee(string name, int sal)
        {
            this._name = name;
            this._sal = sal;
        }

        public string Name
        {
            get
            {
                return _name;
            }
        }
    }

    public class DisplayEmployee
    {
        static void Main()
        {
            // a new Employee class object Create.
            Employee employee1 = new Employee("Shweta", 4000);

            // Create one more new object and copying employee1 value.
            Employee employee2 = new Employee(employee1);

            Console.WriteLine(employee2.Name);          
        }
    }

Output

Shweta


No comments:

Post a Comment