1

I am making a copy of a Dictionary<string, object> using the Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) constructor. However, I found that the object values within the dictionary are the same reference types.

var dict = new Dictionary<string, object>
{
    { "number", 1 },
    { "obj", new Test { Str = "original string" } }
};
        
var dictCopy = new Dictionary<string, object>(dict);
        
// Mutate data within dictCopy
dictCopy["number"] = 2;
(dictCopy["obj"] as Test).Str = "mutated!";
        
Console.WriteLine(dict["number"].Equals(dictCopy["number"])); // False
Console.WriteLine(dict["number"]); // 1
Console.WriteLine(dictCopy["number"]); // 2
        
Console.WriteLine(dict["obj"].Equals(dictCopy["obj"])); // True
Console.WriteLine((dict["obj"] as Test).Str); // mutated!
Console.WriteLine((dictCopy["obj"] as Test).Str); // mutated!
public class Test
{
    public string Str {get; set;}
}

How can I have a copy so that the object values are not the same?

Mohamad Mustafa
  • 65
  • 1
  • 2
  • 8
  • 2
    Did you see this question: https://stackoverflow.com/questions/78536/deep-cloning-objects? A dictionary is in no way different than any other object. – MakePeaceGreatAgain Feb 09 '22 at 07:33
  • 1
    After long time I saw question with minimal reproducible example, +1 to you – Prasad Telkikar Feb 09 '22 at 07:37
  • 1
    The constructor for dictionary - as you already figured out - just pouts the exact same objects into your new dictionary. In order to avoid referencing the same objects all over again, you'd need to copy those objects also which may assume to copy their internally used objects also recursivly. That's what a "deep" copy is about. As we don't know your object-structure it's hard to guess how deep that copy must be. – MakePeaceGreatAgain Feb 09 '22 at 07:38
  • @HimBromBeere The dictionary is sent by the client, and theoretically there's no limit to the number of nested objects they can send. – Mohamad Mustafa Feb 09 '22 at 11:29

0 Answers0