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?