How can I copy a Dictionary<string, string>
to another new Dictionary<string, string>
so that they are not the same object?
The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.
Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.
One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.
Assuming you mean you want them to be individual objects, and not references to the same object pass the source dictionary into the destination's constructor:
Dictionary<string, string> d = new Dictionary<string, string>(); Dictionary<string, string> d2 = new Dictionary<string, string>(d);
"so that they are not the same object."
Ambiguity abound - if you do actually want them to be references to the same object:
Dictionary<string, string> d = new Dictionary<string, string>(); Dictionary<string, string> d2 = d;
(Changing either d
or d2
after the above will affect both)
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { Dictionary<string, string> first = new Dictionary<string, string>() { {"1", "One"}, {"2", "Two"}, {"3", "Three"}, {"4", "Four"}, {"5", "Five"}, {"6", "Six"}, {"7", "Seven"}, {"8", "Eight"}, {"9", "Nine"}, {"0", "Zero"} }; Dictionary<string, string> second = new Dictionary<string, string>(); foreach (string key in first.Keys) { second.Add(key, first[key]); } first["1"] = "newone"; Console.WriteLine(second["1"]); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With