Boolean Expressions Demo


C# Conditional Branching
2m 15s

The course is part of this learning path

Start course


The ability for software to perform tasks or functions based on the state of variables or data is intrinsic to programming. In plain language, that means responding appropriately to input from the user or some data feed. C# Conditional Branching primarily focuses on If and Switch statements, the main mechanisms for executing or branching to different code depending on whether a condition is true or false. A simple example is allowing users to log in if their username and password match those stored in the software.

Learning Objectives

  • Learn and understand If-statement syntax and how to use it in different scenarios
  • Learn and understand the Switch statement and how to use it 
  • Learn about evaluating multiple Boolean conditions
  • See how the dotnet new command has changed with the release of .NET 6.0 and C# 10

Intended Audience

This course is intended for students that are relatively new to programming but not absolute beginners and want to know how to make their software responsive and adaptive. Students should know the basics of a C# programs structure and have experience running a program within their development environment. While for-loops and object-oriented concepts will be mentioned in the course, in-depth knowledge of these topics isn't essential.


Demo Source Code


There are gaping holes in the moth light example, like we have three light sources but are only comparing two at a time. We can address some of the problems by doing multiple Boolean evaluations in one if-statement. We use the double ampersand operator to "and" Boolean comparisons together, meaning all comparisons must be true for the combined expression to be true. If only one of the comparisons needs to be true for the combined expression to be true, we use the double pipe "or" operator. We can use the exclamation character to negate the result of an expression. In plain language, that means making true false and false true. As with arithmetic, we use brackets to isolate and give precedence to comparisons within a compound expression.

I'll start by adding a porch and neighbor comparison to the first if-statement, so we only head to the porch light when it is brighter than the moon and the neighbors. While I'm at it, let's change the greater than to greater than and equal to. Great, that works as intended. However, if I alter the lumen values and replace the "and" with an "or," instead of going to the neighbors the moth heads to the porch. It's worth mentioning that the C# compiler is smart enough to know that in an "or" scenario, once it has found a true condition, it won't bother evaluating any other comparisons in the expression.

I've gone as far as I can with the moth example. I'll pack moth light away within a region. Unlike Visual Studio, VS Code doesn't have region functionality built into the editor. I installed #region folding for VS Code to get something akin to Visual Studio regions, although not quite as convenient.

In this demo I want to rank pasta on type, brand, and price. I have a pasta class with a public bool member called fresh, which is true for fresh pasta and false for dry pasta. There is a  decimal price member, a string member for the brand, two int members for storing the brand and type ranking, and a read-only rating member that returns the two rankings summed together. We have a default constructor and one that allows us to set fresh, price, and brand on instantiation. I've overridden the ToString method to return the brand, pasta type, and price. Below the pasta parent, I have the pasta children representing different varieties of pasta. Back to the main program. 

I'll start by defining the maximum price I'm willing to pay for fresh and dry pasta. Next, I'll add an array of strings with the pasta varieties ordered from most to least preferred. Each variety string corresponds to a child pasta class name. I have a string array of brand preferences ranked from most to least preferred in the same vein. Now we need a list of pasta to rank, which means adding the system.collections.generic using statement. I'll just paste in my pasta. The "M" after the price in the constructors means treat the floating-point price as a decimal rather than the default double. We'll need another list called pastaChoice to hold the ranked pasta.

For each pasta in the pastas list, we get its variety by using the object's GetType method, converting it to a string, and storing it in pastaName. GetType will return the class Lasagne for the first pasta, and ToString will convert the class name to a string. I'll also initialize brand and type ranks to zero. Right, that's the setup taken care of.

The first thing we need to do is make sure the pasta meets our price conditions. If the pasta is fresh and its price is less than or equal to the fresh pasta price, or the pasta is dry, so not fresh and is less than or equal to the dry pasta price, continue. This is a good example of using brackets to mix "and" and "or" operators. We use the "and" to associate the correct price with the pasta type, but either one of the compound expressions can be true for the if-statement to be true.

Next, we need to rank the pasta variety by comparing the pasta name with the pasta preference array. When we get a match, we take "i," the array index, add one to it, and assign it to the pasta type rank. Using double plus in front of or to the left of the, i, adds one before assigning the value – remembering that arrays start at index zero. We'll do the same routine for ranking the pasta brands, but I'll fast forward through the typing.

We need to add the ranked pasta to the pasta choice list, so that's pasta where type and brand ranks are greater than zero. Because we'll be inserting into the list, a for loop won't do for iterating through pasta choice, so I'll use a while loop. We iterate through the loop while i is less than the pasta choice count. The first time through, when the pasta choice list is empty, so its count is zero, we don't enter the while loop and add the first item when i and count both equal zero. 

This last if-statement also adds lowly ranked items to the end of the list. Meaning we've iterated through the list without meeting the if-statement condition, and i equals the list count. Inside the while loop, we compare the pasta rating with items already in pasta choice. If the rating, which is just the combined ranking, is less than an existing choice, we insert it ahead of it. However, if the ratings are equal, we resort to price comparison. So the ratings are equal, and the pasta price is less than the current pasta choice price. Once we have ranked all the eligible pasta, we write them out to the console in preference order. Let's run that to make sure it compiles. There we go – a simple little pasta ranking program demonstrating the use of Boolean and, or, and not operators in if-statements.

About the Author
Learning Paths

Hallam is a software architect with over 20 years experience across a wide range of industries. He began his software career as a  Delphi/Interbase disciple but changed his allegiance to Microsoft with its deep and broad ecosystem. While Hallam has designed and crafted custom software utilizing web, mobile and desktop technologies, good quality reliable data is the key to a successful solution. The challenge of quickly turning data into useful information for digestion by humans and machines has led Hallam to specialize in database design and process automation. Showing customers how leverage new technology to change and improve their business processes is one of the key drivers keeping Hallam coming back to the keyboard. 

Covered Topics