Dictionary
How can we copy a Dictionary
in VB.NET, while keeping the original Dictionary
separate? We can use the Dictionary
constructor.
It is possible to assign a reference to a Dictionary
, but if we do this, each Dictionary
reference points to the same data. Instead, we must copy the Dictionary
's entire contents.
Here we create a Dictionary
, then copy it—and then when the original is modified, the copy remained unchanged. This shows that the 2 Dictionaries are entirely separate.
Dictionary
, and then add 3 keys of String
type with Integer values.Dictionary
constructor (the New Function) copies one Dictionary
's contents into another.Dictionary
by adding a key "fish" with the value 4.For-Each
loop over the KeyValuePairs
in the Dictionaries, we display all the contents of 2 Dictionaries.Module Module1 Sub Main(args as String()) ' Step 1: create a Dictionary. Dim dictionary = New Dictionary(Of String, Integer)() dictionary.Add("cat", 1) dictionary.Add("dog", 3) dictionary.Add("iguana", 5) ' Step 2: copy the Dictionary to a second Dictionary. Dim copy = New Dictionary(Of String, Integer)(dictionary) ' Step 3: modify the original Dictionary. dictionary.Add("fish", 4) ' Step 4: display the 2 separate Dictionaries. For Each pair in dictionary Console.WriteLine($"ORIGINAL: {pair}") Next For Each pair in copy Console.WriteLine($"COPY: {pair}") Next End Sub End ModuleORIGINAL: [cat, 1] ORIGINAL: [dog, 3] ORIGINAL: [iguana, 5] ORIGINAL: [fish, 4] COPY: [cat, 1] COPY: [dog, 3] COPY: [iguana, 5]
When we analyze the results of the program, only the original Dictionary
has the key "fish" in it. This means the copy did not get modified when the original did.
It is possible to copy a Dictionary
with a single statement of VB.NET code. We do not need to loop over the original Dictionary
and add each entry individually to the copy.