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

    Operators

    Operators transform values: arithmetic for calculations, comparison for branching, logical for compound conditions, and assignment for state updates.

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

    Introduction

    Operators transform values: arithmetic for calculations, comparison for branching, logical for compound conditions, and assignment for state updates. C# also provides null-coalescing (??), null-conditional (?.), and pattern-matching operators that replace verbose null checks.

    Interviewers probe operator precedence, short-circuit evaluation of && and ||, and the difference between == and ReferenceEquals. Misusing + for string building in hot paths or assigning with = inside conditions are classic junior mistakes.

    This lesson maps every operator category with banking and validation examples you will reuse through LINQ and ASP.NET Core model binding.

    The story

    An e-commerce checkout page calculates tax, applies a promo code like SAVE10, and masks the customer's card number on the receipt. The payment service must combine arithmetic, null-safe defaults, and string slicing without crashing when optional fields are missing.

    Operators and expressions are the glue between user input and the final charge amount shown on the confirmation screen.

    Understanding the topic

    Key concepts

    • Arithmetic: + - * / % — integer division truncates; use cast or decimal for precision.
    • Comparison: == != < > <= >= — structs may override Equals; classes default to reference equality.
    • Logical: && || ! short-circuit; & | for bitwise; ^ XOR.
    • Assignment: = += -= ?? ??= — null-coalescing assignment (C# 8+).
    • Null-conditional ?. and ?[] safely navigate null references.
    • is / is not pattern matching replaces type checks and casts.
    text
    flowchart LR
    A[Operands] --> Arith[+ - * /]
    A --> Compare[== != < >]
    A --> Logical[&& || !]
    Arith --> Result[Expression Result]

    Step-by-step explanation

    1. Expressions evaluate left-to-right respecting precedence (multiplication before addition).
    2. Short-circuit: && skips right if left false; || skips if left true.
    3. ?? returns right operand when left is null.
    4. ?. returns null if receiver null instead of throwing.
    5. Compound assignment x += 1 reads and writes x atomically for primitives.
    6. Operator overloading allows custom types to use +, == with syntax sugar.

    Practical code example

    Null-coalescing, conditional access, and pattern matching in a payment validation helper:

    csharp
    namespace TechLearningPro.Operators;
    public static class PaymentValidator
    {
    public static decimal CalculateTotal(decimal? amount, decimal taxRate, string? promoCode)
    {
    decimal baseAmount = amount ?? throw new ArgumentNullException(nameof(amount));
    decimal tax = baseAmount * taxRate;
    decimal discount = promoCode switch
    {
    "SAVE10" => baseAmount * 0.10m,
    "SAVE20" => baseAmount * 0.20m,
    null or "" => 0m,
    _ => 0m
    };
    return baseAmount + tax - discount;
    }
    public static string FormatCardLast4(string? cardToken) =>
    cardToken?.Length >= 4 ?
    quot;****{cardToken[^4..]}" : "N/A";
    }

    Line-by-line code explanation

    • decimal? amount allows null when the cart total has not been computed yet.
    • amount ?? throw new ArgumentNullException(...) uses the null-coalescing operator to fail fast on missing data.
    • decimal tax = baseAmount * taxRate applies standard arithmetic with decimal precision.
    • promoCode switch { ... } is a switch expression that maps codes to discount amounts.
    • "SAVE10" => baseAmount * 0.10m calculates a ten-percent discount for a known promo.
    • null or "" => 0m handles empty promo codes without throwing.
    • _ => 0m is the discard arm for unrecognized codes — safe default behavior.
    • return baseAmount + tax - discount combines subtotal, tax, and discount into the final total.
    • cardToken?.Length >= 4 uses null-conditional access before reading the token length.
    • cardToken[^4..] takes the last four characters with the index-from-end range operator.

    Key takeaway: Throw expression on ?? catches missing amounts early. Range operator [^4..] takes last four chars — C# 8+ index from end.

    Real-world use

    Where you'll use this in production

    • Pricing engines combining discounts with null-safe promo codes.
    • Healthcare eligibility rules with chained && conditions.
    • API query filters building dynamic LINQ with null-coalesced defaults.
    • Bitwise flags for feature toggles in enterprise licensing.

    Best practices

    • Use ?? and ?. instead of nested if-null checks.
    • Parenthesize complex conditions for readability.
    • Never assign in condition unless intentional (while ((x = Read()) != null)).
    • Override Equals/GetHashCode together when comparing custom types.
    • Use switch expressions for mapping discrete values.

    Common mistakes

    • Using & instead of && — no short-circuit, NullReferenceException risk.
    • Integer division 5/2 equals 2 — need 5/2.0 or 5m/2m.
    • Comparing strings with == without understanding interning vs ordinal.
    • Overusing ++ in expressions harming readability.

    Advanced interview questions

    Q1BeginnerWhat is short-circuit evaluation?
    && and || skip evaluating right operand when result is determined.
    Q2BeginnerDifference between == and Equals?
    == uses operator overload; Equals is virtual method; ReferenceEquals checks identity.
    Q3IntermediateExplain ?? vs ?.
    ?? provides default when null; ?. stops member access chain when receiver null.
    Q4IntermediateWhen overload operators?
    When type behaves like primitive (Money, Vector) — sparingly, with clear semantics.
    Q5AdvancedHow does pattern matching with is improve on traditional casts?
    Combines type test, cast, and binding in one expression with exhaustiveness checking in switch.

    Summary

    C# operators cover arithmetic, logic, assignment, and null-safety. Short-circuit and precedence affect both correctness and performance. ?? ?. and switch expressions replace boilerplate null and branch code. Use decimal operators for financial math. Next: Console I/O and formatting user-facing output.

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