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

TechEd Barcelona 2008 - Day 1.1

10. November 2008

Yesterday I arrived in Barcelona to attend Microsoft TechEd 2008. After a pleasant flight (with a small, normal, big fuel leak - what's it going to be captain?) and long trip to the hotel we arrived at our hotel right next to the CCIB. We went out for some tapas at around twelve o'clock and I must say, here in Spain they know how to make them.

 So now I'm going to head of to register myself downstairs and grab some lunch later on.

Be the first to rate this post

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

Development, Varia ,