C# Boolean
Boolean variables are used in C# to store true or false values. They are a fundamental part of programming, and are used in various contexts, such as controlling program flow and making logical comparisons. In this article, we will cover the basics of C# Booleans, including how to declare them, assign them values, and use them in different types of statements.
Declaring Boolean Variables
To declare a Boolean variable in C#, you use the bool
keyword followed by the variable name. For example:
1bool isRaining;
This declares a Boolean variable named isRaining
that can store either true
or false
values. By default, a Boolean variable is initialized to false
. To initialize it to a specific value, you can use the =
operator.
1bool isRaining = true;
Boolean Operators
C# provides a number of operators for working with Boolean values. Here are some of the most common ones:
Logical AND (&&
)
The logical AND operator returns true
if both operands are true
, and false
otherwise.
1bool result = true && false; // false
Logical OR (||
)
The logical OR operator returns true
if at least one of the operands is true
, and false
otherwise.
1bool result = true || false; // true
Logical NOT (!
)
The logical NOT operator returns the opposite of the Boolean value. If the value is true
, it returns false
, and vice versa.
1bool result = !true; // false
Boolean Expressions
Boolean expressions are used to make logical comparisons between values. They can be used in if
statements, loops, and other control structures to control program flow. For example:
1bool isRaining = true; 2bool hasUmbrella = true; 3 4if (isRaining && hasUmbrella) 5{ 6 Console.WriteLine("Don't forget your umbrella!"); 7}
This code uses the if
statement to check if both isRaining
and hasUmbrella
are true
. If they are, it prints a message to the console.