Home
VB.NET
Dictionary Copy Example
This page was last reviewed on Nov 27, 2023.
Dot Net Perls
Copy Dictionary. How can we copy a Dictionary in VB.NET, while keeping the original Dictionary separate? We can use the Dictionary constructor.
Dictionary
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.
Example. Here are 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.
Step 1 We create a new Dictionary, and then add 3 keys of String type with Integer values.
Step 2 This is where the copy occurs. The Dictionary constructor (the New Function) copies one Dictionary's contents into another.
Step 3 We modify the original Dictionary by adding a key "fish" with the value 4.
Step 4 With the For-Each loop over the KeyValuePairs in the Dictionaries, we display all the contents of 2 Dictionaries.
KeyValuePair
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 Module
ORIGINAL: [cat, 1] ORIGINAL: [dog, 3] ORIGINAL: [iguana, 5] ORIGINAL: [fish, 4] COPY: [cat, 1] COPY: [dog, 3] COPY: [iguana, 5]
Important point. 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.
So The 2 Dictionaries are completely separate in memory, and changing one does not affect the other.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 27, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.