Generic Cloning Method in c#

20. November 2008

Since I found my drive again to create some code after I attended TechEd last week. Here's number 1 in what should become a nice code library.

 So you would like to clone an object do you? And you don't want to start writing code in each class or factory service for a certain object type do you?

Well here's one solution that goes for all object that are serializable, and we make all are classes serializable these days, don't we.

/// <summary>
/// Creates a cloned decoupled object from a serializable source object
/// </summary>
/// <typeparam name="T">The type of the object to clone</typeparam>
/// <param name="objectToClone">The object to clone</param>
/// <returns>A decoupled copy of the source object</returns>
public static T Clone<T>(T objectToClone)
{
  // Initialize to default null
  T clone = default(T);
  MemoryStream memoryStream = null;
  try
  {
    BinaryFormatter bf = new BinaryFormatter();
    memoryStream = new MemoryStream();
 
    // Serialize the object in memory
   bf.Serialize(memoryStream, objectToClone);
 
    // Make sure all is loaded in the stream
    memoryStream.Flush();
 
    // Reset the position
    memoryStream.Position = 0;
    // Decoupled copy of the original object
   clone = ((T) bf.Deserialize(memoryStream));
  }
  catch(Exception err)
  {
    LogService.LogError("Failed to clone an object.", err);
  }
  finally
  {
     if (memoryStream != null)
    {
      memoryStream.Close();
      memoryStream.Dispose();
    }
  }
  return clone;
}

Currently rated 2.0 by 2 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Development

Comments