Updated: May 20, 2020
Many times, when writing software, you will need to branch your program logic based on a set of conditions. A user decision could determine the outcome of a video game. The value of an integer might trigger different display messages. The current date and time may cause something to be marked “past due” or “expired”. Each of these conditions would perform a different action in your application.
To determine which branch your application needs to take, you need to perform a “conditional check,” which results in a value of TRUE or FALSE. The user did not select the right answer; conditional check equals FALSE. The current date is higher than the expiration date; condition check equals TRUE.
When working with C#, there are many types of conditional checks.
Before you get into the details of if statements, you need to make sure you have a clear understanding of what a condition check is. This small segment of code trips up many people attempting to learn how to write software.
This fact was mentioned earlier but bore repeating. Condition checks will evaluate a condition and provide a TRUE or FALSE. The TRUE/FALSE is the result of the check; it is not related to the values inside the condition.
Condition: “5 equals 7 – 2” Result: True
Condition “ 5 does not equal 10 – 2” Result: True
Condition “TRUE equals FALSE” Result: False
Condition “FALSE equals FALSE” Result: True
Condition “John equals Scott” Result: False
As you can see from the examples, the result of the condition check is not reliant on specific values in the condition; it only cares about the result of the check.
To write and understand condition statements, you need to know the different comparison operators available in C#.
The following table lists out the most common ones.
Pay close attention to the operator used to check the equality of two values. With C#, a single equal sign (=) is used to set a value. Every time Visual Studio comes across a single equals sign, it will try to set the value of whatever is on the left of the sign. If you want to compare the equality of two values, you need to use two equal signs (==).
int x = 10, y = 20; Console.WriteLine(x == y); // Displays FALSE Console.WriteLine(x = y); // Displays 20
Comparing numeric values are pretty straightforward when you use the comparison operators from the earlier table. Each operator will compare the value on the left side with the value on the right. The condition check will return a TRUE or FALSE, depending on the result.
int x = 10, y = 20, z = 10; Console.WriteLine(x == y); // Displays FALSE Console.WriteLine(x != y); // Displays TRUE Console.WriteLine(x < y); // Displays TRUE Console.WriteLine(x < z); // Displays FALSE Console.WriteLine(x >= y); // Displays FALSE Console.WriteLine(x <= z); // Displays TRUE
Comparing string is a little more involved. If you recall, C# is case-sensitive, so “Scott” and “scott” are not equal.
To check for equality, you can use the ToLower() method of the string variable that you learned about in a previous post.
Console.WriteLine(nameOne == nameThree); // Displays FALSE Console.WriteLine(nameTwo.ToUpper() == nameThree); // Displays TRUE Console.WriteLine(nameOne.ToLower() == nameThree.ToLower()); // Displays TRUE
Using ToUpper() or ToLower()is only one way to check for equality with string values. But, as you can see, requires some extra work.
Another way you can check to see if two strings are equal is by using the string.Equals() method. The Equals method will compare two values and return a TRUE if they are equal, FALSE if they are not.
string nameOne = "Scott", nameTwo = "scott", nameThree = "SCOTT"; Console.WriteLine(nameOne.Equals(nameTwo)); // Displays FALSE Console.WriteLine(nameTwo.Equals(nameThree)); // Displays FALSE Console.WriteLine(nameOne.Equals(nameThree)); // Displays FALSE
All three Equals checks in this code segment will result is FALSE. This result occurs because each value has a different case configuration. Fortunately, the Equals method allows you to include a StringComparision value, which will change the way the method checks for equality.
The most common StringComparison types are detailed here:
Ordinal – When making an “ordinal” comparison, any language features are stripped out, and each character is reduced to its numeric value. At this point, the numerical value of the two strings is compared. This method is the fastest, most efficient way to compare string. It is the default comparison type used by the Equals method.
CurrentCulture/InvariantCulture – These two comparison types take into consideration a culture-specific alphabet when interpreting the value of each character. Which alphabet the application uses will depend on which culture type you choose.
InvariantCulture will use a default setting that will be identical on every computer that runs the application
CurrentCulture will use the culture setting that is set in the control panel on the individual computer running the application
IgnoreCase – All of the previous types take the case of the character into account. However, each type also has an “IgnoreCase” option that will follow the rules of the comparison type but ignore the case of the character.
If you update the code from earlier with a StringComparison type. You will get a different result.
string nameOne = "Scott", nameTwo = "scott", nameThree = "SCOTT"; Console.WriteLine(nameOne.Equals(nameTwo,StringComparison.OrdinalIgnoreCase)); // Displays TRUE Console.WriteLine(nameTwo.Equals(nameThree, StringComparison.OrdinalIgnoreCase)); // Displays TRUE Console.WriteLine(nameOne.Equals(nameThree, StringComparison.OrdinalIgnoreCase)); // Displays TRUE
Throughout this post, we have displayed multiple TRUE or FALSE values. What if we want to actually store that value into a variable and use it later in our code. The Boolean data type is used for this situation.
To declare a Boolean variable, you need to use the “bool” keyword. The name of your variable should make it clear that it contains a value of TRUE or FALSE.
bool isUserOfAge; bool areValuesEqual; bool isInputValid;
You can initialize the variable by giving it a literal value, using the value of another variable, or as the result of an operation.
isInputValid = false; isUserOfAge = userAge >= 18; areValuesEqual = validPassword.Equals(userPassword);
Conditional checks and Boolean variables are prevalent in all sorts of application. They are used to branch logic, determine looping frequency and validate input. You will see both of these concepts in multiple posts.