PanosPlat
PanosPlat

Reputation: 958

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?

Upvotes: 0

Views: 155

Answers (4)

InBetween
InBetween

Reputation: 32750

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. 

Upvotes: 4

Yousaf
Yousaf

Reputation: 29282

Am I using a wrong operand?

Yes you are.

You need the AND && operator which will be true only if all of the conditions are true.

You are using the OR || operator which will give you true even if one of the conditions are true.

Use the AND && operator instead of OR ||

Upvotes: 3

SpaceUser7448
SpaceUser7448

Reputation: 189

Use && (which means 'and')

|| means 'or'

Upvotes: 2

Marius Loewe
Marius Loewe

Reputation: 236

You want an and, but you used an or.

Upvotes: 3

Related Questions