C
C#14mo ago
MightyPirate

✅ data override in dictionary of dictionaries

I'm trying to create a dictionary of dictionaries, and use temp variable to create it, but when i change data in temp variable, it also changes in main dictionary. My code looks like this: tempDictionary.Add(key, stuff) tempDictionary.Add(key2, stuff2) mainDictionary.Add(mkey, tempDictionary) tempDictionary.Clear tempDictionary.Add(key3, stuff3) mainDictionary.Add(mkey2, tempDictionary) the problem is mainDictionary[mkey] turns out to be the same as mainDictionary[mkey2] What are my options?
9 Replies
Angius
Angius14mo ago
Dictionary is a reference type, so yes, that's how it will work You can either use a separate temp variable for each dictionary, do some shallow or deep cloning, or just initialize the whole dictionary of dictionaries in one go, instead of a bunch of .Add() calls
MightyPirate
MightyPirateOP14mo ago
Thanks Separate variables are not an option, single-command init is also something i woul like to avoid can you tell me more about shallow and deep cloning (and what is the differece)
Angius
Angius14mo ago
Shallow cloning will clone the dictionary, but not the values inside of it Deep cloning clones the whole structure Easiest way to do a shallow clone would probably be LINQ's .ToDictionary() method
cap5lut
cap5lut14mo ago
am i missing something or would it just be instead of clearing the dictionary (tempDictionary.Clear()), creating a new dictionary (tempDictionary = new Dictionary<...>();) ?
Angius
Angius14mo ago
True, yeah
cap5lut
cap5lut14mo ago
@MightyPirate if ya need an explanation why/how that would work let me know and ill explain further
MightyPirate
MightyPirateOP14mo ago
i think i got it, will try that right now yep, that seems to do what i want from it. Thanks a lot. do i need to close this question now somehow or it should stay as is?
cap5lut
cap5lut14mo ago
its better to $close it
MODiX
MODiX14mo ago
Use the /close command to mark a forum thread as answered
Want results from more Discord servers?
Add your server