0
0
C Sharp (C#)programming~3 mins

Why Switch expression (modern C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could replace long, messy decision code with a simple, elegant expression?

The Scenario

Imagine you have to decide what to do based on many different conditions, like choosing what to wear depending on the weather. Doing this by writing many if-else statements can get confusing and long.

The Problem

Using many if-else or old switch statements makes your code bulky and hard to read. It's easy to make mistakes or forget a case, and changing the logic later becomes a headache.

The Solution

The modern C# switch expression lets you write all these conditions in a clear, short, and neat way. It makes your code easier to read and less error-prone by handling all cases in one place.

Before vs After
Before
string result;
switch (weather) {
  case "sunny":
    result = "Wear sunglasses";
    break;
  case "rainy":
    result = "Take an umbrella";
    break;
  default:
    result = "Wear normal clothes";
    break;
}
After
var result = weather switch {
  "sunny" => "Wear sunglasses",
  "rainy" => "Take an umbrella",
  _ => "Wear normal clothes"
};
What It Enables

You can write clear, concise decision-making code that's easy to update and understand at a glance.

Real Life Example

Think about a weather app that shows advice based on the forecast. Using switch expressions, the app's code stays clean and easy to add new weather types.

Key Takeaways

Manual if-else chains are long and error-prone.

Switch expressions simplify complex decisions into neat, readable code.

They make your programs easier to maintain and extend.