Search code examples
c#dictionarytrygetvalue

Why TryGetValue deallocates my Dictionary ?


I have this piece of code :

Dictionary<string, object> tempDict = new Dictionary<string, object>();

if(xDicionary.TryGetValue(...., out tempDict)
{
tempDict.Add(...);
}
else
{
tempDict.Add(..);
}

If the code passes to the else block then I got and exception that cannot perform add because tempDict points to null. Why is this happening ? I know how to bypass it in an ugly way by allocating new Dictionary also in the else block but is there any better way of doing this ?


Solution

  • Because methods that have an out parameter, must assign a value to the out parameter. That means that when you call xDicionary.TryGetValue tempDict is always overwritten, and when nothing is found, it is set to null. Therefore, in your else, tempDict will always be null.