Conditionals
Making Choices in Code
Life is full of decisions. "If it's raining, take an umbrella. Otherwise, wear sunglasses." Your code needs to make decisions too, and that's exactly what conditionals do.
The if statement is the most basic decision-maker. It checks a condition (something that's either true or false) and runs a block of code only when the condition is true. This branching logic is at the heart of algorithms like binary search. You can chain decisions together with else if and provide a fallback with else.
if / else if / else
Switch — The Cleaner Multi-Choice
When you're comparing one value against many options, switch is cleaner than a tower of if/else if blocks. Think of it like a vending machine — you press a button (the value), and it matches to the right slot.
Modern C# has switch expressions (introduced in C# 8) that are even more compact. And with pattern matching, switch becomes incredibly powerful — you can match types, ranges, and even combine conditions.