Learning Resources
 

The if Statement


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.

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

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.

Which means: 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