Click here to Skip to main content
15,919,613 members
Articles / Programming Languages / C#
Article

Implementing Deep Cloning via Serializing objects

Rate me:
Please Sign up or sign in to vote.
4.78/5 (21 votes)
22 Feb 2008CPOL 147.7K   37   18
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:

C#
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:

C#
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)


Written By
Software Developer (Senior) Harland Financial Solutions
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMessage Closed Pin
22-Oct-20 21:32
AMAYA JOHN22-Oct-20 21:32 
GeneralSerializable Pin
TerryMulhern3-Jun-19 21:08
TerryMulhern3-Jun-19 21:08 
QuestionWhy are you dependant of IsSerializable ? Pin
copa01718-Feb-15 22:49
copa01718-Feb-15 22:49 
QuestionNull object clone exception Pin
Thierry Parent14-Sep-14 0:26
Thierry Parent14-Sep-14 0:26 
QuestionSerialization is very slow, use direct assigning. Pin
comaric31-Jan-13 3:31
comaric31-Jan-13 3:31 
AnswerRe: Serialization is very slow, use direct assigning. Pin
reggaeguitar10-Sep-14 7:28
reggaeguitar10-Sep-14 7:28 
QuestionHow do I make a Type serializable Pin
AlexanderBlade10-Apr-12 12:08
AlexanderBlade10-Apr-12 12:08 
Hi I'm using Mvc3 and I'm a bit of a newbie to MVC3. I get the error message about the type needs to be serializable. How can I solve this? Is they any way around this?

Thanks for any help or suggestions.
AnswerRe: How do I make a Type serializable Pin
Stephen Inglish10-Apr-12 12:25
Stephen Inglish10-Apr-12 12:25 
GeneralRe: How do I make a Type serializable Pin
AlexanderBlade11-Apr-12 16:17
AlexanderBlade11-Apr-12 16:17 
QuestionAlternative method to copy object to reduce performance penalty Pin
jozamm5-Aug-11 18:32
jozamm5-Aug-11 18:32 
AnswerRe: Alternative method to copy object to reduce performance penalty Pin
Stephen Inglish6-Aug-11 4:23
Stephen Inglish6-Aug-11 4:23 
GeneralFYI Pin
lagerdalek23-May-10 13:04
lagerdalek23-May-10 13:04 
GeneralJust One Small Correction... Pin
paper133720-Mar-09 6:17
paper133720-Mar-09 6:17 
GeneralGood use of generics but be aware Pin
ilya lozovyy29-Apr-08 9:33
ilya lozovyy29-Apr-08 9:33 
GeneralE=MC^2 Pin
Tom Hawkins17-Apr-08 10:45
Tom Hawkins17-Apr-08 10:45 
GeneralExcellent idea!!! Pin
Weslei Gomes24-Mar-08 11:15
Weslei Gomes24-Mar-08 11:15 
QuestionWhat about the performance penalty? Pin
AndyHo26-Feb-08 2:14
professionalAndyHo26-Feb-08 2:14 
GeneralVery Interesting Idea Pin
merlin98125-Feb-08 4:27
professionalmerlin98125-Feb-08 4:27 
GeneralRe: Very Interesting Idea Pin
Libby Howells3-Sep-20 23:59
Libby Howells3-Sep-20 23:59 

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

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