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.

OperatorNameUsageDescriptionExamples
!logical negation operator!ANot 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 ANDA & BA and B. It returns true only if both A and B are true otherwise falsebool C = A & B;  //C is false because B is false.
|Logical ORA | BA or B. It returns false only if both A and B are false otherwise truebool C = A | B;  //C is true because A is true.
^Logical XORA ^ BA XOR B. It returns true if only one of A or B is true otherwise falsebool C = A ^ B;  //C is true because only A is true.
&&Conditional ANDA && BSame as Logical AND but only evaluate B if A is truebool C = A && B;  //C is false because B is false.
||Conditional ORA || BSame as Logical OR but only evaluate B if A is falsebool 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
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.
Note Note
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.

AB!A!BA&BA|BA^BA&&BA||B
truetruefalsefalsetruetruefalsetruetrue
truefalsefalsetruefalsetruetruefalsetrue
falsetruetruefalsefalsetruetruefalsetrue
falsefalsetruetruefalsefalsefalsefalsefalse