6.0: Booleans
In this module, we'll be learning about booleans and boolean expressions.
File Location
Right click on the solution.
Go to Add > New Project.
Select Console App (.NET Framework) and name it
06_booleans
.Write your code for this module within
Program.cs
of that project.
Description
The type
bool
represents a boolean value.The value can either be true or false.
The default value is false.
Examples
We assign booleans values just like we did with strings, instead we are declaring them true or false.
bool isSad = false
bool isHappy = true
Comparison Operators
Booleans are often used with comparison operators(symbols), which creates the ability to write boolean expressions/boolean logic. Here are some comparison operators in C#:
Operator
Meaning
==
Equality
!=
Inequality
<
Less than
<=
Less than or equal to
>
Greater than
>=
Greater than or equal to
&&
And
`
`
Or
Boolean Logic
You can use boolean logic to control the flow of the code in your programs. One way to control this flow is using if
statements. If
statements return a true or false value, and they are used with logical and relational operators.
Example
Type the code below in your Program.cs
file:
The
==
operator compares the variable to the value. If the value is exactly50
, the expression resolves to true.The
if
statement contains the logic that will run depending on the result of the previous comparison. If the expression was true(which it is), it will execute the code inside of the if statement and then continue to #3. If it wasn't true, it will bypass that expression and still continue to #3.This code is independent of the boolean expression and will run no matter what.
Challenges
Now that you've had some experience with booleans, try some challenges in the following module before we move on to the next topic.
Last updated