0

Working with nullable bools in C# I find myself writing this pattern a lot

if(model.some_value == null || model.some_value == false)
{
    // do things if some_value is not true
}

Is there a more compact way to express this statement? I can't use non-nullable bools because I can't change the model, and I can't do this

if(model.some_value != true)
{
    // do things if some_value is not true
}

Because this will throw a null reference exception if model.some_value is null

One idea I had: I could write an extension method for bools like String.IsNullOrEmpty - bool.IsNullOrFalse. This would be neat enough but I'm wondering if there's some more obvious way of doing this already?

roryok
  • 9,325
  • 17
  • 71
  • 138
  • 1
    second code block work perfect. Why you did get null reference error. https://dotnetfiddle.net/yf1bro – Jenish Rabadiya Feb 26 '15 at 11:12
  • Did you try #2? It should be working fine.. – Simon Whitehead Feb 26 '15 at 11:12
  • @JenishRabadiya from msdn - _"If the HasValue property is true, the value of the current Nullable object can be accessed with the Value property. Otherwise, attempting to access its value throws an InvalidOperationException exception. "_ https://msdn.microsoft.com/en-us/library/sksw8094%28v=vs.110%29.aspx – Gusdor Feb 26 '15 at 11:15
  • @Gusdor did you looked at fiddle I provided. It works why would we aceess its value? second code block does not access it. – Jenish Rabadiya Feb 26 '15 at 11:19
  • @JenishRabadiya is right, it does work there. Apologies – roryok Feb 26 '15 at 11:25
  • @JenishRabadiya I made the poor assumption that it was using Mono and discounted the results. – Gusdor Feb 26 '15 at 11:39

1 Answers1

0

Use a null-coalescing operator to handle cases where the value is null.

if(model.some_value ?? false != true)
{
    // do things if some_value is not true
}

From msdn:

?? Operator (C# Reference)

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

https://msdn.microsoft.com/en-us/library/ms173224.aspx

Alternatively, a switch would do it.

switch(model.some_value)
{
    case false:
    case null:
    // do things if some_value is not true
    break;
}
Gusdor
  • 14,001
  • 2
  • 52
  • 64