Friday, 26 August 2011

Copy Constructor in C#

         Unlike some languages, C# does not provide a copy constructor. If you create a new object and want to copy the values from an existing object, you have to write the appropriate method yourself.

The following program describes copy constructor...

 class sample
    {
        string nme;
        int number;

        public sample()
        {
       
        }
       
        // Parameterised Constructor.............
        public sample(string name, int no)
        {
            this.nme = name;
            this.number = no;
        }
        // Copy Constructor -------------------------
        public sample (sample object11)
        {
            nme=object11.nme;
            number = object11.number;
           
   
        }

        public void show()
        {
            Console.WriteLine("Name is " + nme);
            Console.WriteLine("Number is " + number);
        }
    }
   
   
   
    class Program
    {
        static void Main(string[] args)
        {
            sample obj = new sample("radha",101);
            sample obj1 = new sample(obj);
            obj.show();
            obj1.show();
            Console.Read();


        }
    }


Output:
Name is radha
Number is 101
Name is radha
Number is 101


No comments:

Post a Comment