A nested if statement places one decision inside the branch of another decision.
if (player1.isAvailable)
{
if (player1.position == "Goalkeeper")
{
System.Console.WriteLine("Goalkeeper is available.");
}
}The outer condition asks whether the player is available. The inner condition is reached only when that first condition is true.
Start with:
if (player1.isAvailable)If that condition is false, the entire outer block is skipped. The program never reaches:
if (player1.position == "Goalkeeper")If the outer condition is true, execution enters the block and evaluates the inner condition.
Suppose:
player1.isAvailable = true
player1.position = "Goalkeeper"The execution path is:
isAvailable → true
enter outer block
position == "Goalkeeper" → true
run inner blockThe message is displayed.
Think of the structure as:
Is the player available?
|
true
|
v
Is the player a goalkeeper?
|
true
|
v
Display messageThe second question depends on reaching the true path of the first.
An else if chain asks alternate questions when earlier conditions are false.
A nested if asks another question inside a branch that has already been selected.
Conceptually:
else-if chain:
question 1
false → question 2
nested if:
question 1
true → question 2The execution structures are different even when the conditions discuss similar information.
Readable formatting makes the nesting visible:
if (player1.isAvailable)
{
if (player1.position == "Goalkeeper")
{
System.Console.WriteLine("Goalkeeper is available.");
}
}The inner if belongs to the outer true block.
The message belongs to the inner true block.
Braces define the actual block structure.
Suppose:
isAvailable = true
position = "Forward"Predict:
outer condition → true
inner condition → false
message → not displayedThat step-by-step reasoning makes nested flow easier to understand.
For this activity, focus on reading and tracing nested decisions.
Writing nested if structures independently is introduced in the next batch.
A nested if means: