Operators

    Lesson 3 โ€ข Beginner Track

    What You'll Learn

    • Use arithmetic operators (+, -, *, /, %) and understand integer division
    • Apply increment (++), decrement (--), and compound assignment (+=, *=)
    • Compare values with ==, !=, >, <, >=, <= and understand what they return
    • Combine conditions with logical operators (&&, ||, !)
    • Use the ternary operator for concise conditional expressions
    • Handle null values safely with ??, ??=, and ?. operators

    ๐Ÿ’ก Real-World Analogy

    Operators are like the buttons on a calculator. Arithmetic operators (+, -, ร—, รท) do maths. Comparison operators are like a referee making yes/no decisions โ€” "Is player A's score higher than player B's?" Logical operators are like combining conditions on a checklist: "Do you have BOTH a passport AND a visa?" (&&) or "Do you have EITHER cash OR a card?" (||).

    ๐Ÿ“Š Operator Precedence

    PriorityOperatorsExample
    1 (Highest)() ?. !Parentheses, null-conditional, not
    2* / %Multiply, divide, remainder
    3+ -Add, subtract
    4< > <= >=Comparison
    5== !=Equality
    6&&Logical AND
    7||Logical OR
    8 (Lowest)= += -= *= ??=Assignment

    1. Arithmetic Operators

    Arithmetic operators perform mathematical calculations. Watch out for integer division โ€” 10 / 3 gives 3, not 3.33. Use ++ and -- for incrementing/decrementing, and compound operators like += for concise updates.

    Arithmetic Operators

    Explore arithmetic, increment/decrement, and compound assignment.

    Try it Yourself ยป
    C#
    using System;
    
    class Program
    {
        static void Main()
        {
            int a = 10, b = 3;
    
            // Basic arithmetic
            Console.WriteLine($"a + b = {a + b}");   // 13
            Console.WriteLine($"a - b = {a - b}");   // 7
            Console.WriteLine($"a * b = {a * b}");   // 30
            Console.WriteLine($"a / b = {a / b}");   // 3 (integer division!)
            Console.WriteLine($"a % b = {a % b}");   // 1 (remainder)
    
            // Increment & decrement
            int x = 5;
            Console.WriteLine($
    ...

    2. Comparison & Logical Operators

    Comparison operators return bool (true/false). Logical operators combine multiple conditions: && requires both to be true, || requires at least one, and ! flips the result. These are the foundation of control flow.

    Comparison & Logical Operators

    Compare values and combine conditions with &&, ||, and !.

    Try it Yourself ยป
    C#
    using System;
    
    class Program
    {
        static void Main()
        {
            // Comparison operators
            int age = 20;
            Console.WriteLine($"age == 20: {age == 20}");  // true
            Console.WriteLine($"age != 18: {age != 18}");  // true
            Console.WriteLine($"age > 18:  {age > 18}");   // true
            Console.WriteLine($"age <= 21: {age <= 21}");   // true
    
            // Logical operators
            bool hasTicket = true;
            bool isVIP = false;
    
            // AND โ€” both must be true
            
    ...

    3. Ternary & Null-Safe Operators

    The ternary operator (condition ? a : b) is a one-line if-else. C# also has powerful null-safe operators: ?? provides a fallback for null values, ??= assigns only if null, and ?. safely accesses members without crashing on null.

    Ternary & Null Operators

    Use ternary expressions and handle null values safely.

    Try it Yourself ยป
    C#
    using System;
    
    class Program
    {
        static void Main()
        {
            // Null-coalescing operator (??)
            string? userName = null;
            string displayName = userName ?? "Guest";
            Console.WriteLine($"Welcome, {displayName}!");  // "Guest"
    
            userName = "Alice";
            displayName = userName ?? "Guest";
            Console.WriteLine($"Welcome, {displayName}!");  // "Alice"
    
            // Null-coalescing assignment (??=)
            string? city = null;
            city ??= "London";  // Assig
    ...

    Pro Tips

    • ๐Ÿ’ก Use parentheses for clarity: Even if precedence is correct, (a > 5) && (b < 10) is clearer than a > 5 && b < 10.
    • ๐Ÿ’ก Prefer ?? over if-null checks: string name = input ?? "default"; is cleaner than a 4-line if-else.
    • ๐Ÿ’ก Short-circuit evaluation: && and || stop evaluating as soon as the result is known. Put cheaper checks first.
    • ๐Ÿ’ก Use ?. to avoid NullReferenceException: user?.Address?.City returns null safely instead of crashing.

    Common Mistakes

    • Using = instead of ==: if (x = 5) is assignment, not comparison. C# catches this for bools but be careful.
    • Integer division surprise: 7 / 2 gives 3. Cast one operand: (double)7 / 2 gives 3.5.
    • Confusing ++ placement: x++ returns the old value then increments. ++x increments first then returns the new value.
    • Ignoring null warnings: C# 8+ has nullable reference types. Don't suppress warnings with ! โ€” use ?? or ?. instead.
    • Chaining comparisons: 1 < x < 10 doesn't work like maths. Use x > 1 && x < 10.

    ๐ŸŽ‰ Lesson Complete

    • โœ… Arithmetic: +, -, *, /, % โ€” integer division truncates
    • โœ… Increment/decrement: x++ (post) vs ++x (pre) โ€” different return values
    • โœ… Comparison operators return bool: ==, !=, >, <, >=, <=
    • โœ… Logical: && (AND), || (OR), ! (NOT) โ€” short-circuit evaluation
    • โœ… Ternary: condition ? valueIfTrue : valueIfFalse
    • โœ… Null-safe: ?? (fallback), ??= (assign if null), ?. (safe access)
    • โœ… Next lesson: Control Flow โ€” if statements, switch, and pattern matching

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service