C# Booleans

A boolean in C# is a data type that can hold one of two values: true or false. Booleans are commonly used in decision-making structures like if statements, loops, and conditional expressions.

Boolean Declaration

You can declare a boolean variable using the bool keyword.

Example

bool isActive = true;
bool isComplete = false;
Console.WriteLine(isActive);   // Outputs True
Console.WriteLine(isComplete); // Outputs False

Output:

True False

Code Explanation: The boolean variables isActive and isComplete are assigned the values true and false, respectively. When printed, they display their values.

Boolean Expressions

Boolean expressions are used to evaluate conditions and return true or false. These are often used in control flow statements like if or loops.

int age = 18;
bool isAdult = age >= 18;
Console.WriteLine(isAdult); // Outputs True

Output:

True

Code Explanation: The expression age >= 18 evaluates to true, which is then stored in the isAdult boolean variable and printed.

Boolean Logic with Operators

Boolean logic can be combined using logical operators such as && (AND), || (OR), and ! (NOT) to create more complex conditions.

bool isMorning = true;
bool isWeekend = false;
bool canSleepIn = isMorning && isWeekend;
bool willGoToWork = isMorning && !isWeekend;

Console.WriteLine(canSleepIn);   // Outputs False
Console.WriteLine(willGoToWork); // Outputs True

Output:

False True

Code Explanation: The expression isMorning && isWeekend evaluates to false because both conditions are not true. The expression isMorning && !isWeekend evaluates to true since isMorning is true and !isWeekend (not weekend) is also true.

Using Booleans in Control Structures

Booleans are often used in control flow statements to make decisions.

bool isSunny = true;
if (isSunny)
{
    Console.WriteLine("Go outside!");
}
else
{
    Console.WriteLine("Stay indoors.");
}

Output:

Go outside!

Code Explanation: The boolean isSunny is evaluated in an if statement. Since it is true, the Go outside! message is printed.