I have the following code:
string thing="";
if(request.Session.Attributes?.TryGetValue("varName", out thing))
{
//do stuff
}
request.Session.Attributes is a dictionary.
I understand that you can't have if(bool?)
which is what the above does.
I also know that you can have .GetValueOrDefault() so that null will be treated as false.
But I can't do request.Session.Attributes?.GetValueOrDefault().TryGetValue("varName", out thing)
So what is the correct way to return false
if Attributes is null
otherwise return the bool
from the TryGetValue?
A quick and slightly dirty way is doing:
string thing="";
if(request.Session.Attributes?.TryGetValue("varName", out thing) ?? false)
{
//do stuff
}
In this way you are sure that if Attributes
is null, the second branch of the ??
will be chosen and it will not get inside the if.
Personally, I would split it, as having it in a 1-liner does not improve the code that much. It'd become:
string thing="";
var attributes = request.Session.Attributes;
if(attributes != null && attributes.TryGetValue("varName", out thing))
{
//do stuff
}
This is much more readable. Sometimes it is just fair to avoid using new features of the language if they do not improve the code.
Bonus tip:
You can get a line back removing the declaration of things
and placing it just after the out
😉:
attributes.TryGetValue("varName", out string thing)