C# Control Statements | if-else and switch-case with Pattern Matching

C# Control Statements | if-else and switch-case with Pattern Matching

🔁 C# Control Statements: if-else and switch-case

Control statements in C# allow your program to make decisions and execute specific blocks of code based on conditions. The two most commonly used control statements are if-else and switch-case.

✅ if-else Statement

Use if to test a condition. If it's true, the code block runs. You can add else to execute alternative code when the condition is false.

🧠 switch-case with Pattern Matching

The switch statement lets you compare a variable against many patterns. Modern C# (from version 8.0 onwards) supports pattern matching inside switch, making your conditions more expressive.

💡 Example: if-else and switch-case


using System;

class Program {
    static void Main() {
        int number = 15;

        // if-else example
        if (number < 10) {
            Console.WriteLine("Less than 10");
        } else if (number >= 10 && number <= 20) {
            Console.WriteLine("Between 10 and 20");
        } else {
            Console.WriteLine("Greater than 20");
        }

        // switch-case with pattern matching
        object value = number;
        switch (value) {
            case int n when n < 10:
                Console.WriteLine("Small integer");
                break;
            case int n when n >= 10 && n <= 20:
                Console.WriteLine("Medium integer");
                break;
            case int n:
                Console.WriteLine("Large integer");
                break;
            default:
                Console.WriteLine("Unknown type");
                break;
        }
    }
}
    

📤 Sample Output

Between 10 and 20
Medium integer

🔍 Summary

  • if-else handles simple conditional logic.
  • switch-case supports multiple values and modern pattern matching for complex logic.
  • Pattern matching adds clarity when working with types and conditions.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences