Search code examples
c#nullablelogical-operators

Nullable bool logical "AND" operator behaves differently with true and false


Using bool? variables, can somebody explain why true & null results in null and false & null results in false?

void Main()
{    
    bool? a = null;
    bool? b = true;
    bool? c = a & b;

    Console.WriteLine($"{b} & NULL => " + c);

    b = false;
    c = a & b;
    Console.WriteLine($"{b} & NULL => " + c);
}

Output:

True & NULL =>
False & NULL => False

I would also be happy about the duplicate, because I did not find it, yet.


Solution

  • The purpose of null in this is case is to identify an unknown value. In three-valued logic, the purpose of the unknown value is to indicate that we do not know anything about the truthy or the falsy of a predicate.

    false AND unknown returns false because it is not important to know what the second operator is. This is due to the and operator nature that requires both the operands to be true to return true. As we know that the first operand is false, the rest is irrelevant, and the result is false.

    On the other hand, true AND unknown returns unknown, because the first operand is true, and therefore the result of the whole operation depends on the second operand. The second operand is unknown, therefore the result is unknown.

    C# indicates unknown with null.