Logical operators in C#

(Last Updated On: January 29, 2019)

Generally, logical operators in C# language e.g. &&, || (Logical AND and Logical OR respectively) are used to evaluate an expression to Boolean if they are true or false.

They are used to control program flow and, generally used in if condition or while or for loops etc.

Let’s make it simple with example

&& logical operator in C#

This logical AND operator returns true if and only if both operands are true.

For example, a == 10 && b ==20 are two operands that is combined with && logical operator.

a == 10 && b == 20

Compiler first, evaluate a == 10 operand / expression. If it is true only then it will evaluate the second expression b == 20. If both expressions are true, then total expression will be evaluating to true or else false.

If first expression is false, then compiler won’t evaluate second expression resulting total output as false.

 

Code Example on && (AND) logical operator:

Read below program first where value of a is 10 and value of variable b is 20.

In if (a == 10 && b == 20), compiler checks a== 10 if it is true. Since, value of variable a is 10, so this expression is true. So, compiler will move to second expression

i.e. b==20. Again, it found that value of b is equal to 20, so, it is also true.

Hence, both expression before and after && are true, the total expression evaluates to true. So, compiler will go inside the if condition block and print true condition.

In if (a == 10 && b == 30), a == 10 is true, hence compiler will check for second expression b ==30. Since value of b is initialized with 20, so value of b cannot be equal to 30, hence false.

So, true && false become false.

Output:
true condition
false condition

AS A SIDE NOTE:

For && logical operator remembers the below truth table

Operand1 && operand2

False && False = False
False && true = False
True && false = False
True && True = True

 

|| – (OR) Logical operator in C#

If any of the operands /expressions used before and after || operator e.g. if (a == 10 || b == 20) is true, then output will be true. Other wise result will be false.

Compiler, checks the first operand, and if it is true, then it will not check the second one.

If first is false, only then it will check for second.

Here is the truth table for || OR logical operator.

Operand1 && operand2

False && False = FALSE
False && true = TRUE
True && false = TRUE
True && True = TRUE

Code example:

Four conditions have been written in this example based on above truth table for ||.

Output:
true condition
true condition
true condition
false condition

 

NOTE:
! logical not – it is coming under both logical and unary operators in C#. It has been described under unary operators in C# programming.