C# If...Else

C# If...Else Statements

Conditional statements allow you to write code that only executes when specific conditions are met. This is how programs make "decisions."

C# uses the following conditional statements:


1. The if Statement

Use the if statement to specify a block of C# code to be executed if a condition evaluates to true.

if (20 > 18) {
  Console.WriteLine("20 is greater than 18"); // This will run
}

2. The else Statement

Use the else statement to catch anything that was false in the if statement.

int time = 20;
if (time < 18) {
  Console.WriteLine("Good day.");
} else {
  Console.WriteLine("Good evening."); // This will run
}

3. The else if Statement

If you have multiple conditions, use else if to chain them together.

Else If Example

using System;

class Program { static void Main() { int time = 22; if (time < 10) { Console.WriteLine("Good morning."); } else if (time < 20) { Console.WriteLine("Good day."); } else { Console.WriteLine("Good evening."); } } }


Short Hand If...Else (Ternary Operator)

There is a shorthand version of if...else, which is known as the ternary operator because it consists of three operands. It is used to replace simple if...else statements with a single line of code!

Syntax: variable = (condition) ? expressionTrue : expressionFalse;

Exercise

?

Which statement executes if the initial condition is false?