Search code examples
c#deep-copyreference-type

Value copy without using serialization in c#


I have two lists and I am trying to copy the source to the target. In the new iteration, changing the source affects the target. I understand, I am making a reference copy. Is there a way to make deep copy without using any serializer(due to performance issues). Please find my code below

public void ListFiller()
      {
         newListCopy = new List<KeyValuePair<string, object>>(newList);             
      } 

Solution

  • The KeyValuePairs are structs and therefore will be recreated. However, the values of the KeyValuePair are not recreated because that are reference types. Therefore the same instance is still referenced in both data structures.

    The performant way to solve that is to implement IClonable (or a custom clone method) and create a deep clone of your object manually. However that is time-consuming and you have to maintain the clone method if the object structure changes:

      public void ListFiller()
      {
         newListCopy = new List<KeyValuePair<string, object>>();
         foreach (var pair in newList)
         {
             var clone = (pair.Value as IClonable)?.Clone();
             // handle case that the object does not implement IClonable
             newListCopy.Add(new KeyValuePair<string, object>(pair.Key, clone );
         }           
      } 
    

    As you already mentioned, a simpler way is, to use serialization for recreating the whole data structure. That is relativly easy to implement but not so performant (is that actually a problem?) and the objects need to be serializable.

    The internet is full of similar questions and solutions.