Monday, March 18, 2013

Shallow Copy vs Deep Copy

Hi,

Shallow copy : is where the value type members of an object are copied to a new object where as for reference type objects the reference of the original object is stored in new object so any changes in new object will be reflected to the old object.


Deep Copy: Is where the value type & reference type members of an object are copied to a new object so any changes in the new object does not reflect to the old object.



A Deep Copier sample method which can be very useful.

 using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;    
     
/// <summary> /// Provides a method for performing a deep copy of an object. /// Binary Serialization is used to perform the copy. /// </summary>

public static class CopierFactory
{

/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="sourceobject">The object instance to copy.</param>
 /// <returns>The copied object.</returns>

public static T Clone<T>(T sourceobject)
{
  if (!typeof(T).IsSerializable)
  {
    throw new ArgumentException("The type must be serializable.", "source");
  }
 
  // Don't serialize a null object, simply return the default for that object

 if (Object.ReferenceEquals(sourceobject, null))
  {
    return default(T);
  }

IFormatter formatter = new BinaryFormatter();
  Stream memorystream = new MemoryStream();
  using (memorystream )
  {
     formatter.Serialize(memorystream , sourceobject);
     memorystream.Position =0;
     return (T)formatter.Deserialize(memorystream );
  }
}
}

No comments: