22 Sep 2017

what is copy constructor in C sharp with example


copy constructor can be used to create an object copy the value from another object it is called copy constructor.

Example-
                     Suppose that if you want to create a new object you wand to copy the value another object. 

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

namespace what_is_copy_constructor
{
  public class Rock
    {
        public string Name;
        public int Age;
        public Rock(string X, int Y)//instance constructor //
        {
            Name = X;
            Age= Y;
        }
        public Rock(Rock Obj)//Declaring Copy Constructor//  

        {
            Name = Obj.Name;
            Age = Obj.Age;
        }
        public void print()
        {
            Console.WriteLine("{0},{1}", Name, Age);
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Rock Obj = new Rock("Rock Programmer",25); //create the new object

            Rock Obj1 = new Rock(Obj);//copy the object
            Obj.print();
            Obj1.print();
            Console.ReadKey();

        }
    }
}
out put:-

1 comment:
Write comments

Popular Posts

Popular Posts

Translate

Total Pageviews