C# Tutorial C# Advanced C# References

C# - Booleans



There are many instances in the programming, where a user need a data type which represents True and False values. For this, C# has a bool data type, which takes either True or False values.

Boolean Values

A boolean variable is declared with bool keyword and can only take boolean values: True or False values. In the example below, a boolean variable called MyBoolVal is declared to accept only boolean values.

using System;
 
class MyProgram {
  static void Main(string[] args) {
    bool MyBoolVal = true;
    Console.WriteLine(MyBoolVal);   
     
    MyBoolVal = false;
    Console.WriteLine(MyBoolVal); 
  }
}

The output of the above code will be:

True
False

Boolean Expressions

A boolean expression in C# is an expression which returns boolean values: True or False. In the example below, comparison operator is used in the boolean expression which returns True when left operand is greater than right operand else returns False.

using System;
 
class MyProgram {
  static void Main(string[] args) {
    int x = 10;
    int y = 25;

    Console.WriteLine(x>y);   
  }
}

The output of the above code will be:

False

A logical operator can be used to combine two or more conditions to make complex boolean expression like && operator is used to combine conditions which returns True if all conditions are true else returns False. Please see the example below.

using System;
 
class MyProgram {
  static void Main(string[] args) {
    int x = 10;

    Console.WriteLine((x > 0 && x < 25));   
  }
}

The output of the above code will be:

True

5