Skip to main content

Nesting Conditions

An if statement can contain another if statement, this is known as nesting.

if (condition1)
{
if(condition2)
{
if(condition3)
{
// do stuff
}
}
}

When to Nest​

Deeply nested conditionals can make code harder to read, debug, and maintain.

Sometimes nesting is unavoidable, especially when a check only makes sense in the context of a previous one, but before reaching for another nested block, try simplifying it with:

  • Combined Conditions
  • Guard Clauses (covered later)
  • Extracted functions (covered later)

Combing Conditions​

Lets say you can only go hiking this fall if you have supplies AND it's warm enough:

bool hasSupplies = true;
double temp = 20.2;

if (hasSupplies)
{
if(temp > 5.0)
{
Console.WriteLine("Wow time to hike");
}
}

While the above is possible, nested conditions get harder to read and maintain as they grow. When each condition is simple, combine them with a logical operator (&&) instead comme ca:

bool hasSupplies = true;
double temp = 20.2;

if (hasSupplies && temp > 5.0)
{
Console.WriteLine("Wow time to hike");
}

This keeps the logic easier to scan at a short glance.