Utilizor
Contact Us

C# Booleans

True or False values.

C# Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:

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

For this, C# has a bool data type, which can take the values true or false.

Boolean Expression

A Boolean expression returns a boolean value: true or false, by comparing values/variables.

Examples

Boolean Values

Declaring boolean variables.

using System;

class Program
{
  static void Main(string[] args)
  {
    bool isCSharpFun = true;
    bool isFishTasty = false;
    Console.WriteLine(isCSharpFun);   // Outputs True
    Console.WriteLine(isFishTasty);   // Outputs False
  }
}

Boolean Expression

Comparing values returns a boolean.

using System;

class Program
{
  static void Main(string[] args)
  {
    int x = 10;
    int y = 9;
    Console.WriteLine(x > y); // returns True, because 10 is higher than 9
  }
}

Real Life Example

Using booleans in conditional logic.

using System;

class Program
{
  static void Main(string[] args)
  {
    int myAge = 25;
    int votingAge = 18;

    if (myAge >= votingAge) 
    {
      Console.WriteLine("Old enough to vote!");
    } 
    else 
    {
      Console.WriteLine("Not old enough to vote.");
    }
  }
}