0

I don't understand why this happens:

var demoDict = new Dictionary<string, string>()
{
    {"key", "value" }
};

for (int i = 0; i < 2; i++)
{
    var tempDict = demoDict;

    tempDict.TryAdd("keyAdded", "valueAdded");
}

Imagine i have a code like this, why does the TryAdd to the tempDict add the Key into the demoDict too?

When you do the same thing with Classes or Integers for example, this behavior does not happen.

Steve
  • 47
  • 6
  • 4
    "*When you do the same thing with Classes ... this behavior does not happen*" -- [not true](https://sharplab.io/#v2:C4LgTgrgdgNAJiA1AHwAICYCMBYAUHgNwEMwACAY1IF5SoBTAd1IGEAKASgG49yA6AZWqkARAHl6w7rmJk4Q8lLxwBQ4QBUGAe0l48qTAE5Wffl125UAZlIYWeAN55Szm9f0AGUoPukA5nWBOUgBnAKCAXzxwoA=). – canton7 Jun 27 '23 at 10:38
  • 4
    It will happen with any reference type. Because in those cases `var tempDict = demoDict;` means `tempDict` will reference the same object as `demoDict`. – wohlstad Jun 27 '23 at 10:41
  • 7
    A dictionary is a reference type. If you add a variable `tempDict` and assign an existing dictionary reference to it, you have two variables which reference the same dictionary. If you want a new reference, initialize a new dictionary with `new` – Tim Schmelter Jun 27 '23 at 10:42
  • @canton7 yes you're right sorry, I did the test for the class wrong – Steve Jun 27 '23 at 10:44

0 Answers0