Start learning free

LESSON 74 OF 347 · CONDITIONAL STATEMENTS

Reducing If-Else to a Boolean Expression in C#

Practice Read the full explanation

We will learn a simple trick to improve our code quality: Reducing If-Else to Boolean Expressions.

Video Lesson:

STEP 1 OF 1
    Ctrl + Enter to check

    C# · CONDITIONAL STATEMENTS

    Reducing If Else To Boolean Expression in C#, explained

    Problem overview

    You write a method LegalAge that takes an integer age and returns a bool: true when the age is 18 or more, and false otherwise. The lesson is about code quality: the right solution is a single line, with no if at all.

    The long way

    A first attempt often looks like this:

    public bool LegalAge(int age) {
        if (age >= 18) {
            return true;
        } else {
            return false;
        }
    }
    

    It is correct, but it has a pattern that is worth recognising: the code tests a condition and then returns true if the condition is true, false if it is false. In other words, the answer is the condition itself.

    Approach

    A comparison such as age >= 18 is an expression whose value is a bool. It is true for 18 and above, and false below that. Since the method has to return exactly that value, return the expression directly. No if and no else are needed.

    This works for any condition, not just comparisons. If the condition were a && b, you could return that too. The shortcut applies whenever the branches return the literal true and false.

    Other shapes collapse the same way. All of these are equivalent to the one-line version:

    if (age >= 18) return true;
    return false;
    
    return age >= 18 ? true : false;
    

    In each case the code is spelling out the value that the comparison already has. Long forms are not wrong, but they take longer to read and leave more room for a slip, such as returning true in both branches.

    Step by step

    1. Look at what the method must return. It returns bool, and the answer is "is the age at least 18?".
    2. Write that question as an expression. age >= 18.
    3. Return it. Put return in front of the expression. This replaces the whole if-else.

    The solution in C#

    class Solution {
        public bool LegalAge(int age) {
            return age >= 18;
        }
    }
    

    C# details

    • The type is bool, in lowercase; it is an alias for System.Boolean. Its values are the lowercase keywords true and false.
    • The comparison is evaluated before return sends the result back, so there are no parentheses to add.
    • Printing a bool with Console.WriteLine shows True or False with a capital first letter, which differs from the source keywords. The method itself returns the real boolean value, not text.

    Because the result is a bool, the caller can use it straight away. For example, if (LegalAge(20)) { ... } works the same as it would with the long version, and so does bool ok = LegalAge(20);.

    When to keep the if

    If the branches do something more than return the literals true and false, you need the if. A branch that prints, logs a message or returns a different value is doing real work, and the expression shortcut would drop it. The reduction is only for the case where the if restates a value the condition already holds. Spotting that case quickly is a useful habit when you read other people's code too.

    Edge cases and common mistakes

    • The boundary. Age 18 is legal, so the operator must be >=. With >, an 18-year-old would be rejected. LegalAge(18) is true, LegalAge(17) is false.
    • Comparing to true. Writing if (x == true) or return (age >= 18) == true; is noise. A bool is already a condition.
    • Inverting by accident. When you shorten an if-else that returns false first, the expression has to be the opposite of the condition. For example, if (age < 18) return false; return true; becomes return age >= 18;, not return age < 18;.
    • Wrapping in a ternary. return age >= 18 ? true : false; works but says nothing extra.

    Testing

    • LegalAge(18) returns true.
    • LegalAge(17) returns false.
    • LegalAge(0) returns false.
    • LegalAge(40) returns true.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free