C# Logical Operators
C# Logical Operators are used in logical expressions and the returned value is definitely bool type value. To demonstrate the examples clearly, we'll assume two bool variables are defined as A=true and B=false.
Operator | Name | Usage | Description | Examples |
---|---|---|---|---|
! | logical negation operator | !A | Not A. It returns true if A is false and returns false if A is true. | bool C = !A; //C is false because A is true. |
& | Logical AND | A & B | A and B. It returns true only if both A and B are true otherwise false | bool C = A & B; //C is false because B is false. |
| | Logical OR | A | B | A or B. It returns false only if both A and B are false otherwise true | bool C = A | B; //C is true because A is true. |
^ | Logical XOR | A ^ B | A XOR B. It returns true if only one of A or B is true otherwise false | bool C = A ^ B; //C is true because only A is true. |
&& | Conditional AND | A && B | Same as Logical AND but only evaluate B if A is true | bool C = A && B; //C is false because B is false. |
|| | Conditional OR | A || B | Same as Logical OR but only evaluate B if A is false | bool C = A || B; //C is true because A is true. |
Example 01-10-01
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System; namespace TestLogicalOperators { class Program { static void Main(string[] args) { bool x, y; x = false; y = true; Console.WriteLine("x={0}, y={1}", x, y); Console.WriteLine("!x={0}, !y={1}", !x, !y); Console.WriteLine("x&y={0}", x&y); Console.WriteLine("x|y={0}", x|y); Console.WriteLine("x^y={0}", x^y); Console.WriteLine("x&&y={0}", x && y); Console.WriteLine("x||y={0}", x || y); Console.Read(); } } }
Output
x=False, y=True !x=True, !y=False x&y=False x|y=True x^y=True x&&y=False x||y=True
- Line 9-11: Declare 2 bool variables x, y and its initial values.
- Line 12: Output x, y.
- Line 13: Output !x and !y. ! operator reverses its right operand
- Line 14: Output the result of x&y and it is false.
- Line 15: Output the result of x|y and it is true.
- Line 16: Output the result of x^y and it is true because x and y have the different value.
- Line 17: Output the result of x && y and it is false. x && y is the same as x&&y.
- Line 18: Output the result of x || y and it is true. x || y is the same as x||y.
![]() |
---|
The spaces between an operator and its operand will be neglected when it is compiled. But the spaces make the code more readable. |
The following is the full value table for two oprands A and B.
A | B | !A | !B | A&B | A|B | A^B | A&&B | A||B |
---|---|---|---|---|---|---|---|---|
true | true | false | false | true | true | false | true | true |
true | false | false | true | false | true | true | false | true |
false | true | true | false | false | true | true | false | true |
false | false | true | true | false | false | false | false | false |