#824 – A Copy Constructor Makes a Copy of an Existing Object

A copy constructor is a constructor that you can define which initializes an instance of a class based on a different instance of the same class.

In the example below, we define a copy constructor for Dog.  The constructor creates a new instance of a Dog based on an existing instance.

    public class Dog
        public string Name { get; set; }
        public int Age { get; set; }

        // Constructor that takes individual property values
        public Dog(string name, int age)
            Name = name;
            Age = age;

        // Copy constructor
        public Dog(Dog otherDog)
            Name = otherDog.Name;
            Age = otherDog.Age;

Example of using the copy constructor:

            // Create a dog
            Dog myDog = new Dog("Kirby", 15);

            // Create a copy of Kirby
            Dog other = new Dog(myDog);