This content originally appeared on DEV Community and was authored by hamza zeryouh
🔥 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) { /* ... */ }
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")
};
Benefits:
More readable
Safer (compiler checks exhaustiveness)
Easier to maintain
What’s your favorite modern C# feature?
This content originally appeared on DEV Community and was authored by hamza zeryouh

hamza zeryouh | Sciencx (2025-08-09T12:39:02+00:00) C# Language Trick – Pattern Matching. Retrieved from https://www.scien.cx/2025/08/09/c-language-trick-pattern-matching/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.