Search code examples
c#booleannullable

A neater way of handling bools in C#


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?


Solution

  • 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;
    }