Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep Copy of a C# Object

Tags:

c#

deep-copy

I am working on some code that is written in C#. In this app, I have a custom collection defined as follows:

public class ResultList<T> : IEnumerable<T>
{
  public List<T> Results { get; set; }
  public decimal CenterLatitude { get; set; }
  public decimal CenterLongitude { get; set; }
}

The type used by Results are one of three custom types. The properties of each of the custom types are just primitive types (ints, strings, bools, int?, bool?). Here is an example of one of the custom types:

public class ResultItem
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool? isLegit { get; set; }
}

How do I perform a deep copy of a ResultList object that I've created. I found this post: Generic method to create deep copy of all elements in a collection. However, I can't figure out how to do it.

like image 279
user70192 Avatar asked Jun 17 '12 20:06

user70192


People also ask

What is a deep copy C?

A deep copy, in contrast, means that you copy an entire object (struct). If it has members that can be copied shallow or deep, you also make a deep copy of them.

What is deep and shallow copy in C?

Deep copy stores copies of the object's value. Shallow Copy reflects changes made to the new/copied object in the original object. Deep copy doesn't reflect changes made to the new/copied object in the original object. Shallow Copy stores the copy of the original object and points the references to the objects.

Is spread operator deep copy?

For nested objects the spread operator will provide a deep copy to the first instance of the values but leaves all the nested data as shallow copies sharing a space in memory with original. Take note of this behavior!


2 Answers

The approach involving the least coding effort is that of serializing and deserializing through a BinaryFormatter.

You could define the following extension method (taken from Kilhoffer’s answer):

public static T DeepClone<T>(T obj)
{
    using (var ms = new MemoryStream())
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(ms, obj);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

…and then just call:

ResultList<T> clone = DeepClone(original);
like image 191
Douglas Avatar answered Oct 02 '22 05:10

Douglas


One of the reasons why your ResultList class won't work with Jon Skeet's example is because it does not implement the ICloneable interface.

Implement ICloneable on all the classes that you need cloned, e.g.

public class ResultItem : ICloneable
{
  public object Clone()
  {
    var item = new ResultItem
                 {
                   ID = ID,
                   Name = Name,
                   isLegit = isLegit
                 };
    return item;
  }
}

And also on ResultList:

public class ResultList<T> : IEnumerable<T>, ICloneable where T : ICloneable
{
  public List<T> Results { get; set; }
  public decimal CenterLatitude { get; set; }
  public decimal CenterLongitude { get; set; }

  public object Clone()
  {
    var list = new ResultList<T>
                 {
                   CenterLatitude = CenterLatitude,
                   CenterLongitude = CenterLongitude,
                   Results = Results.Select(x => x.Clone()).Cast<T>().ToList()
                 };
    return list;
  }
}

Then to make a deep copy of your object:

resultList.clone();
like image 39
Rei Mavronicolas Avatar answered Oct 02 '22 03:10

Rei Mavronicolas