Skip to content

C# - If Else

Conditional statements allow your program to execute different blocks of code based on a specified condition. The if-else statement is the most fundamental control flow structure for making decisions in C#.

The if statement executes a block of code only if its boolean condition evaluates to true.

int userAge = 20;
if (userAge >= 18)
{
Console.WriteLine("Access granted. You are an adult.");
}
// Output: Access granted. You are an adult.

You can add an else block to provide an alternative path of execution when the if condition is false.

if (boolean_expression)
{
// Executes if the expression is true
}
else
{
// Executes if the expression is false
}

The flow of control can be visualized as a fork in the road:

( Condition? )
/ \
true / \ false
/ \
(if block) (else block)
int temperature = 15;
if (temperature > 25)
{
Console.WriteLine("It's a hot day. Wear shorts!");
}
else
{
Console.WriteLine("It's cool outside. Consider a jacket.");
}
// Output: It's cool outside. Consider a jacket.

To test multiple conditions in sequence, you can chain else if statements. As soon as one condition is met, its block is executed, and the rest of the chain is skipped.

int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B"); // This block will be executed
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
// Output: Grade: B

Modern C# Alternatives for Conditional Logic

Section titled “Modern C# Alternatives for Conditional Logic”

For simple if-else assignments, the ternary operator provides a highly concise syntax. It is an expression that returns a value.

int userAge = 20;
// Syntax: condition ? value_if_true : value_if_false;
string status = (userAge >= 18) ? "Adult" : "Minor";
Console.WriteLine($"User status: {status}"); // Output: User status: Adult

For complex if-else if chains that evaluate a single variable, a switch expression is often more readable and less error-prone.

int statusCode = 404;
string message = statusCode switch
{
200 => "OK",
401 => "Unauthorized",
404 => "Not Found",
500 => "Internal Server Error",
_ => "Unknown Status Code" // The discard '_' acts as the default case
};
Console.WriteLine($"Response: {message}"); // Output: Response: Not Found
  • Use Braces {}: Always use curly braces for if and else blocks, even for a single-line statement. This prevents bugs when adding more lines later.
  • Avoid Deep Nesting: Deeply nested if statements (arrow code) are hard to read. Refactor them using methods, switch statements, or guard clauses.
  • Guard Clauses: Start a method by checking for invalid conditions and exiting early. This flattens your logic.
  • Short-Circuiting: Be aware that the logical AND (&&) and OR (||) operators are “short-circuiting.” In A && B, B is not evaluated if A is false. This is useful for preventing errors, e.g., if (user != null && user.IsAdmin).
  • Common Error: Using the assignment operator (=) instead of the equality operator (==) in a condition. C# helps prevent this by requiring a bool in the if condition, but it’s a classic bug to watch for.