Deep Copy: JSON Route


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:


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);
            return (T)entity;

One thought on “Deep Copy: JSON Route

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s