C# If Else

You often need your program to make decisions. C# uses if...else statements to run different blocks of code depending on whether a condition is true or false. This is how your programs react to data instead of always doing the same thing.

Conditions and Decisions

A condition is any expression that evaluates to a Boolean value, either true or false. C# gives you a set of conditional statements that let you branch your code based on these values. The most common one is the if statement.

  • Use if to run code only when a condition is true.
  • Use else to run code when that condition is false.
  • Use else if to test a new condition when the previous ones were false.
  • Use the ternary operator (?:) as a short way to choose between two values.

The if Statement

The if statement runs a block of code only when its condition is true. Notice the condition sits inside parentheses, and the code to run sits inside curly braces.

A simple if

int temperature = 30;

if (temperature > 25)
{
    Console.WriteLine("It is a warm day.");
}
Note: C# is case sensitive, so you must write if and else in lowercase. Writing If or ELSE will cause a compile error.

The else and else if Statements

Use else to define a block that runs when the if condition is false. Add else if between them to test extra conditions in order. C# checks each condition from top to bottom and runs the first block whose condition is true.

Grading with else if

int score = 72;

if (score >= 90)
{
    Console.WriteLine("Grade: A");
}
else if (score >= 60)
{
    Console.WriteLine("Grade: B");
}
else
{
    Console.WriteLine("Grade: F");
}

The Ternary Operator

When you only need to choose between two values, the ternary operator gives you a compact one-line version of if...else. It follows the pattern condition ? valueIfTrue : valueIfFalse.

Short if...else

int age = 20;
string result = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine(result);
// Output: Adult
StatementWhen it runs
ifThe block runs only if the condition is true.
else ifTested only if all earlier conditions were false.
elseRuns when no earlier condition was true.
?:Returns one of two values based on a condition.
Note: You can nest an if inside another if, but too much nesting is hard to read. Often an else if chain or a switch statement is clearer.

Exercise: C# If...Else

What type must the expression inside an if(...) condition evaluate to in C#?