What is the difference between | and || operators in c#?


|| is called logical OR operator and | is called bitwise logical OR but the basic difference between them is in the way they are executed. The syntax for || and | the same as in the following −

  • bool_exp1 || bool_exp2
  • bool_exp1 | bool_exp2
  • Now the syntax of 1 and 2 looks similar to each other but the way they will execute is entirely different.
  • In the first statement, first bool_exp1 will be executed and then the result of this expression decides the execution of the other statement.
  • If it is true, then the OR will be true so it makes no sense to execute the other statement.
  • The bool_exp2 statement is executed if and only if bool_exp1 returns false on execution.
  • It is also known as the short circuit operator because it shorts the circuit (statement) on the basis of the first expression’s result.
  • Now in the case of | things are different. The compiler will execute both statements, in other words both statements are executed regardless of the result of one statement
  • It’s an inefficient way of doing things because it makes no sense to execute the other statement if one is true because the result of OR is effective only for results evaluated to “false” and it’s possible when both statements are false.

logical OR

Example

 Live Demo

using System;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         if(Condition1() || Condition2()){
            Console.WriteLine("Logical OR If Condition Executed");
         }
         Console.ReadLine();
      }
      static bool Condition1(){
         Console.WriteLine("Condition 1 executed");
         return true;
      }
      static bool Condition2(){
         Console.WriteLine("Condition 2 executed");
         return true;
      }
   }
}

Output

Condition 1 executed
Logical OR If Condition Executed

Bitwise logical OR

Example

 Live Demo

using System;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         if(Condition1() | Condition2()){
            Console.WriteLine("Logical OR If Condition Executed");
         }
         Console.ReadLine();
      }
      static bool Condition1(){
         Console.WriteLine("Condition 1 executed");
         return true;
      }
      static bool Condition2(){
         Console.WriteLine("Condition 2 executed");
         return true;
      }
   }
}

Output

Condition 1 executed
Condition 2 executed
Logical OR If Condition Executed

Updated on: 24-Sep-2020

685 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements