C# Programming Tutorial 0/45 lessons ~6 min read Lesson 7

    Conditional Statements

    if, else if, and else branch execution based on boolean conditions.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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.
    text
    flowchart TD
    Start([Condition]) --> Check{if true?}
    Check -->|yes| TrueBlock[Execute Block]
    Check -->|no| FalseBlock[Else Block]
    TrueBlock --> Merge[Continue]
    FalseBlock --> Merge

    Step-by-step explanation

    1. Evaluate condition expression to bool.
    2. Enter first true branch; skip remaining else if/else.
    3. Blocks use { } for multiple statements; single statement allowed without braces (discouraged).
    4. Scope: variables declared inside block not visible outside.
    5. Conditional operator evaluates only chosen branch (short-circuit).
    6. Combine with logical operators for compound business rules.

    Practical code example

    Healthcare triage priority with guard clauses and pattern matching:

    csharp
    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 TriageLevel defines 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.Critical assigns the highest priority without nesting deeper.
    • if (systolicBp >= 140 || heartRate >= 100) catches urgent but non-critical cases.
    • return TriageLevel.Urgent routes the patient to faster review.
    • return TriageLevel.Routine is 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?
    if handles arbitrary boolean expressions; switch best for discrete value matching with patterns.
    Q2BeginnerWhat is a guard clause?
    Early return/throw when preconditions fail, avoiding else nesting.
    Q3IntermediateWhen avoid ternary operator?
    Nested ternaries or side effects — use if for clarity.
    Q4IntermediateRefactor nested ifs in legacy code?
    Extract methods, use polymorphism/strategy, switch expressions, or rule engine.
    Q5AdvancedModel complex insurance underwriting rules maintainably.
    Policy specification pattern: composable rules returning Result; unit test each rule; data-driven config for thresholds.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.