We experienced a odd behavior when we tried to copy a dictionary and perform changes to the value in a loop as show below. It showed Enumeration value can’t be modified.
Dim Parent As New Dictionary(Of String, String)
Dim copy As Dictionary(Of String, String)
copy = Parent
For Each kvp As KeyValuePair(Of String, String) In copy
Parent(kvp.key) = “Test”
It’s because what that copy operation does is only copies the address of the dictionaries memory stack and they both actually refer the same object.
This is actually called as “Shallow Copy”, on further reading it came to light that there are two ways to copy objects in .net
· Deep copy
· Shallow copy
You can google about it to know more about it and how they differ
So to actually perform a deep copy of the dictionary .net has provided the following way.
Dim copy As New Dictionary(Of String, String)(Parent)
In which the original dictionary is passed as an parameter to the constructor of new dictionary.
Also please go through Icloneable Interface to know more about it.