#827 – Making a Deep Copy with a Copy Constructor

The semantics that you use within a copy constructor can be to make a shallow copy of an object or a deep copy.

In the example below, the copy constructor for Dog makes a deep copy of the object passed in.  In this case, that means that the new Dog that is created will also have a new instance of DogCollar object, copied from the DogCollar property of the original Dog object.

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

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

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

            Collar = (otherDog.Collar != null) ?
                new DogCollar(otherDog.Collar.Length, otherDog.Collar.Width) :
                null;
        }
    }
Advertisement