DEV Community

Cover image for C# Language Trick – Pattern Matching
hamza zeryouh
hamza zeryouh

Posted on

C# Language Trick – Pattern Matching

🔥 This C# 9+ feature can replace multiple if statements

Instead of:

if (shape is Circle c) { /* ... */ } else if (shape is Rectangle r) { /* ... */ } else if (shape is Triangle t) { /* ... */ } 
Enter fullscreen mode Exit fullscreen mode

Do this:

var area = shape switch { Circle c => Math.PI * c.Radius * c.Radius, Rectangle r => r.Width * r.Height, Triangle t => t.Base * t.Height / 2, _ => throw new ArgumentException("Unknown shape") }; 
Enter fullscreen mode Exit fullscreen mode

Benefits:

More readable
Safer (compiler checks exhaustiveness)
Easier to maintain

What’s your favorite modern C# feature?

Top comments (0)