Selection Statements

Software is all about the selection statements; we use these to control which parts of code get executed and which do not. There are two different types of selection statements: the if statement and the switch statement.

If Statement

If statements compare the result of an expression, or series of expressions, to determine if a section of code should be executed. The following statement shown in the code box shows a single expression that will always return true. This explicitly states that if the variable executeCode is true then that code is executed.

Explicit Statement

// Initialize variables
bool executeCode = true;
 
if(executeCode == true)
{
    // Execute this line of code
    Console.WriteLine("Hello World");
}

Implicit Statement

However, we need not explicitly state this in all cases. The following shows an example of code that implicitly states that if canExecuteHello is true then the proceeding code may be executed.

// Initialize variables
bool canExecuteHello = true;
 
if(canExecuteHello)
{
    // Execute this line of code
    Console.WriteLine("Hello World");
}

Execution Order

When processing if statements it can sometimes be important to know exactly how it does it. The order that you write your expressions in multiple-expression if statement does matter, although we have not yet had the chance to experience it. When processing each of the epressions if any of them returns true the rest of the expressions need not be evaluated and are skipped.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.