1

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

M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
Peter Kellner
  • 14,748
  • 25
  • 102
  • 188

3 Answers3

16

Use GetValueOrDefault:

if(x.GetValueOrDefault(false))

You can also use this with other types.

Joanvo
  • 5,677
  • 2
  • 25
  • 35
  • This seems to me like the best solution so I'm checking it. I'd prefer that it not be such a long name and it would be nice if there was someway to say GetValueOrParam1(param1). The way it is now, it seems a little vague because you could easily not know the default value. For example, is default value of string "" or null? Be nice if I could say x.GetValueOrOther("") or something like that. – Peter Kellner Oct 02 '14 at 14:53
  • Actually, in this function you are passing as parameter the default value *you want* to have when the object has a null value, so in case of string you can choose whatever is convenient to you: an empty string or a null object. – Joanvo Oct 02 '14 at 14:59
  • Thanks Joanvo, exactly what I wanted. Now, if they could only make it a couple characters instead of a block long method name. – Peter Kellner Oct 02 '14 at 15:56
  • I guess you can only shorten the function name by creating an extension method of your own which wraps that functionality (+ info: http://msdn.microsoft.com/en-us/library/bb383977.aspx) – Joanvo Oct 03 '14 at 11:08
9
if (x == true)

That should work and is the shortest

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
7

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)) 
{
}
Neel
  • 11,625
  • 3
  • 43
  • 61
  • What's interesting, the compiler compiles the `??` operator into a call to *GetValueOrDefault*. So, in performance, they are equal; in beauty, the coalesce operator is nicer. ☺ – IS4 Nov 04 '14 at 00:58