C# If Statement

Array Collections File String Windows VB.NET Algorithm ASP.NET Cast Class Compression Convert Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method .NET Number Regex Sort StringBuilder Struct Switch Time Value

If keyword

The if-statement is a selection statement. It directs the control flow of your C# program. It is translated to intermediate language instructions called branches. It makes a logical decision based on a parameter or a user's input. Expressions in an if-statement evaluate always to true or false.

Write your code so that the normal path through the code is clear. Make sure that the rare cases don't obscure the normal path of execution. This is important for both readability and performance. McConnell, p. 355

If example

This program simply computes the value of an expression and then tests it in an if-statement. The condition inside the if-statement is evaluated to a boolean value and if the value is true, the inner block is executed.

Program that uses if statement [C#]

using System;

class Program
{
    static void Main()
    {
	int value = 10 / 2;
	if (value == 5)
	{
	    Console.WriteLine(true);
	}
    }
}

Output

True

Overview: This C# tutorial displays the if-statement. It also demonstrates else-if and else.

If/else example

Next, let's look at an example of a method called Test that internally uses the if-statement with two 'else if' blocks and one 'else' block. The example method returns a value based on the formal parameter. The order the if-statement tests are written in is important. We must test the more restrictive conditions first, or the less restrictive conditions will match both cases.

Program that uses if-statement [C#]

using System;

class Program
{
    static void Main()
    {
	// Call method with embedded if-statement three times.
	int result1 = Test(0);
	int result2 = Test(50);
	int result3 = Test(-1);

	// Print results.
	Console.WriteLine(result1);
	Console.WriteLine(result2);
	Console.WriteLine(result3);
    }

    static int Test(int value)
    {
	if (value == 0)
	{
	    return -1;
	}
	else if (value <= 10)
	{
	    return 0;
	}
	else if (value <= 100)
	{
	    return 1;
	}
	else // See note on "else after return"
	{
	    return 2;
	}
    }
}

Output

-1
1
0
Main method

Overview. We define two methods, the Main entry point and a Test static method. The Main method body calls the Test method three times. The Test method internally uses several branching instructions that are expressed in the high-level if-statements. The formal parameter of the Test method is tested against the value zero, and then tested to see if it is less than or equal to ten, and then 100.

Static MethodElse keyword

Else return. The Test method uses a four-part if-statement with an else clause that returns a value. Because all of the conditions in the if-statement return a value, there is no reachable point in the method after the else statement. You could delete the else statement and put the "return 2" code on a separate line. This reduces the symmetry of the code but also reduces the line count and syntax noise in the code.

Else Statement

Nested ifs

Nesting if-statements will create a similar flow of control to using the boolean && operator. The arrangement of your if statements will impact performance in some situations. We explore nested ifs in more detail.

Nested If

Switch

The C# language provides a switch construct that in many cases will provide better performance and clearer code than if-statements. The compiler can turn integer or enum switch statements into jump tables and string switches into Dictionary instances, which provide a constant time lookup operation. Switch statements can only test an expression against constant values—this is their main limitation.

Switch Statement

Ternary operator

Question and answer

The ternary operator in the C# language allows you to express a predicate and consequent statement in a single statement. In other words, you can embed an if-statement inside a single statement. The ternary operator is most easily identified by the "? :" syntax.

Ternary Operator Use

Null coalescing operator

The null coalescing operator is similar to the ternary operator but can only be used on a null reference variable. It uses the ?? syntax.

Null Coalescing Operator

Performance

Performance optimization

In a complex program with many paths, sometimes having many if-statements for less-common paths can reduce performance for common paths. This problem can be solved by using a lookup table or Dictionary that encodes the branches in data objects. Also sometimes you can simply reorder the if statements in your program to put the most common ones first.

Short-Circuit If Versus Switch Performance Reorder If Statements

High-level language translation

.NET Framework information

Let's consider the process by which if-statements are translated into machine code, which is preceded by intermediate language in the .NET Framework. High-level languages provide structured programming models where blocks of code are separated with parentheses.

However, these blocks are meaningless to the execution engine, and are instead translated into single instructions that are part of the intermediate language. If-statements are translated to branch instructions, which tell the execution engine to "jump" forward over several further instructions if a condition matches.

bne Instruction Intermediate Language

Summary

The C# programming language

We looked at examples of the if-statement. Further, we looked at how the branch instructions are used in the low-level representation of the code. We mentioned the style issues related to returning in an else statement, compared the if-statement to switch-statements, and noted how you can use lookup tables to encode selection statements in data.

Dot Net Perls