#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;
        }
    }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #827 – Making a Deep Copy with a Copy Constructor

  1. Elliott says:

    May I ask…. what is the advantage and disadvantage of implementing the copy constructor and ICloneable.Clone ?
    um… With talking about the best practice, which one you think should be more good to be used ?

    Cheers,
    Elliott

  2. Alex says:

    Should “Name = otherDog.Name;” be “Name = String.Copy(otherDog.Name);” ? In order to make it a deep copy?

    • Sean says:

      I don’t think there’s a need. Since strings are immutable, both objects have the same copy and if you changed the value in otherDog, it wouldn’t affect the copy pointed to by the new object.

Leave a comment