C# Booleans - Complete Guide
Introduction to Booleans
In C#, a Boolean (bool) is a data type that can represent only two values: true or false.
Booleans are fundamental for decision-making in programs and are widely used in conditional statements, loops, and logical expressions to control execution flow.
Declaring and Initializing Booleans
A Boolean variable is declared using the 'bool' keyword.
It can be assigned directly with true/false or set based on the result of a comparison expression.
using System;
namespace BooleanExample
{
class Program
{
static void Main(string[] args)
{
bool isActive = true;
bool isFinished = false;
Console.WriteLine($"isActive: {isActive}");
Console.WriteLine($"isFinished: {isFinished}");
int x = 10, y = 20;
bool comparison = x < y;
Console.WriteLine($"Is x less than y? {comparison}");
}
}
}
isActive: True isFinished: False Is x less than y? True
Boolean Operators
Boolean values are combined using logical operators:
- && (AND): True if both operands are true.
- || (OR): True if at least one operand is true.
- ! (NOT): Inverts the Boolean value.
using System;
namespace BooleanOperators
{
class Program
{
static void Main(string[] args)
{
bool a = true;
bool b = false;
Console.WriteLine($"a && b: {a && b}");
Console.WriteLine($"a || b: {a || b}");
Console.WriteLine($"!a: {!a}");
}
}
}
a && b: False a || b: True !a: False
Booleans in Conditions
Booleans are primarily used in if statements, loops, and other control flow constructs.
They allow execution of specific code blocks depending on whether a condition evaluates to true or false.
using System;
namespace BooleanConditions
{
class Program
{
static void Main(string[] args)
{
bool isLoggedIn = true;
if (isLoggedIn)
{
Console.WriteLine("Welcome back, user!");
}
else
{
Console.WriteLine("Please log in.");
}
for (int i = 0; i < 3; i++)
{
bool isEven = i % 2 == 0;
Console.WriteLine($"{i} is even? {isEven}");
}
}
}
}
Welcome back, user! 0 is even? True 1 is even? False 2 is even? True