Search code examples
booleanboolean-operations

C# Bool operand usage


I want to have the following results

A B =
T T T
F T F
T F F
F F F

I am using this clause to achieve it

A || B

but it does not provide correct results.

Am I using a wrong operand?


Solution

  • Allthough all other answers are correct, I'd like to point out that the operator you are asking for is neither || nor &&. The operator that actually does exactly what you are asking for is & (and the equivalent that you are mistakenly using would be |).

    And, what is the difference? || and && are short circuiting operators. What does that mean? It means that whatever is on the right side of the operator is only evaluated if the left hand side is true. This does not happen with the non short circuit versions of the operators (the truly bolean logical and and or operators):

    public bool True()
    {
        Console.WriteLine("True called.");
        return true;
    }
    
    public bool False()
    {
        Console.WriteLine("False called.");
        return false;
    }
    
    var b1 = False() && True(); //b1 will be false and "False called." will be 
                                //printed on the console. 
    
    var b2 = False() & True();  //b2 will be false and "False called. True called." 
                                //will be printed on the console.