Conditional Statements
if, else if, and else branch execution based on boolean conditions.
Introduction
if, else if, and else branch execution based on boolean conditions. They gate business rules — credit approval, dosage checks, role authorization — and appear in every codebase alongside guard clauses that fail fast.
C# treats bool strictly — no implicit conversion from int like C/C++. You can use ternary ? : for simple assignments and pattern matching in conditions for type checks. Nested if-chains hurt readability; early returns and switch expressions often clarify intent.
Interviewers ask about dangling else, assignment vs comparison bugs, and refactoring complex condition trees into policy objects or strategy pattern.
The story
A hospital triage system receives vital signs from an emergency room monitor: heart rate, blood pressure, and whether the patient reports chest pain. Nurses need software that instantly classifies each case as Routine, Urgent, or Critical so the right team responds first.
if / else chains encode those medical thresholds — guard clauses reject impossible readings before any severity logic runs.
Understanding the topic
Key concepts
- if (condition) executes block when condition is true.
- else if chains multiple mutually exclusive branches.
- Ternary: condition ? whenTrue : whenFalse — use for simple expressions only.
- Boolean expressions must be bool — no truthy/falsy integers.
- Guard clauses return early on invalid state reducing nesting.
- Pattern matching in if (x is Type t) combines check and bind.
flowchart TDStart([Condition]) --> Check{if true?}Check -->|yes| TrueBlock[Execute Block]Check -->|no| FalseBlock[Else Block]TrueBlock --> Merge[Continue]FalseBlock --> Merge
Step-by-step explanation
- Evaluate condition expression to bool.
- Enter first true branch; skip remaining else if/else.
- Blocks use { } for multiple statements; single statement allowed without braces (discouraged).
- Scope: variables declared inside block not visible outside.
- Conditional operator evaluates only chosen branch (short-circuit).
- Combine with logical operators for compound business rules.
Practical code example
Healthcare triage priority with guard clauses and pattern matching:
namespace TechLearningPro.Conditionals;public enum TriageLevel { Routine, Urgent, Critical }public static class TriageEvaluator{public static TriageLevel Evaluate(int heartRate, int systolicBp, bool chestPain){if (heartRate <= 0 || systolicBp <= 0)throw new ArgumentOutOfRangeException("Vitals must be positive.");if (chestPain || systolicBp >= 180 || heartRate >= 130)return TriageLevel.Critical;if (systolicBp >= 140 || heartRate >= 100)return TriageLevel.Urgent;return TriageLevel.Routine;}}
Line-by-line code explanation
public enum TriageLeveldefines the three possible outcomes as named constants.Evaluate(int heartRate, int systolicBp, bool chestPain)accepts the raw vital signs as parameters.if (heartRate <= 0 || systolicBp <= 0)is a guard clause rejecting invalid measurements.throw new ArgumentOutOfRangeException(...)stops processing when input is nonsensical.if (chestPain || systolicBp >= 180 || heartRate >= 130)checks critical thresholds first — most severe cases exit early.return TriageLevel.Criticalassigns the highest priority without nesting deeper.if (systolicBp >= 140 || heartRate >= 100)catches urgent but non-critical cases.return TriageLevel.Urgentroutes the patient to faster review.return TriageLevel.Routineis the default when no alert thresholds fire.
Key takeaway: Guard clause validates input first. Flat structure beats deep nesting — interviewers reward readability.
Real-world use
Where you'll use this in production
- Loan approval engines with cascading eligibility checks.
- RBAC authorization before controller actions.
- Medical alert thresholds triggering notifications.
- Feature flags gating experimental UI paths.
Best practices
- Prefer guard clauses over deep nesting.
- Extract complex conditions to named bool methods.
- Always use braces — avoid Apple goto fail bugs.
- Use switch expression when mapping discrete outcomes.
- Unit test each branch including boundary values.
Common mistakes
- if (x = 5) assignment instead of comparison — compile error in C#.
- Omitting else leaving variables uninitialized on some paths.
- Duplicated condition logic across methods.
- Mega-methods with 10+ nested if blocks.
Advanced interview questions
Q1BeginnerDifference between if and switch?
Q2BeginnerWhat is a guard clause?
Q3IntermediateWhen avoid ternary operator?
Q4IntermediateRefactor nested ifs in legacy code?
Q5AdvancedModel complex insurance underwriting rules maintainably.
Summary
if/else control flow based on boolean conditions. Guard clauses and named predicates improve readability. C# requires explicit bool — no implicit truthiness. Combine with pattern matching for type-aware branches. Next: modern switch expressions and patterns.