What are the logical operators in C#?
Answers
Answer:
Operator Description Example
&& Called Logical AND operator. If both (A && B) is false.
the operands are non zero then condition
becomes true.
|| Called Logical OR Operator. If any of the (A || B) is true.
two operands is non zero then condition
becomes true.
! Called Logical NOT Operator. Use to !(A && B) is true.
reverse the logical state of its operand.
If a condition is true then Logical NOT operator
will make false.
Example
The following example demonstrates all the logical operators available in C# −
Live Demo
using System;
namespace OperatorsAppl {
class Program {
static void Main(string[] args) {
bool a = true;
bool b = true;
if (a && b) {
Console.WriteLine("Line 1 - Condition is true");
}
if (a || b) {
Console.WriteLine("Line 2 - Condition is true");
}
/* lets change the value of a and b */
a = false;
b = true;
if (a && b) {
Console.WriteLine("Line 3 - Condition is true");
} else {
Console.WriteLine("Line 3 - Condition is not true");
}
if (!(a && b)) {
Console.WriteLine("Line 4 - Condition is true");
}
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
Explanation: