#825 – Shallow Copies

When making a copy of an object, you can either make a shallow copy or a deep copy.  A shallow copy is one in which the exact values of all data members of the object are copied.  You can think of this as byte-for-byte copy of the original object.

With a shallow copy, reference-typed members are copied by copying the reference to the object, rather than by making a new copy of the child object.

For example, if a Dog object contains a reference to a DogCollar object and we make a shallow copy, we get the following:

825-001

The problem with a shallow copy is that the second object is now referencing the sub-objects that the first object pointed to.  In many cases, this may not be what you want.  In the example above, if we change the first dog’s collar, we also change the second dog’s collar.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

5 Responses to #825 – Shallow Copies

  1. Pingback: Dew Drop – April 18, 2013 (#1,530) | Alvin Ashcraft's Morning Dew

  2. Pingback: #828 – Implementing Both a Copy Constructor and ICloneable | 2,000 Things You Should Know About C#

  3. Pingback: #829 – Add Comments to Indicate Shallow vs. Deep Copying | 2,000 Things You Should Know About C#

  4. Pingback: #830 – The Problem with ICloneable | 2,000 Things You Should Know About C#

  5. Yann Duran says:

    Hi Sean,

    “if we change the first dog’s collar, we also change the second dog’s collar”

    I don’t think that’s right. Unnless you meant if you change any of the details in DogCollar #1, then Dog #2 will display the same property values as Dog #1, but if you set Dog # 1’s collar to NewDogCollar , Dog # 2 will still have DogCollar # 1 as its collar. In other words, setting Dog # 1’s collar to a new collar doesn’t affect Dog #2 at all.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: