C# - Shallow vs. Deep copy

Shallow Copy

Value type fields are copied bitwise.
Reference type fields are copied bitwise.
A bitwise copy is a simple memory copy.
The source bits are copied bit-for-bit (or byte for byte) to the destination.
In C++, we would write: memcpy(dest, src, sizeof(src));

Deep Copy

Value type fields are copied bitwise.
Reference type fields are copied by creating a new instance of the object.

An example:


Our CWebPage class has a reference type, and a value type.


  class CWebPage
  {
      public Uri Uri; // This is a reference type
      public int Count; // This is a value type
  }
  

We will implement ICloneable twice.
Once to create a shallow copy of CWebPage.
Once to create a deep copy of CWebPage.


ICloneable implementing a shallow copy:


  class CWebPage : ICloneable
  {
      public Uri Uri;
      public int Count;
      
      public object Clone()
      {
          return base.MemberwiseClone();
          // or
          return new CWebPage
          {
              Uri = this.Uri,
              Count = this.Count,
          };
      }
  }
  

ICloneable implementing a deep copy:


  class CWebPage : ICloneable
  {
      public Uri Uri;
      public int Count;
      
      public object Clone()
      {
          return new CWebPage
          {
              Uri = new Uri(this.Uri.OriginalString),
              Count = this.Count,
          };
      }
  }
  

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath