Deep Copy: JSON Route

Introduction

This post is not about:

  • … when to deep copy and when to shallow copy
  • … answering what will happen to events
  • … design problem when deep copy is overused (do research)
  • … JSON v/s Binary serialization
  • … having extension at object level
  • … performance

This post is about:

Cloning

using System;
using System.Runtime.Serialization.Json;
using System.IO;

namespace MyGreatCompany.MyGreatExtensions
{
    public static class Objects
    {
        public static T GetDeepCopy(this T from)
        {
            DataContractJsonSerializer serialiser = new DataContractJsonSerializer(from.GetType());
            MemoryStream memoryStream = new MemoryStream();
            serialiser.WriteObject(memoryStream, from);
            object entity = Activator.CreateInstance(from.GetType());
            entity = serialiser.ReadObject(memoryStream);
            memoryStream.Close();
            memoryStream.Dispose();
            return (T)entity;
        }
    }
}
Advertisements

One thought on “Deep Copy: JSON Route

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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