C# Booleans
A bool is a type that holds one of two values, true or false. A comparison makes a bool value from two other values.
A bool value
A bool variable holds true here. Printing it shows the word True with a capital T.
using System;
class Program
{
static void Main(string[] args)
{
bool isReady = true;
Console.WriteLine(isReady);
}
}Two comparisons
A comparison checks two values and gives a bool result. The first test here is true, and the second test is false.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(10 > 5);
Console.WriteLine(10 < 5);
}
}Equal and not equal
The == sign tests equality, and != tests the opposite. The two lines print True and then False.
using System;
class Program
{
static void Main(string[] args)
{
int score = 7;
Console.WriteLine(score == 7);
Console.WriteLine(score != 7);
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
int age = 20;
int points = 45;
bool canEnter = age >= 18;
bool hasWon = points == 50;
Console.WriteLine("Can enter: " + canEnter);
Console.WriteLine("Has won: " + hasWon);
}
}Key points
- A bool holds either true or false.
- Printing a bool shows True or False, each with a capital letter.
- The sign > asks whether the left value is greater than the right value.
- The sign >= means greater than or equal to.
- The sign == asks whether two values are equal.
- The sign != asks whether two values are not equal.
In this example, age is 20, so the test age >= 18 gives true and the first line prints Can enter: True. Points is 45, so the test points == 50 gives false. The second line prints Has won: False.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the comparison 5 == 5 print?