
Nested if statements are useful. They are different from if-statements that use the && operator. In certain contexts they compile to the same intermediate language. Nested if-statements can be clearer than expressions in some cases. They are less clear in other cases.
This C# program uses an if-statement nested within another if-statement.

This program introduces three methods: Method1, Method2, and Method3. Method1 uses a nested if-statement; it checks that the variable is greater than or equal to 10 and less than or equal to 100. Method2, meanwhile, does the exact same thing as Method2 but uses the && logical AND operator to put both tests in a single expression. With logical AND, the runtime will stop evaluating expressions if one is false—this is called short-circuiting.
Short-CircuitProgram that shows if-statements [C#]
using System;
class Program
{
static void Main()
{
Method1(50);
Method2(50);
Method3(50);
}
static void Method1(int value)
{
if (value >= 10)
{
if (value <= 100)
{
Console.WriteLine(true);
}
}
}
static void Method2(int value)
{
if (value >= 10 &&
value <= 100)
{
Console.WriteLine(true);
}
}
static void Method3(int value)
{
if (value <= 100 &&
value >= 10)
{
Console.WriteLine(true);
}
}
}
Output
True
True
TrueDescription. Method1 and Method2 will have the exact same performance characteristics. If the value is less than 10, it will never be tested against 100. Method3, however, flips the two conditions so that the variable is tested against the upper limit first. Method3 would be slightly faster if more of the method's input is greater than 100 than is less than 10.
Note: This is because the second check would be short-circuited.

If-statements compile into branch instructions. You can think of branch instructions as GOTO statements, in that they test a very simple expression and then conditionally "jump" to another instruction based on an offset value. When the C# compiler encounters if-statements (and nested if-statements), they are translated into branch statements.
Tip: Nesting is not relevant to the compiler's final representation of the program.

We nested some if-statements and also compared nested if-statements to an if-statement that uses the logical AND operator in an expression. With logical AND, short-circuiting yields the same performance benefit of nested if-statements and also requires less source code. Nested if-statements are necessary in some contexts where expressions are mixed with statements, but in many other situations using logical AND is clearer to read.
If Statement