How to Use Boolean Logic in C# Programming
 
 

Boolean variables can be only two values: true or false. Actually, you see true or false in the Visual Studio IDE, but Booleans are actually a one or a zero. A one stands for true, and a zero stands for false. You can use these two values to control the flow of code in your programs. Code flow is controlled using a C# "if" statement. These statements evaluate variables and return either true or false. Depending on the result, control changes to either within the if statement brackets or outside of them. We'll learn how to control code flow using Boolean variables and the if statement in this article.

The if Statement

The if statement goes hand-in-hand with logical and relational operators. The operators perform the comparison of two variables, and the if statement contains the statements that run depending on the result of the comparisons.


Let's first take a look at a basic template for the if statement.

if (condition) 

   ...Code to be executed 

}

Note that the if statement requires all lower case letters. If you use "If" in place of "if," the compiler will fail and throw you an error. This is opposite of VB.NET, which uses a capital "i" for its if statement.

The condition is set in parenthesis. The condition uses comparison operators (also called relational operators). Relational operators compare if a variable is greater than, less than, equal to or not equal to another variable. If the condition equals true, then the code within the brackets labeled "Code to be executed" runs. If the result is false, then the if statement's code is completely skipped and any code after the brackets runs.

You can also use the if-else statement. The if-else statement executes an alternative set of statements if the condition is equal to false. Let's take a look at a template for the if-else statement.

if (condition) 

     code to execute 

else 

   execute this code instead

}

Notice that most of the if-else statement is the same as the previous if example, but this time we added an else section. The same execution is made with the if statement and the condition result. If the condition evaluates to true, the code in the first section labeled "code to execute" runs. If the result is false, the statements within the else statement labeled "execute this code instead" runs. The if-else statement allows you to provide an alternative set of instructions should the condition evaluate to false.

Now that we know how to create an if statement, we now need to understand the relational operators needed for the condition statements. C# has 6 main relational operators you'll use to create your conditions. Operators include:

Equal to                                  ==

Not equal to                            !=

Greater than                           >

Less than                                 <

Greater than and equal to      >=

Less than and equal to            <=

Let's first take a look at what these operators do within an if statement.

string name = "John";

if (name == "John")

{

   Console.WriteLine("Welcome " + name);

}

You'll recognize the string variable assignment. We create a string variable named "name" and then assign the value "John" to it. We then step into the if statement. The if statement uses the equal relation operator to compare the variable name. You can compare two variables or a variable and a static value. In this example, the static value is "John." If name is equal to John, then the condition is equal to true. Since we give the variable name the "John" at the beginning of our code, you can see that this expression evaluates to true. In normal coding, you'll usually compare two variables, so you won't be able to project the outcome of the expression.

Since the condition evaluates to true, the statement within the if condition is executed. Any statements within these brackets will execute when the condition is true. In this example, simple output to the console is displayed.

Let's take a look at another example with a different relation operator.

string name = "John";

if (name != "John")

{

   Console.WriteLine("Welcome " + name);

}
else 

{

   Console.WriteLine("We don't know your name.");

}

Now we added an else statement. Notice that we also changed the relation operator. We changed the condition to use the not equal to ( != ) operator. This condition now evaluates to false since the name variable does indeed equal the "John" value.

Since the condition evaluates to false, the first set of statements are ignored. We added an else statement, which basically tells the program "if the condition is false, default code execution to these statements." In this example, we print an alternative message to the console. In this example code, the result is that the message "We don't know your name" is displayed to the user.

The "equal to" and "not equal to" operators are useful for strings, but what about numbers? The other operators are beneficial when you want to compare numeric values. Let's take a look at the other operators in action.

int mynumber = 2;

if (mynumber > 2)

{

   Console.WriteLine("Your number is {0} ", mynumber);

}
 

We changed the code from the previous examples. First, we created an integer in the first line of code instead of a string. Next, we changed the Console.WriteLine function to print an integer instead of using strings.

In this example, we assign the value of 2 to our integer variable named mynumber. We then use the if statement condition to evaluate the value of mynumber. The value of mynumber is 2, so this condition evaluates to false. The result is that the if statement is skipped and code execution begins with the next statements after the brackets. We don't have any statements in this example, so the program would end.

What if we wanted to include the value two, though, in our if statement condition? The C# language provides you with the >= relational operator. This operator tells the program to evaluate if the value is greater than another or equal to. Let's chance the code in our sample.

int mynumber = 2;

if (mynumber >= 2)

{

   Console.WriteLine("Your number is {0} ", mynumber);

}

This one small change in the logic completely changes the execution flow for your program. We added >= to the condition logic, and now the code within the if statement brackets will execute. Again, it's easy to see the outcome of these statements since we define the variable and assign it a value right before the if statement runs. However, larger programs will have additional logic and statements that change the condition outcome. As you can probably guess, just one small logic change can cause huge bugs in your code. These bugs or errors are called logic errors. For this reason, always ensure that you test your conditions against several values to ensure that you have the right logic in your if statements.

The Else-If Statement

You aren't limited to just two options in an if statement. What happens when you need to test against more than one condition? You can use the else-if statement.

