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:
if to specify a block of code to be executed if a condition is true.else to specify a block of code to be executed if the same condition is false.else if to specify a new condition to test, if the first condition is false.if StatementUse 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 }
else StatementUse 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 }
else if StatementIf you have multiple conditions, use else if to chain them together.
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."); } } }
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;
Which statement executes if the initial condition is false?