Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
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;
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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;
}
over 4 years ago · Santiago Trujillo Report

0

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;
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!