7 Things about C#: If Statements

Joe Mayo
Seven Things about C#
9 min readJul 4, 2023

--

Tree branch, with multiple branches.

Branching is intrinsic to all of the work we do every day as developers. We need to evaluate a condition and determine what logic to run, depending on the result of the condition. If you’re just learning to program, that might sound a bit abstract, but the rest of this post explains in more concrete terms how to do branching with if statements and options you should be aware of.

1 — If statements operate on conditions

More specifically, if statements require a conditional expression that evaluates to a boolean result — either true or false. A boolean is represented by the bool type in C# and a bool type variable can only hold a true or false value. Here’s an example of how to declare a bool:

bool isDoorOne;

That’s a variable of type bool. The default value of a bool variable is false. Since we didn’t assign a value, isDoorOne is false. The next example is when we declare and assign a value to a bool:

bool isDoorTwo = true;

This code assigns the value true to the isDoorTwo variable. What this does is explain the syntax of bool variables and how to assign values. In practice, you’ll need to use full expressions that evaluate to a bool value, as in the following example:

string userResponse = "Q";
bool isQuit =…

--

--

Joe Mayo
Seven Things about C#

Author, Instructor, & Independent Consultant. Author of C# Cookbook: — http://bit.ly/CSharpCookbook — @OReillyMedia #ai #csharp #Web3