If-Else Statement

This lesson discusses if-else statements in detail including nested-ifs and if-else if-else statements using examples

Programming in general often requires a decision or a branch within the code to account for how the code operates under different inputs or conditions.

Within the C# programming language, the simplest and sometimes the most useful way of creating a branch within your program is through an If-Else statement.

If-Else Block

As with most of C#, the if statement has the same syntax as in C, C++, and Java. Thus, it is written in the following form:

Press + to interact
if (condition)
{
// Do something
}
else
{
// Do something else
}

Note: The two execution sections are mutually exclusive. Meaning only one of the two sections can execute at a time based on the result of the boolean expression.

The if statement evaluates its condition expression to determine whether to execute the if-body. Optionally, an else clause can immediately follow the if body, ...