Logical Operators in C#

Logical operators (also known as Boolean or conditional operators) usually compare two or more conditions and return a Boolean result (true or false). They must be used on boolean type operands or variables. They are widely used in C# programming and very useful when comparing more than one condition.

If you aren’t generally familiar with operators and precedence in programming, then I suggest that you check out my blog post on Working with Operators in C#.

Here are the logical operators used in C#:

Operand Description
&& AND operator. If both operands are true, then the condition is true.
|| OR operator. If any operands are true, then the condition is true.
! NOT operator. If an operand or a condition is true, the NOT operator will make them false and vice versa.
^ XOR operator. If one operand is true, then the condition is true.

Example using logical operators

bool x = true;
bool y = true;

Console.WriteLine(!x);  //  Output: False
Console.WriteLine(x && y);  //  Output: True
Console.WriteLine(x || y);  //  Output: True
Console.WriteLine(x ^ y);  //  Output: False

x = true;
y = false;
Console.WriteLine(!x);  //  Output: False
Console.WriteLine(x && y);  //  Output: False
Console.WriteLine(x || y);  //  Output: True
Console.WriteLine(x ^ y);  //  Output: True

x = false;
y = true;
Console.WriteLine(!x);  //  Output: True
Console.WriteLine(x && y);  //  Output: False
Console.WriteLine(x || y);  //  Output: True
Console.WriteLine(x ^ y);  //  Output: True

x = false;
y = false;
Console.WriteLine(!x);  //  Output: True
Console.WriteLine(x && y);  //  Output: False
Console.WriteLine(x || y);  //  Output: False
Console.WriteLine(x ^ y);  //  Output: False
comments powered by Disqus