Generic Cloning Method in c#

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;
}

Tags:

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading


Björn Bailleul

Web application engineer and developer interested in creating customer centric applications build for ease of use and efficiency. My experience goes from intranet applications to widely used service websites, product portfolios and e-commerce websites.

Specialties

C#, MVC, AJAX, ASP.NET, SQL Server, SQL Reporting Services, WCF, XML, HTML, JavaScript, CSS, Web Services, Scrum, ...

View Bjorn Bailleul's profile on LinkedIn

Month List