Reputation: 15508
Wondering if there is a simpler way to check for a nullable bool being true.
I find myself doing code like this a lot which gets real bulky. Any faster way to do it?
bool? x = false;
if (x.hasValue && x.Value) ...
Seems like there must be a clean faster way to check for true
Upvotes: 1
Views: 9710
Reputation: 5817
Use GetValueOrDefault
:
if(x.GetValueOrDefault(false))
You can also use this with other types.
Upvotes: 16
Reputation: 11741
May be many developers are not familiar with this but you can use the null coalesce operator (??), as shown below:
int? x = null;
// Set y to the value of x if x is NOT null; otherwise,
// if x = null, set y to -1.
int y = x ?? -1;
and for condition check :-
if (nullableBool ?? false) { ... }
and another option is GetValueOrDefault Method
if (nullableBool.GetValueOrDefault(false))
{
}
Upvotes: 7