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 theDogCollar property of the original Dog object.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 = <span class="skimlinks-unlinked">otherDog.Name</span>;
        Age = <span class="skimlinks-unlinked">otherDog.Age</span>;
 
        Collar = (otherDog.Collar != null) ?
            new DogCollar(otherDog.Collar.Length, <span class="skimlinks-unlinked">otherDog.Collar.Width</span>) :
            null;
    }
}