The C# If Else Statement: An Overview With Code Examples

c#Conditional statements are a part of every programming language. You will find them in every application with a significant amount of code. Because they are part of the basic fundamentals of coding, you need to know the C# if else structure. (New to C#? Learn the basics.) The basic if statement is a part of any C-derived language, and you can use it to control the execution of code. The most difficult part of learning conditional statements is understanding the logic behind it. When you understand the logic, you know which part of the if else statement will execute.

An Overview of the If Else Condition

The If statement tests a specific condition. If the condition returns the boolean “true,” then the coded statements within the if statement are executed. You can add several conditional statements in one if statement, but it makes it more difficult to keep track of the logic.

The else statement is a way to execute an alternative set of code if the condition returns “false.” Basically, the if else statement says “if this condition is true, execute the code in the first block of code. If the condition is false, then execute the code located in the else block.”

You can also embed if statements. Embedded if statements can be very long, and the longer the if statement becomes, the more difficult it is to keep track of the logic. Although if statements are very basic parts of C# coding, they can get quite complex and difficult to understand.

The Basic If Else Statement

You want your code to read as simply as possible. To grasp the idea of an if statement, the first part is to create a variable that contains a value. This can be any type of value including an integer, string, boolean or array of bytes. For this example, a boolean value will be set. The following code creates a boolean variable in C#:

bool myCondition = false;

A boolean value is really a one or a zero, but in terms of C# coding, a zero generally means “false” and a one generally means “true.” If you were to convert this variable, you would get a “zero” in place of the “false” boolean value. Typically, your code dynamically assigns this variable, but for this example, the variable is statically assigned a value.

The next step is to create the template for your if statement. You can worry about the “else” part of the statement after you set up your main template. The following code is a simple if statement without the else:

if ( < condition > )
{
}

All if statements enclose the condition in parenthesis. The condition always goes within the parenthesis, and the condition is always evaluated by the C# compiler.

Next, you introduce the condition. Add the following code to your statement:

if ( myCondition == false )
{
 // do something here
}

Get started with conditions, loops and logical operators in C#.

Notice the double equal sign in the condition statement. When you use a single equal sign, the compiler thinks you want to assign a value to a variable. A double equal sign is a comparison between two values. If you accidentally use a single equal sign in your if statement, the compiler will return an error.

You can also take shortcuts with condition statements. The exclamation mark will switch your statement. For instance, the following statement is the same as the previous one:

if ( !myCondition )
{
}

Notice the exclamation point is set instead of the condition evaluating to false. When you have a condition without the double equal sign, it evaluates to true. For instance, if you use the following statement, the condition would check if the “myCondition” variable was true:

if ( myCondition )
{
}

The statement above checks if the variable is true. If the value is true, then any statement within the brackets is executed. The if statement before this one uses the exclamation mark to reverse the condition to false.

Next, you need to add the code you want to execute. The following code prints a statement telling the user the value of “myCondition”:

Convert.Write( myCondition.ToString() );

The “ToString” function changes the output to a string. Most developers change printed values to strings to avoid any data type error messages.

Put the whole statement together and you have a full if statement:

bool myCondition = false;
if ( !myCondition )
{
Convert.Write( myCondition.ToString() );
}

 Not familiar with C# statements? Learn how to work with C# syntax.

Adding the Else to Your If Statement

The else statement lets you add an additional way to execute code only if the first if condition is not met. In this example, the condition evaluates if myCondition is false, and if so, the code executes. But, sometimes you’ll need to execute a second set of code if the first condition is not met. This is accomplished with the “else” statement. The following code is an example of an if statement template with the else statement appended at the end:

if ( < condition > )
{
}
else
{
}

Notice the condition is still present, but the else statement is set after the condition’s brackets. To put all the code together and add some code that runs if th condition isn’t met, use the following code:

bool myCondition = false;
if ( !myCondition )
{
Convert.Write( myCondition.ToString() );
}else
{
Convert.Write( “The else statement was executed.” );
}

In the above code, if myCondition is false, the condition’s value is printed. However, if myCondition is true, the second statement “The else statement was executed” is printed. In the above statement, the boolean value is set statically, so the first condition is always met, but usually your code dynamically sets the variable’s value, so there is always a chance that the second block of code executes. Additionally, if you remove the exclamation mark, the logic is switched and the else statement is always executed.

Embedding If Statements and Adding Conditions

There are two additional ways the if statement is used. First, you can embed if statements, so you have several if conditions that are evaluated before the compiler reaches the else statement.

An embedded if statement lets you evaluate one statement and then evaluate a second statement later. For instance, add another variable to the above code using the following syntax:

