C# Tip: Pattern Matching

Learn about C# 8/9 pattern matching and switch expressions to replace ifs, improve readability and exhaustiveness. Custom solutions in AI, cybersecurity, and cloud with Q2BSTUDIO.

domingo, 17 de agosto de 2025 • 1 min read • Q2BSTUDIO Team

Artificial-Intelligence-

C# Language Pattern Matching Tip: replace multiple if statements with the C# 9 and later switch expression

Instead of using multiple checks with is and else if like

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

use the switch expression with pattern matching for greater clarity and safety

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() };

Benefits: more readable, the compiler can verify exhaustiveness, easier to maintain

More details: the C# 8 and C# 9 syntax has improved pattern matching by allowing switch expressions, property matching, and relational patterns, which reduces errors and makes the code more declarative

At Q2BSTUDIO we are a custom software and application development company, specialists in artificial intelligence, cybersecurity, and aws and azure cloud services. We offer custom software, business intelligence services, power bi implementations, AI solutions for companies, and custom AI agents.

If you need to migrate legacy code, optimize logic with pattern matching, or develop custom applications with integrated artificial intelligence and cybersecurity, at Q2BSTUDIO we can help you with cloud architecture, data services, and automation.

Keywords for positioning: custom applications, custom software, artificial intelligence, cybersecurity, aws and azure cloud services, business intelligence services, AI for companies, AI agents, power bi

What is your favorite feature of modern C# or what do you need to solve in your project?

OUR SERVICES

How we can help you

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.