Alexandre Paiva
Alexandre Paiva

Reputation: 304

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;
}

Upvotes: 1

Views: 2435

Answers (2)

Charlieface
Charlieface

Reputation: 71459

Another option is to compare to true.

It looks slightly weird, but it works with three-valued logic and says: is this value true but not false or null

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

You can do the opposite logic with != true: is this value not true, so either false or null

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

Upvotes: 3

Nigel
Nigel

Reputation: 3291

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;
}

Upvotes: 6

Related Questions