What are the logical operators in C#?

CsharpProgrammingServer Side Programming

Logical operators are used with Boolean values. The following three logical operators are available in C#.

&&Called Logical AND operator. If both the operands are non zero then condition becomes true.
||Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

Let us see an example that shows how to work with logical operators in C#. Here condition is checked for Logical AND operator.

if (a && b) {
   Console.WriteLine("Line 1 - Condition is true");

In the same way, let us see how to work with other logical operators in C#.


 Live Demo

using System;

namespace Demo {
   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");

         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");


Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
Published on 06-Aug-2018 12:11:26