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

Why Switch expressions with patterns in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could replace long, messy if-else chains with a neat, powerful one-liner that understands your data?

The Scenario

Imagine you have a list of different shapes, and you want to find their areas. Without patterns, you write many if-else statements checking each shape type and calculating the area separately.

The Problem

This manual way is long, hard to read, and easy to make mistakes. Adding new shapes means adding more if-else blocks, making the code messy and confusing.

The Solution

Switch expressions with patterns let you match shapes by type and properties in a clean, concise way. You write all cases in one place, making the code easier to read and extend.

Before vs After
Before
if (shape is Circle) { area = Math.PI * ((Circle)shape).Radius * ((Circle)shape).Radius; } else if (shape is Rectangle) { area = ((Rectangle)shape).Width * ((Rectangle)shape).Height; } else { area = 0; }
After
area = shape switch { Circle c => Math.PI * c.Radius * c.Radius, Rectangle r => r.Width * r.Height, _ => 0 };
What It Enables

You can write clearer, shorter code that handles many cases smoothly and is easy to update.

Real Life Example

In a drawing app, you can quickly calculate areas or colors of different shapes using switch expressions with patterns, making the app faster to develop and maintain.

Key Takeaways

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

Switch expressions with patterns simplify matching by type and properties.

Code becomes cleaner, easier to read, and extend.