Let's first take a look at the else-if template.

if (condition) 

     code to execute 

else if (condition) 

   execute this code instead

}
 

Notice that the template is the same except for the else section. The else section has an additional condition and another if. This section evaluates a second condition in your logic. Let's take a look at another example.

int mynumber = 2;

if (mynumber > 2)

{

   Console.WriteLine("Your number is greater than two. ");

}

else if (mynumber == 2)

{

   Console.WriteLine("Your number is equal to two.");

}

else 

{

   Console.WriteLine("We don't know your number.");

}

As you can see, if statements with multiple if and else statements can get difficult to understand. In this statement, we have 3 outcomes. The first condition evaluates if the number is greater tthan 2. Since it's not, the next else-if statement is executed. Instead of defaulting to the else statement, the program performs another comparison. In this condition, we evaluate if the number is equal to two. Since this condition evaluates to true, the statements within the else-if brackets are executed. The else section is never executed since the else-if statement returns true.

When you have several else-if statements, the execution flow just goes down the list of else-if statements until one of them equals true. If none of them equal true, code execution flows to the else statement. If you have no else statement and none of the conditions evaluate to true, the if statement is skipped altogether.

You can have several else-if conditions in your if statement. However, this is usually a poor way to create code. Once you have several else-if statements, you should turn the if statement into a function and use your logic in a function or class method.

Logical Operators

We described the else-if statement, but you can make your code more efficient and easier to read with logical operators. Logical operators let you combine conditions, so you can evaluate multiple variables in one if statement. Let's use the example from above.

int mynumber = 2;

if (mynumber > 2)

{

   Console.WriteLine("Your number is greater than two. ");

}

else if (mynumber == 2)

{

   Console.WriteLine("Your number is equal to two.");

}

else 

{

   Console.WriteLine("We don't know your number.");

}

We have two conditions in the above if statement. We first evaluate if a number is greater than two, and then we identify if the number is equal to two. Let's change this code to make it more efficient.

int mynumber = 0;

if (mynumber > 2 || mynumber < 1)

{

   Console.WriteLine("Your number is greater than two or less than one. ");

}

else 

{

   Console.WriteLine("We don't know your number.");

}

We've changed some values and changed the logic of our code. We first create our mynumber variable and assign it a value of 0. You should recognize the two conditions. The first one identifies if mynumber is greater than 2. The second one identifies if the mynumber variable is less than 1.

The || is the logical operator. This operator stands for "or." The if statement says "evaluate to true if mynumber is greater than 2 or mynumber is greater than 1." The || statement always returns true if at least one statement evaluates to true. Since mynumber is equal to zero, the second condition evaluates to true. Therefore, the if statement as a whole returns true and the if statement's block of code executes. In this example, the result is that "Your number is greater than two or less than one" is displayed on the screen.

A second logical operator lets you combine the two conditions and only return true if both statements are true. Let's take a look at the same code except with the logical and operator ( && ).

int mynumber = 0;

if (mynumber > 2 && mynumber < 1)

{

   Console.WriteLine("Your number is greater than two or less than one. ");

}

else 

{

   Console.WriteLine("We don't know your number.");

}

We changed the code in only one place. We changed the logical or ( || ) to the logical and symbol ( && ).

This if statement says "evaluate to true if mynumber is greater than two and mynumber is less than one." Of course, this statement would never evaluate to true, but we use this as an example to illustrate how to use the && operator. When the && symbol is used, the if statement only returns to true if both conditions equal true. If any one of the conditions evaluate to false, the entire if statement returns false and the code within the else brackets is executed.

We showed you two conditions combined with the logic operators, but you can have several within one if statement. However, if you use too many logic operators within an if statement, it's suggested that you break out the if statement into a function or class method. The if statement can be very difficult to troubleshoot if too many conditions are created within one if block.

Embedding If Statements

One last coding trick with if statements includes embedding them together. Embedding if statements is sometimes necessary when you need to perform a Boolean condition within an if statement. Let's take a look at an example.

int mynumber = 0;

if (mynumber > 2 || mynumber < 1)

{

   Console.WriteLine("Your number is greater than two or less than one. ");

   if (mynumber == 0)

{

   Console.WriteLine("Your number is equal to zero. ");

}

}

else 

{

   Console.WriteLine("We don't know your number.");

}

Notice that we added an additional if statement within the if brackets. This allows you to create additional logic in your code. First, the variables are evaluated in the main if statement. We use the logical or operator to set the condition to true if mynumber is either less than 1 or greater than 2. Since we set the variable with a value of 0, this if statement evaluates to true. Remember with the logical or statement, only one condition must evaluate to true for the entire if statement to return true. Since the second condition evaluates to true (mynumber < 1), the execution flow falls into the if statement brackets.

The second if statement only has one condition. It evaluates if mynumber equals 0, which it does. Therefore, the second if statement content is also executed. The result of the above code is that "Your number is greater than two or less than one" is displayed as well as "Your number is equal to zero." As you can see, the if statement is a powerful way to control the way your code is executed.

We covered logical operators, relational operators, and the if statement. You can create complex programs with these C# concepts, and you will need them in any program you create whether it's desktop or web applications.