Logical Operators are used to compute the logical operation in a program such as &&
, ||
and !
. They are used to evaluate the condition.
The following are the C# Logical Operators. Assume X holds the value 1 and Y holds 0
Operator | Description | Example |
&& (logical and) | If both the operands are non-zero, then the condition becomes true. | (X && Y) is false |
|| (logical or) | If any of the two operands are non-zero, then the condition becomes true. | (X || Y) is true |
! (logical not) | Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(X && Y) is true |
Example of Logical Operators in C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | using System; namespace Operators { class Logical { static void Main(string[] args) { bool a = true; bool b = false; Console.WriteLine("'!' Operator: {0}", !b); Console.WriteLine("'||' Operator: {0}", a || b); Console.WriteLine("'&&' Operator: {0}", a && b); } } } |
Output:
1 2 3 | '!' Operator: True '||' Operator: True '&&' Operator: False |