Search code examples
c#deep-copyconcurrentdictionary

Deep copy a ConcurrentDictionary in C#


I am trying to make a deep copy of a ConcurrentDictionary in C#, but failing. How can I do so that cdTwo becomes a deep copy of cdOne so that I can change the DataObj in cdTwo without chaning it in cdOne?

Main.cs:

using System.Collections.Concurrent;
namespace ExampleCode;
internal class Program
{
    private static void Main(string[] args)
    {
        // Create the data object with the message to the world
        DataObj objOne = new();

        // Create the concurrent dictionaries
        ConcurrentDictionary<int, DataObj> cdOne = new();
        ConcurrentDictionary<int, DataObj> cdTwo = new();

        // Create obj one
        objOne.MessageToTheWorld = "Hello, World";
        cdOne.TryAdd(0, objOne);

        // Clone cdOne without changing the DataObj in cdOne when changing cdTwo (not working)
        cdTwo = cdOne;
        cdTwo[0].MessageToTheWorld = "Hello, Europe";

        // Print the message to the user
        Console.WriteLine(cdOne[0].MessageToTheWorld);
        Console.WriteLine(cdTwo[0].MessageToTheWorld);
        Console.ReadKey();
    }
}

Class file DataObj.cs:

namespace ExampleCode;
internal class DataObj
{
    public string MessageToTheWorld { get; set; }

    public DataObj() { }

    public object Clone()
    {
        DataObj obj = (DataObj)this.MemberwiseClone();
        return obj;
    }

}

Edit. I tried this one Deep cloning objects but it gave me this: enter image description here


Solution

  • cdTwo = cdOne;

    That's not cloning anything, it's just copying a handle to cdTwo into cdOne. Deep cloning the dictionary would look like this:

    foreach(var (key, value) in cdOne)
        cdTwo[key] = (DataObj)value.Clone(); // the function you provided