0

Initially, I 'dict' and 'dict2' which is a copy of 'dict'. If I replace a Key in 'dict', the change is applied to dict2 too. How can this be avoided? Below is some sample code.

Sub Main()
    Dim dict As New Dictionary(Of String, Object) From {{"Big", "Small"}, {"Hot", "Cold"}}
    Dim dict2 As New Dictionary(Of String, Object) : dict2 = dict

    If dict.ContainsKey("Hot") Then 'Only makes changes to dict
        dict.Add("Warm", dict("Hot").ToString)
        dict.Remove("Hot")
    End If

    writeDict(dict) 'Displays said changes
    writeDict(dict2) 'Displays same changes as dict
End Sub

Sub writeDict(dict As Dictionary(Of String, Object)) 'Ignore this
    For Each i As KeyValuePair(Of String, Object) In dict
        Console.Write(i.ToString)
    Next
    Console.ReadLine()
End Sub

Ideally I would pass in 'dict' to another Sub, validate it by replacing some keys, then exit the Sub. Then I would resume working with the original dictionary.

But currently that's not working, because changes to dictionaries seem to be global.

  • 3
    No, `dict2` is NOT a copy of `dict`. When you do `dict2 = dict` you're not creating a copy of an object. You're just assigning an existing object to another variable, so both variables refer to the same object. There's only one `Dictionary` so of course a change to it via one variable is reflected in the other variable. If your father was wearing a red shirt and then your mother's husband put on a blue shirt, would you be shocked to find that your father was now wearing a blue short? – jmcilhinney May 31 '19 at 14:13
  • 1
    Possible duplicate of [What is the best way to clone/deep copy a .NET generic Dictionary?](https://stackoverflow.com/questions/139592/what-is-the-best-way-to-clone-deep-copy-a-net-generic-dictionarystring-t) – Sebastian Brosch May 31 '19 at 14:16
  • 1
    @jmcilhinney if my parents were divorced, then yes ;) – djv May 31 '19 at 17:38
  • 1
    @djv, VB.NET doesn't support divorce. ;-) – jmcilhinney Jun 01 '19 at 01:38

1 Answers1

4

When you do "dict2 = dict" it doesn't create a new Dictionary, you just have two variables that points at the same place. You need to create a new instance and copy the data.

    Dim dict As New Dictionary(Of String, Object) From {{"Big", "Small"}, {"Hot", "Cold"}}
    Dim dict2 As New Dictionary(Of String, Object)(dict)
the_lotus
  • 12,668
  • 3
  • 36
  • 53