Create Deep Copies Of Object In C# Using AutoMapper

A Quick Preface

A shallow copy of an object is one that points to the same place in memory as the original. Any changes made to the copy also effect the original because the copy references the same place in memory as the original. (see accessing by reference)

A deep copy of an object is one that points to a completely separate place in memory, yet contains all the same values as the original. Any changes made to the copy do not effect the original object, nor do any changes to the original effect the copy.


I was recently tasked with our business wanting to audit changes when a customer updates their profile. If the customer changes their phone number, address, or any other property of their account, the business wanted a record of that detailing the old value, the new value, and when the changes were made.

I thought the best plan of attack would be to:
1) Create a deep copy of the customer object before changes.
2) Make any requested updates to the original customer object.
3) Save the customer triggered updates to the database.
4) Compare the copied object to the modified object and record all changes in a separate place for the business.

The .NET framework, surprisingly, does not contain a method to create a deep copy of an object. You must either roll your own helper method or use an existing 3rd party library, so I decided on AutoMapper.

The Code

//define our original person object
var originalPerson = new Person()
{
	FirstName = "Jasper",
	LastName = "Showers",
};

//ideally this would be done in a config file at app startup
Mapper.Initialize(cfg => cfg.CreateMap<Person, Person>());

//create the deep copy using AutoMapper
var deepCopy = Mapper.Map<Person>(originalPerson);

//change properties on the original
originalPerson.FirstName = "Ronald";
originalPerson.LastName = "McDonald";

//record any property changes for the two objects
//leaving this part out for the sake of the example and return both objects
return new List<Person>()
{
	originalPerson,
	deepCopy,
};

This will output the following expected results. Notice that the copied object is in fact a deep copy and was not changed by reference.

[  
   {  
      "FirstName":"Ronald",
      "LastName":"McDonald"
   },
   {  
      "FirstName":"Jasper",
      "LastName":"Showers"
   }
]

You can download the Visual Studio solution used in this example here.

Leave a Reply

Your email address will not be published. Required fields are marked *