Facebook Page Twitter Page LinkedIn Page
× C# Tutorial C# Advanced C# Resources


Logical operators are used to combine two or more conditions. C# has following logical operators:

  • && - logical AND operator
  • || - logical OR operator
  • ! - logical NOT operator

Logical AND operator (&&)

The logical AND operator is used to combine two or more conditions and returns true only when all conditions are true, otherwise returns false. Consider the below example to understand this concept:

using System;

class MyProgram {
  static void range_func(int x){
    //&& operator is used to combine conditions
    //returns true only when x >= 10 and x <= 25
    if(x >= 10 && x <= 25)
      Console.WriteLine(x +" belongs to range [10, 25]."); 
    else
      Console.WriteLine(x +" do not belongs to range [10, 25].");
  }

  static void Main(string[] args) {
    range_func(15);
    range_func(25);
    range_func(50);
  }
}

The output of the above code will be:

15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25].

Logical OR operator (||)

The logical OR operator is used to combine two or more conditions and returns true when any of the conditions is true, otherwise returns false. Consider the following example:

using System;

class MyProgram {
  static void range_func(int x){
    //|| operator is used to combine conditions
    //returns true when either x < 100 or x > 200
    if(x < 100 || x > 200)
      Console.WriteLine(x +" do not belongs to range [100, 200].");   
    else
      Console.WriteLine(x +" belongs to range [100, 200]."); 
  }

  static void Main(string[] args) {
    range_func(50);
    range_func(100);
    range_func(150);
  }
}

The output of the above code will be:

50 do not belongs to range [100, 200].
100 belongs to range [100, 200].
150 belongs to range [100, 200].

Logical NOT operator (!)

The logical NOT operator is used to return opposite boolean result. Consider the below example:

using System;

class MyProgram {
  static void range_func(int x){
    //! operator is used to return
    //true when x <= 100
    if(!(x >= 100))
      Console.WriteLine(x +" is less than 100.");   
    else
      Console.WriteLine(x +" is greater than or equal to 100."); 
  }

  static void Main(string[] args) {
    range_func(50);
    range_func(100);
    range_func(150);
  }
}

The output of the above code will be:

50 is less than 100.
100 is greater than or equal to 100.
150 is greater than or equal to 100.

❮ C# - Operators

5