How do these practically differ?
// Approach one
if (x == 1)
DoSomething();
else if (x == 2)
DoSomethingElse();
// Approach two
if (x == 1)
DoSo
Note that there is no else if
construct in C#. Your first code sample is exactly the same as:
if (x == 1)
DoSomething();
else
{
if (x == 2)
DoSomethingElse();
}
Since there is only one statement in else
, the braces can be omitted, and for enhanced readability, if
is usually written on the same line as the preceding else
. Writing multiple "else if
" statements is equivalent to further nesting:
if (x == 1)
DoSomething();
else
{
if (x == 2)
DoSomethingElse();
else
{
if (x == 3)
YetSomethingElse();
else
{
if (x == 4)
ReallyDifferent();
}
}
}
The above can be written as:
if (x == 1)
DoSomething();
else if (x == 2)
DoSomethingElse();
else if (x == 3)
YetSomethingElse();
else if (x == 4)
ReallyDifferent();
From this, you can see that chaining "else if
" and if
can produce different results. In case of "else if
", the first branch that satisfies the condition will be executed, and after that no further checks are done. In case of chained if
statements, all branches that satisfy their conditions are executed.
The main difference here is when execution of a branch causes a subsequent condition to become true. For example:
var x = 1;
if (x == 1)
x = 2;
else if (x == 2)
x = 3;
VS
var x = 1;
if (x == 1)
x = 2;
if (x == 2)
x = 3;
In the first case, x == 2
, while in the second case x == 3
.