Complete C# Tutorial

C# Switch Expression – A Shorter, Cleaner Way!

Hey there, C# learner! πŸ‘‹ Ever felt frustrated writing long switch statements with all those case and break keywords? 😡 Traditional switch cases work fine, but they take up too much space and look repetitive.

Good news! C# 8.0 introduced the switch Expression – a shorter and cleaner way to write switch cases. πŸŽ‰ No more endless break statements!

Why Use Switch Expression? πŸ€”

  1. Less code, more readability – No need for case and break.
  2. Faster execution – It’s optimized for better performance.
  3. More fun to write! – Who doesn’t love cleaner code? 😎

Syntax of Switch Expression in C#

Alright, buddy! Before we jump into more examples, let’s crack the syntax of the switch Expression in C#. Don’t worryβ€”it’s super simple! 😎

Here’s what it looks like:

				
					variable = input switch
{
    case1 => result1,
    case2 => result2,
    case3 => result3,
    _ => defaultResult // Default case (optional)
};
				
			

Breaking it Down Like a Pro πŸ”

  1. No case or break needed – Just write caseValue => result.
  2. Each case is separated by a comma (,) – No {} or : needed!
  3. The _ (underscore) means “default case” – It handles all unmatched cases.

Now, let’s turn this into a real-life example!

Example: Convert Numbers to Words

				
					int number = 3;

string word = number switch
{
    1 => "One",
    2 => "Two",
    3 => "Three",
    _ => "Unknown"
};

Console.WriteLine(word);
				
			

Output (if number = 3):

				
					Three
				
			

Pretty cool, right? πŸ˜ƒ No case, no break, just clean code!

Why is Switch Expression Better?

βœ… Less typing – Saves time and effort!
βœ… Easier to read – No case blocks cluttering your code.
βœ… No missing break errors – One less thing to worry about!

Now that you know the syntax, go ahead and try it in your own programs! πŸš€

Real-World Example: Order Processing System

Imagine you are building an e-commerce website. Users order different items, and each item has a delivery time:

  • Electronics take 7 days πŸ“±
  • Clothing takes 3 days πŸ‘•
  • Books take 2 days πŸ“š
  • Other items take 5 days πŸ“¦

Instead of writing a long switch statement, let’s simplify it with a switch Expression in C#!

C# Switch Expression Example πŸ“Œ

				
					using System;

class Program
{
    static void Main()
    {
        string itemCategory = "Electronics"; // Try changing this to "Books" or "Clothing"

        int deliveryDays = itemCategory switch
        {
            "Electronics" => 7,
            "Clothing" => 3,
            "Books" => 2,
            _ => 5 // Default case for other items
        };

        Console.WriteLine($"Your {itemCategory} will be delivered in {deliveryDays} days.");
    }
}
				
			

Output (if itemCategory = "Electronics"):

				
					Your Electronics will be delivered in 7 days.
				
			

How Does This Code Work? 🧐

  1. The user selects an item category (e.g., "Electronics").
  2. The switch Expression checks the category and returns the delivery time.
  3. No need for case, break, or return. Just clean, simple code!
  4. If the category doesn’t match, the default case (_) returns 5 days.

See how much cleaner this is compared to a traditional switch? πŸš€

Conclusion 🎯

The switch Expression in C# is a game-changer for writing short, clean, and readable code. Instead of using traditional switch statements, you can save time and avoid unnecessary lines of code.

Next time you write a switch case, ask yourself: Can I use a switch Expression instead? If yes, go for it! 😎

Next What? πŸš€

You’re doing great! πŸ”₯ But there’s more awesomeness ahead.

In the next lesson, we’ll explore Pattern Matching – a powerful way to make your switch statements even smarter! 🧠

πŸ‘‰ Excited? Let’s dive into Pattern Matching next! πŸš€

Leave a Comment

Share this Doc

Switch Expression (C# 8.0+)

Or copy link