bool myCondition = false;
string testing = “testing”;

if ( !myCondition )
{
Convert.Write( myCondition.ToString() );
}
else
{
Convert.Write( “The else statement was executed.” );
}

Notice the extra variable added after the myCondition variable. You may want to test this string after you finish evaluating the myCondition variable. You can embed another if statement in the original if statement or in the else statement. The following code adds another if statement to your code:

bool myCondition = false;
string testing = “testing”;

if ( !myCondition )
{
        if ( < condition > )
        {
        }

Convert.Write( myCondition.ToString() );
}
else
{
Convert.Write( “The else statement was executed.” );
}

In this additional code, if myCondition evaluates to false, then the next statement of code is another if condition. This if condition is then evaluated. If it returns true, then the code within this statement is executed. For instance, if you wanted to verify that the testing string contained “testing,” the following syntax applies:

bool myCondition = false;
string testing = “testing”;

if ( !myCondition )
{
        if ( testing == “testing” )
        {
                    Convert.Write( “Testing was evaluated to true.” );
        }

Convert.Write( myCondition.ToString() );
}
else
{
Convert.Write( “The else statement was executed.” );
}

In the above code, the code would print out “Testing was evaluated to true” and the value of myCondition, which is false.

You can add an additional else statement to the embedded if statement. The following code shows you how to add an else statement to your embedded if statement:

bool myCondition = false;
string testing = “testing”;

if ( !myCondition )
{
        if ( testing == “testing” )
        {
                    Convert.Write( “Testing was evaluated to true.” );
        }
        else
        {
                    Convert.Write( “Testing was evaluated to false.” );
        }

Convert.Write( myCondition.ToString() );
}
else
{
Convert.Write( “The else statement was executed.” );
}

In this example, the else statement is executed if the testing variable does not contain the “testing” string.  You could add even another embedded if statement and continue with embedded if statements. However, it’s generally considered bad coding practice to have too many embedded if statements. If you start to have too many if statements with embedded if statements, it’s time to create a separate function to evaluate the variables and separate too many if statements from the coding flow. It’s considered bad coding practice to have several if statements with more embedded statements, because it’s difficult to read for other coders. If you have several if statements, it’s important to set comments in the code, so other coders responsible for your code are able to understand the logic and the general flow of your statements.

You can also add multiple conditions in your if statements. These are generally more traditional than embedding multiple if statements. You use multiple conditions using the “&&” and “||” characters. The “&&” statement says “and this condition is also true.” The “||” statement says “or this statement is true.” For an example, look at the following code:

bool myCondition = false;
string testing = “testing”;

if ( !myCondition && testing != null)
{
        if ( testing == “testing” )
        {
                    Convert.Write( “Testing was evaluated to true.” );
        }
        else
        {
                    Convert.Write( “Testing was evaluated to false.” );
        }

Convert.Write( myCondition.ToString() );
}
else
{
Convert.Write( “The else statement was executed.” );
}

In this statement, the && statement tells the compiler that there is another condition to evaluate. In this condition, the compiler looks to see if the testing variable is null or empty. If you changed from && to ||, you totally change the logic. The “or” logic operator can be tricky when you have multiple conditions to evaluate. When you use the or operator, any one of the multiple conditions that evaluates to true will drop the code into the first if block. This means that if you have three conditions, and one of them that evaluates to true will trigger the if statement. This is one type of logic bug that is difficult to find and fix. The following code is an example of using the or statement:

bool myCondition = false;
string testing = “testing”;

if ( !myCondition || testing != null)
{
        if ( testing == “testing” )
        {
                    Convert.Write( “Testing was evaluated to true.” );
        }
        else
        {
                    Convert.Write( “Testing was evaluated to false.” );
        } 

Convert.Write( myCondition.ToString() );
}
else
{
Convert.Write( “The else statement was executed.” );
}

In the statement above, the condition says “if myCondition is false or testing isn’t null.” Therefore, if myCondition is false or testing isn’t null, the condition’s code will execute. This is an important logical difference that you must pay attention to when creating and structuring your code. Again, because the variables are statically assigned, you know which statements will execute. However, you typically set variables dynamically, so if there is confusion, you can step through the code with a variety of input.

Because you code with C# using Visual Studio, you can use the Visual Studio debugger to step through each statement and drop into the variety of condition statements. Get started working with Visual Studio.

The if statement can be difficult to grasp, and it’s even more difficult to grasp the idea when you add the else statement along with embedded if statements. The if statement is an essential part of all programming code. You will always find if statements in code, even in small projects when you first start out programming in the real world.