Peter Kellner
Peter Kellner

Reputation: 15508

What is the fastest way to check for nullable bool being true in C#?

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

Answers (3)

Joanvo
Joanvo

Reputation: 5817

Use GetValueOrDefault:

if(x.GetValueOrDefault(false))

You can also use this with other types.

Upvotes: 16

Neel
Neel

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

David Pilkington
David Pilkington

Reputation: 13628

if (x == true)

That should work and is the shortest

Upvotes: 9

Related Questions