Branching and Looping in C#, Part 1 - Combining else With if
(Page 4 of 6 )
You can combine else with if in one statement to execute more than one test on the expression. As you already know, if tests the expression, and if it evaluates to false, the else block will be executed. Sometimes this is not what we need, however. We may need to be very specific with the else part. For example, take a look at the following code:
int x = 5;
if(x != 0)
{
Console.WriteLine("x != 0");
}
else
{
Console.WriteLine("x = 0");
}
There is nothing special about this code; but notice that with the if statement we test to see if the x is not equal to zero, and if so, it will execute the if block, and else it will execute the else block. Now let's look at the following code:
using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
int x = 5;
if(x == 0)
{
Console.WriteLine("x != 0");
}
else if(x == 4)
{
Console.WriteLine("x == 4");
}
else if(x == 5)
{
Console.WriteLine("x == 5");
}
else
{
Console.WriteLine("x = 0");
}
Console.ReadLine();
}
}
}
if you compile and run the application, you will get the following in the console window:

C# features the combination of else with if to further test the Boolean expression (only when the if statement evaluates to false), so if the if Boolean expression evaluated to true, the else if statements will never be tested. I will rewrite the above code as follows:
using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
int x = 5;
if(x != 0)
{
Console.WriteLine("x != 0");
}
else if(x == 4)
{
Console.WriteLine("x == 4");
}
else if(x == 5)
{
Console.WriteLine("x == 5");
}
else
{
Console.WriteLine("x = 0");
}
Console.ReadLine();
}
}
}
You will get the following result:

This is an unexpected result, because x is assigned 5. It is true that x is assigned 5, but the code was not perfect; the if statement tested to check if x is not equal to 0, and it's not equal to zero, so it escaped the next else if statement, and that's why we got this value. With this in mind, never use an expression that is misleading while using else if statements.
Next: The switch Statement >>
More C# Articles
More By Michael Youssef