Home
VB.NET
Dictionary Copy Example
Updated Feb 9, 2025
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 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.
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]
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 9, 2025 (grammar).
Home
Changes
© 2007-2025 Sam Allen