Copy Constructor definition with example in C#.Net

Copy Constructor 

C# is not providing any copy constructor. But using different ways we can do that. first we have to create a new object and want to copy all values from a already existing object, for that one we have to write one appropriate method.

You can check other types of constructors also.

Example:

class Program
    {
        static void Main(string[] args)
        {
            car obj1 = new car(3000, "white");
            car obj2 = new car(obj1);
            Console.WriteLine(obj2.details);
        }
    }
    class car
    {
        private int weight = 0;
        private string color = string.Empty;

        //copy constructor
        public car(car previousCar)
        {
            weight = previousCar.weight;
            color = previousCar.color;
        }

        //instance constructor
        public car(int size, string color)
        {
            this.color = color;
            this.weight = size;
        }
       
        //Get Accessor
        public string details
        {
            get
            {
                return "The Color of the car is " + this.color + ". And weight of the car is " + this.weight.ToString();
            }
        }
    }
This is one of the good OOPS Dotnet Interview Question
See more SQL Server, C#.Net, ASP.net Interview Questions
Share this post :

Post a Comment

Please give your valuable feedback on this post. You can submit any ASP.NET article here. We will post that article in this website by your name.

 
Support : Ranga Rajesh Kumar
Copyright © 2012. ASP.NET Examples - All Rights Reserved
Site Designed by Ranga Rajesh Kumar