✅ 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
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()
callsThanks
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)
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()
methodam i missing something or would it just be instead of clearing the dictionary (
tempDictionary.Clear()
), creating a new dictionary (tempDictionary = new Dictionary<...>();
) ?True, yeah
@MightyPirate if ya need an explanation why/how that would work let me know and ill explain further
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?
its better to $close it
Use the /close command to mark a forum thread as answered