Sometimes it’s important to make an independent copy of an object – eg. when you want to compare the object after a process to the previous state. To make such a backup-copy of an object, serialization is a very handy way. You don’t even need to change your object: you can use an extension method. The only thing you object have to provide is the class attribute [Serializable]. My simple test class for this is:

    public class TestMe
        public string HelloString { get; set; }
        public TestMe HelloClass { get; set; }

  The extension method is also very straight forward:

    public static class DeepCloner
        public static T DeepClone<T>(this T toClone)
            using (var stream = new MemoryStream())
                var serializer = new BinaryFormatter();
                serializer.Serialize(stream, toClone);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)serializer.Deserialize(stream);

Using the extension method is as natural as using a native method:

static void Main()
    var original = new TestMe
            HelloString = "Hello 1",
            HelloClass = new TestMe
                    HelloString = "Hello 2"
    var clone = original.DeepClone();
    clone.HelloClass.HelloString = "I'm new";

    Console.WriteLine("original.HelloString = "
        + original.HelloString);
    Console.WriteLine("original.HelloClass.HelloString "
        + original.HelloClass.HelloString);
    Console.WriteLine("clone.HelloString = "
        + clone.HelloString);
    Console.WriteLine("clone.HelloClass.HelloString = "
        + clone.HelloClass.HelloString);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Sylvio's Infobox

Aktuelle Themen rund um SQL Server, BI, Windows, ...

Meredith Lewis

Professional Digital Portfolio

Vittorio Bertocci

Just another weblog

ScottGu's Blog

Just another weblog

AJ's blog

Thoughts and informations I think worthwhile to share...

Outlawtrail - .NET Development

Architecture & Design

SDX eXperts Flurfunk

Just another weblog

%d bloggers like this: