5,696,576 members and growing! (15,513 online)
Email Password   helpLost your password?
General Programming » Programming Tips » General     Intermediate License: The Code Project Open License (CPOL)

Implementing Deep Cloning via Serializing objects

By Stephen Inglish

The implementation for a deep clone helper class
C# (C# 1.0, C# 2.0, C# 3.0, C#), .NET (.NET, .NET 2.0, .NET 3.5, .NET 3.0), Dev

Posted: 22 Feb 2008
Updated: 22 Feb 2008
Views: 6,801
Bookmarked: 10 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
6 votes for this Article.
Popularity: 3.54 Rating: 4.55 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
2 votes, 33.3%
4
4 votes, 66.7%
5

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



Occupation: Software Developer
Company: Sogeti USA
Location: United States United States

Other popular Programming Tips articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 5 of 5 (Total in Forum: 5) (Refresh)FirstPrevNext
GeneralGood use of generics but be awarememberilya lozovyy10:33 29 Apr '08  
GeneralE=MC^2memberTom Hawkins11:45 17 Apr '08  
GeneralExcellent idea!!!memberWeslei Gomes12:15 24 Mar '08  
GeneralWhat about the performance penalty?memberAndyHo3:14 26 Feb '08  
GeneralVery Interesting Ideamembermerlin9815:27 25 Feb '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 22 Feb 2008
Editor: Deeksha Shenoy
Copyright 2008 by Stephen Inglish
Everything else Copyright © CodeProject, 1999-2008
Web19 | Advertise on the Code Project