Click here to Skip to main content
Licence CPOL
First Posted 22 Feb 2008
Views 40,104
Bookmarked 30 times

Implementing Deep Cloning via Serializing objects

By | 22 Feb 2008 | Article
The implementation for a deep clone helper class

Introduction

I was looking around on The Code Project and saw an article talking about the different implementation styles for deep cloning an object. The article referred to an article using Reflection for Deep Cloning an object, but had no article to reference for using Serialization.

Using the Code

This is a helper class that can be used to perform a deep copy of an object:

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 ObjectCopier
{
 /// <summary>
 /// Perform a deep Copy of the object.
 /// </summary>
 /// <typeparam name="T">The type of object being copied.</typeparam>
 /// <param name="source">The object instance to copy.</param>
 /// <returns>The copied object.</returns>
 public static T Clone<T>(T source)
 {
  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(source, null))
  {
    return default(T);
  }

  IFormatter formatter = new BinaryFormatter();
  Stream stream = new MemoryStream();
  using (stream)
  {
    formatter.Serialize(stream, source);
    stream.Seek(0, SeekOrigin.Begin);
    return (T)formatter.Deserialize(stream);
  }
 }
}

Usage of this class becomes ObjectCopier.Clone(objectBeingCloned);.

Points of Interest

In case you prefer to use the new Extension methods of C# 3.0, change the method to have the following signature:

   public static T Clone<T>(this T source)
   {
      ...
   }

Now the method call simply becomes objectBeingCloned.Clone();.

History

  • 22nd February, 2008: Version 1.0: Initial release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Stephen Inglish

Software Developer (Senior)
Harland Financial Solutions
United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionHow do I make a Type serializable PinmemberAlexanderBlade12:08 10 Apr '12  
AnswerRe: How do I make a Type serializable PinmemberStephen Inglish12:25 10 Apr '12  
GeneralRe: How do I make a Type serializable PinmemberAlexanderBlade16:17 11 Apr '12  
QuestionAlternative method to copy object to reduce performance penalty Pinmemberjozamm18:32 5 Aug '11  
AnswerRe: Alternative method to copy object to reduce performance penalty PinmemberStephen Inglish4:23 6 Aug '11  
GeneralFYI Pinmemberlagerdalek13:04 23 May '10  
GeneralJust One Small Correction... Pinmemberno-paper6:17 20 Mar '09  
GeneralGood use of generics but be aware Pinmemberilya lozovyy9:33 29 Apr '08  
GeneralE=MC^2 PinmemberTom Hawkins10:45 17 Apr '08  
GeneralExcellent idea!!! PinmemberWeslei Gomes11:15 24 Mar '08  
QuestionWhat about the performance penalty? PinmemberAndyHo2:14 26 Feb '08  
In my experience the serialization has a tremendous performance penalty. Even more than reflection.
And in the other hand the class MUST be flagged as serializable, which dont allow many type of objects living inside. Wink | ;)
 
- Andy -
see some magic at: www.pandorabox.com.ar
GeneralVery Interesting Idea Pinmembermerlin9814:27 25 Feb '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 22 Feb 2008
Article Copyright 2008 by Stephen Inglish
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid