If...Else If...Else

Updated: May 20, 2020

It’s great to know what conditional checks are and how to store their results into a variable. However, the real value comes when you understand how to use them to direct the flow of the application.

If statements are a common way to use conditional checks in your code.


IF Statements

An if statement will execute a block of code if the condition it checks resolves to true. The syntax of an if statement in C# follows:


IF(Condition Check)

{

Block of code to execute

}


Notice that the condition check is enclosed by paratheses. The parentheses are how Visual Studio separates the condition check from the rest of the code.


The code to be executed is contained between the curly braces { } to tell Visual Studio what code statements to run. The code will only execute if the result of the condition check is TRUE.

int computerAge = 24;
int userAge = -1;
Console.WriteLine("What is your age?");
string userInput = Console.ReadLine();
bool isValidInput = int.TryParse(userInput, out userAge);
 
if (isValidInput == true)
{
Console.WriteLine($"You are {userAge} years old.");
}
if (isValidInput != true)
{
Console.WriteLine($"You entered \"{userInput}\" which is not a valid number.");
}

This code will run the TryParse method to determine if the user provided a valid number to store in the userAge variable. After calling that method, there are two IF statements. Each one has a different condition check. The first one checks if the value is TRUE, the second checks if the value is anything but TRUE.


Since the input is either valid or invalid, there are only two possible outcomes for this condition check. In situations like this, two IF statements are unnecessary. The ELSE statement exists to handle these situations.


ELSE Statement

The ELSE statement, partners with an IF statement and allows you to provide an auxiliary code block that will execute if the condition check in the IF statement results in a FALSE value.


The syntax of the ELSE statement is similar to the IF statement, except there is no conditional check.

ELSE

{

Block of code to execute

}


As with the IF, the brackets are used to tell the application what code to execute.

if (isValidInput == true)
{
Console.WriteLine($"You are {userAge} years old.");
 }
else
{
Console.WriteLine($"You entered \"{userInput}\" which is not a valid number.");
}
 
if (userAge == computerAge)
{
Console.WriteLine("We are the same age!");
}
else
{
Console.WriteLine("We are not the same age.");
}

In these code samples, there is a code block that will run if the condition check results in TRUE or FALSE.


What if you wanted the application to do a second condition check if the first one is FALSE, before defaulting to the ELSE statement.


For this situation, you would use and ELSE IF statement.

ELSE IF Statement

The ELSE IF statement sits between the IF and the ELSE statement. It will not run if the condition check if the IF statement results in a TRUE value.


However, if it results in a FALSE value, the application will execute the ELSE IF condition check. If that check results in a TRUE value, the code block of the ELSE IF is executed. If the ELSE IF results in a FALSE value, the application will execute the ELSE block.


The ELSE IF statement syntax is identical to the IF statement with an insertion of the ELSE keyword.


ELSE IF(Condition Check)

{

Block of code to execute

}


if (userAge > computerAge)
{
Console.WriteLine($"You are {userAge - computerAge} years older than me!");
}
else if (userAge < computerAge)
{
Console.WriteLine($"You are {computerAge - userAge} years younger than me!");
}
else
{
Console.WriteLine("We are the same age.");
}

In this code segment, the IF statement checks if the userAge is a higher number than computerAge. If this check results in FALSE, the application will perform the ELSE IF condition check to see if userAge is lower than computerAge. If this results in FALSE the application will execute the code in the ELSE block.

Logical Operators

There will be times when you need to perform more than one condition check to determine which block of code to execute. To perform multiple checks, you will need to use one of two logical operators.


AND Operator (&&)

The double ampersand will check multiple conditions and only execute the code block if both condition checks result in a TRUE value

 if (userAge == computerAge && userAge >= 21)
 {
 Console.WriteLine("We are the same age. Let's get a drink.");
 }

This code block will only execute if userAge and computerAge are the same, and that age is 21 or higher.


OR Operator (||)

The double pipe character will check multiple conditions and execute the code block if at least one condition checks result in a TRUE value

 if (computerAge < 21 || userAge < 21)
 {
 Console.WriteLine("Looks like at least one of us is having soda.");
 }

This code block will execute if userAge is lower than 21 or computerAge age is lower than 21. If both condition checks result in TRUE (if both ages are lower than 21), the code block will still execute.


Chaining It Together

You can chain as many ELSE IF statements together that you need. You can also perform multiple condition checks in different statements. The following code shows an example of this.

if (userAge >= 21)
 {
 Console.WriteLine("You are permitted to buy alcohol");
 }
 else if (userAge == 19 || userAge == 20)
 {
 Console.WriteLine("You can have a beer in Canada");
 }
 else if (userAge == 18)
 {
 Console.WriteLine("One more year until you can drink in Canada");
 }
 else if (userAge > 13 && userAge < 18)
 {
 Console.WriteLine("Do your parents know you are trying to buy alcohol");
 }
 else
 {
 Console.WriteLine("Hey Kiddo. Here's a can a soda");
 }

Using the IF statements with Strings

The String object has several methods where understanding IF statements will prove beneficial.


Checking for Null or Empty

The first and probably the most used method is the IsNullOrEmpty method. This method allows you to validate that the user entered a valid text value to store in your string variable.

 Console.WriteLine("What is your name");
 string userName = Console.ReadLine();
 
 if (string.IsNullOrEmpty(userName) == true)
 {
 Console.WriteLine("You have entered invalid text.");
 }
  else
 {
 Console.WriteLine($"It's great to meet you {userName}!");
 }

Checking for Equality

Another popular method is the Equals method of the String object. As discussed in the blog post about Comparison Checks and Boolean Values, the Equals method is an efficient way to compare two strings. You can use an IF statement to determine what happens with that condition check.

 Console.WriteLine("Would you like to quit the application (Yes/No)");
 string answer = Console.ReadLine();
 if (answer.Equals("yes",StringComparison.OrdinalIgnoreCase) == true)
 {
 Environment.Exit(0);
 }

With this code segment, the application will exit if the user enters any variation of the word “yes” (YES, yes, Yes).


Checking for Values

The String object also has a few methods that allow you to check for text values within the string. This is helpful when you are searching a string for specific information.

 string[] courses = new string[]
 {"BIO 100", "BIO 200", "BIO 400", "MTH 100","MTH 200","PSY 400"};
 
 foreach (string course in courses)
 {
 Console.WriteLine($"You have registered for {course}");
 if (course.StartsWith("BIO") == true)
 {
 Console.WriteLine("Biology is fun!");
 }
 if (course.EndsWith("400") == true)
 {
 Console.WriteLine($"{course} is a tough class. Good Luck!");
 }
  }

When executed, this code will display custom messages dependent on the beginning and end of each course.


Using the IF statements with Lists

The IF statement provides you with the ability to do condition checks with your list and array objects. This ability is beneficial to ensuring your application performs as expected.


Checking for Number of Elements

You can use the IF statement to check the number of elements in a list. For example, if you were writing a ticketing application for a kids' amusement park, you could write logic that allows a discount for multiple kids.

List<string> kidNames = new List<string>();
 kidNames.Add("Geoff");
 kidNames.Add("Lindsey");
 kidNames.Add("Heidi");
 kidNames.Add("Drew");
 
 if (kidNames.Count > 2)
 {
 // Apply discount logic here
 }

Checking the number of elements is also very common to determine whether or not to execute specific branches of code.

 if (kidNames.Count == 0)
 {
 Console.WriteLine("You have no kids. Exiting the application");
 Environment.Exit(0);
 }
 else if (kidNames.Count > 2)
 {
 // Apply discount logic here
 }
 else
 {
 // Apply normal pricing 
 }

Checking for Specific Values

You can also use the if statement to check for a particular value. If your amusement park offered free entry for kids under two, you would use the Contains() method of the list.

 List<int> kidAges = new List<int>();
 kidAges.Add(2);
 kidAges.Add(5);
 kidAges.Add(12);
 kidAges.Add(17);
 
 if (kidAges.Contains(2))
 {
 Console.WriteLine("Children two and under are free.");
 }

22 views0 comments

Recent Posts

See All