int orderTotal = 450;
if (orderTotal >= 500) {
Console.WriteLine("Free delivery");
} else {
Console.WriteLine("Delivery fee: โน40");
}
One-Liner: Ternary
string result = score >= 40? "Pass" : "Fail";
Nested If + Else If Ladder
int age = 20;
bool hasID = true;
if (age >= 18) {
if (hasID) {
Console.WriteLine("Entry allowed");
} else {
Console.WriteLine("ID required");
}
} else if (age >= 16) {
Console.WriteLine("Entry with guardian");
} else {
Console.WriteLine("Not allowed");
}
Switch: Cleaner Than 10 If-Else
string role = "admin";
switch (role) {
case "admin":
Console.WriteLine("Full access");
break;
case "editor":
Console.WriteLine("Can edit");
break;
case "user":
case "guest": // Fall-through: both run same code
Console.WriteLine("Read only");
break;
default:
Console.WriteLine("Unknown role");
break;
}
Pattern Matching Switch - C# 8+
int marks = 85;
string grade = marks switch {
>= 90 => "A",
>= 75 => "B",
>= 60 => "C",
_ => "Fail" // _ is default
};
Gotcha #1:if(age = 18) assigns 18. Use == to compare Gotcha #2: Missing break in switch causes fall-through bug Gotcha #3:if(x > 5 && x < 10) โ if(5 < x < 10). Second one doesn't work in C#.
Quick Check ๐ง
EasyQ1: What does age >= 18 check?
MediumQ1: What prints? int x=5; if(x=10) Console.Write("Yes");
HardQ2: Switch without break. What prints? case 1: Console.Write("A"); case 2: Console.Write("B"); break;
No comments yet. Be the first to share your thoughts!