In programming, you often need a data type that can only hold one of two possible values, such as YES/NO, ON/OFF, or TRUE/FALSE. For this, C# has a bool data type.
A boolean variable can only take the values true or false.
You define a boolean variable using the bool keyword.
bool isCSharpFun = true; bool isFishTasty = false;Console.WriteLine(isCSharpFun); // Outputs True Console.WriteLine(isFishTasty); // Outputs False
A boolean expression is a C# statement that evaluates to true or false. You use comparison operators (like >, <, ==) to build these expressions.
This is highly useful for building logic and finding answers.
using System;class Program { static void Main() { int x = 10; int y = 9; // Is x greater than y? Console.WriteLine(x > y); // Returns True, because 10 is greater than 9 // Is x equal to 10? Console.WriteLine(x == 10); // Returns True // Is 10 equal to 15? Console.WriteLine(10 == 15); // Returns False } }
Booleans are the foundation for all decision-making in programming. We will use them heavily in the next chapter when we discuss If...Else statements!
Let's think of a real-life situation where we can apply a boolean logic. Imagine a system that checks if a user is old enough to vote.
using System;class Program { static void Main() { int myAge = 25; int votingAge = 18; // Output true if myAge is greater than or equal to votingAge Console.WriteLine(myAge >= votingAge); // Returns True } }
What are the only two possible values a bool variable can hold?