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 ?
Because methods that have an
outparameter, must assign a value to theoutparameter. That means that when you callxDicionary.TryGetValuetempDictis always overwritten, and when nothing is found, it is set to null. Therefore, in your else,tempDictwill always be null.