C# Booleans

In most cases, in programming, you will need a type of data that may have only one of the two values, such as:

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

In this case, C # has a bool data type, which can take values ​​ true or false.


Boolean Values

The boolean type is declared by the bool keyword and can only take values true​​ or false :

Example
bool isCSharpFun = true;
      bool isFishTasty = false;
      Console.WriteLine(isCSharpFun);   // Outputs True
      Console.WriteLine(isFishTasty);   // Outputs False
      

However, it is very common to return boolean values ​​from rational expressions, for conditional testing (see below).

Boolean Expression

Boolean expression is a C# expression that returns the Boolean value: True​​ or False.

You can use operator comparisons, such as operator greater than - (>) to determine if the expression (or alternative) is true:

Example
int x = 10;
      int y = 9;
      Console.WriteLine(x > y); // returns True, because 10 is higher than 9
      

Or even easier:

Example
Console.WriteLine(10 > 9); // returns True, because 10 is higher than 9
    

In the examples below, we use an operator equal to (==) to check the expression:

Example
Console.WriteLine(10 > 9); // returns True, because 10 is higher than 9
    
Example
int x = 10;
      Console.WriteLine(x == 10); // returns True, because the value of x is equal to 10
      
Example
      
        Console.WriteLine(10 == 15);// returns False, because 10 is not equal to 15