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) { /* … */ }

Do this:

var area = shape switch
{
Circl…


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » C# Language Trick – Pattern Matching." hamza zeryouh | Sciencx - Saturday August 9, 2025, https://www.scien.cx/2025/08/09/c-language-trick-pattern-matching/
HARVARD
hamza zeryouh | Sciencx Saturday August 9, 2025 » C# Language Trick – Pattern Matching., viewed ,<https://www.scien.cx/2025/08/09/c-language-trick-pattern-matching/>
VANCOUVER
hamza zeryouh | Sciencx - » C# Language Trick – Pattern Matching. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/08/09/c-language-trick-pattern-matching/
CHICAGO
" » C# Language Trick – Pattern Matching." hamza zeryouh | Sciencx - Accessed . https://www.scien.cx/2025/08/09/c-language-trick-pattern-matching/
IEEE
" » C# Language Trick – Pattern Matching." hamza zeryouh | Sciencx [Online]. Available: https://www.scien.cx/2025/08/09/c-language-trick-pattern-matching/. [Accessed: ]
rf:citation
» C# Language Trick – Pattern Matching | hamza zeryouh | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.