Search code examples
c#.netdictionarytrygetvalue

TryGetValue on a null dictionary


I am trying to use TryGetValue on a Dictionary as usual, like this code below:

Response.Context.Skills[MAIN_SKILL].UserDefined.TryGetValue("action", out var actionObj)

My problem is the dictionary itself might be null. I could simply use a "?." before UserDefined but then I receive the error:

"cannot implicitly convert type 'bool?' to 'bool'"

What is the best way I can handle this situation? Do I have to check if UserDefined is null before using TryGetValue? Because if I had to use Response.Context.Skills[MAIN_SKILL].UserDefined twice my code could look a little messy:

if (watsonResponse.Context.Skills[MAIN_SKILL].UserDefined != null && 
    watsonResponse.Context.Skills[MAIN_SKILL].UserDefined.TryGetValue("action", out var actionObj))
{
    var actionName = (string)actionObj;
}

Solution

  • Add a null check (?? operator) after the bool? expression:

    var dictionary = watsonResponse.Context.Skills[MAIN_SKILL].UserDefined;
    if (dictionary?.TryGetValue("action", out var actionObj)??false)
    {
        var actionName = (string)actionObj;
    }