Decisions with if / else
Make your program choose: if, else, else if, nested conditions, the ternary operator and common traps.
if statement runs code only when a condition is true.
int temperature = 38; if (temperature > 35){ Console.WriteLine("It's hot. Drink water!");}Console.WriteLine("Done");It's hot. Drink water! Done
if / else: one of two paths
int age = 16; if (age >= 18){ Console.WriteLine("You can vote.");}else{ Console.WriteLine($"Wait {18 - age} more years.");}Wait 2 more years.
else if: many paths, first match wins
else if. C# checks them in order and runs only the first branch whose condition is true; the rest are skipped. Drag the slider and watch:
Combining conditions
int age = 25;bool hasLicence = true; if (age >= 18 && hasLicence) Console.WriteLine("You may drive."); string day = "Sunday";if (day == "Saturday" || day == "Sunday") Console.WriteLine("Weekend!");You may drive. Weekend!
Nested if
bool loggedIn = true;bool isAdmin = false; if (loggedIn){ if (isAdmin) Console.WriteLine("Admin dashboard"); else Console.WriteLine("User dashboard");}else{ Console.WriteLine("Please log in");}User dashboard
The ternary operator ? :
condition ? valueIfTrue : valueIfFalse is shorter than a full if/else.
int stock = 0;string label = stock > 0 ? "In stock" : "Sold out";Console.WriteLine(label);Sold out
Common mistakes
if (x = 5): assignment, not comparison. Use==. (C# reports an error here.)if (x > 5);with a semicolon: theifcontrols an empty statement, and the block below always runs.Comparing decimals with ==:0.1 + 0.2 == 0.3isfalsefordouble. Compare with a tolerance or usedecimal.
Show a hint
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
Show the solution
Console.Write("Year: ");if (int.TryParse(Console.ReadLine(), out int year)){ bool leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; Console.WriteLine(leap ? $"{year} is a leap year" : $"{year} is not a leap year");}else{ Console.WriteLine("Invalid year");}Year: 2024 2024 is a leap year
Remember
ifruns a block only when its condition istrue;elsehandles the rest.In an else ifchain only the first true branch runs, so order matters.Combine conditions with &&,||,!.Use cond ? a : bto choose between two values.