What are the logical operators in C#?


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

OperatorDescription
&&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#.

Example

 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");
         }
         Console.ReadLine();
      }
   }
}

Output

Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements