


How does pattern matching in C# (e.g., is expressions, switch expressions) simplify conditional logic?
Jun 14, 2025 am 12:27 AMPattern matching in C# makes the conditional logic more concise and expressive through is expressions and switch expressions. 1. Use is expressions to perform concise type checks, such as if (obj is string s), and extract values ??at the same time; 2. It can simplify conditional judgments in combination with logical patterns (and, or, not), such as value is > 0 and
Pattern matching in C#—especially with is
expressions and switch
expressions—makes conditional logic cleaner, more expressive, and often easier to maintain. It helps you write code that's focused on the shape or structure of data rather than just its type or value.
Using is
expressions for concise type checks
Before C# 7, checking types usually means using a combination of is
followed by an explicit cast:
if (obj is string) { string s = (string)obj; // do something with s }
With pattern matching, you can simplify this into a single line:
if (obj is string s) { // use s directly }
This approach reduces boilerplate and keeps your logic tight. You're not just checking a condition—you're extracting usable values ??at the same time.
Another handy use is combining it with logical patterns ( and
, or
, not
). For example:
if (value is > 0 and < 10) { // value is between 1 and 9 }
Or filtering out nulls:
if (input is not null) { // proceed safely }
These make simple conditions easier to read and write without extra nesting or casting.
Switch expressions for clean multi-case logic
Traditional switch
statements were limited—they mostly worked with primitive types like int
or string
, and required verbose syntax with case
, break
, and so on.
C# 8 introduced switch expressions , which are much more flexible and compact. They work with any type and support pattern matching:
var result = shape switch { Circle c => $"Circle with radius {c.Radius}", Rectangle r => $"Rectangle {r.Width}x{r.Height}", _ => "Unknown shape" };
Here, each case matches both the type and optionally extracts properties. The _
acts as a default fallback.
This style removes a lot of ceremony from the older switch
syntax. It also enforces exhaustiveness, meaning the compiler will warn you if you miss a possible case.
You can even match based on property values:
var message = person switch { { Age: < 18 } => "Minor", { Age: >= 65 } => "Senior", _ => "Adult" };
This makes complex conditional logic feel more declarative and less procedural.
Where pattern matching really shines
Pattern matching becomes especially useful when dealing with nested or hierarchical data structures. For example, in domain models where different types behave differently, pattern matching lets you inspect and respond to those differences clearly.
It's also great in LINQ queries or filtering operations where you want to extract or transform data based on its structure:
var adults = people.Where(p => p is { Age: >= 18 });
That one-liner filters out only adults, using property pattern matching.
In recursive data structures like trees or expressions, pattern matching can help you deconstruct nodes cleanly and handle each case without deep nesting.
So, yeah, pattern matching in C# doesn't just save keystrokes—it improves readability, reduces error-prone casting, and give you a clearer way to express intent. Once you get used to writing things like is string s
or using switch expressions with rich patterns, going back feels clunky.
The above is the detailed content of How does pattern matching in C# (e.g., is expressions, switch expressions) simplify conditional logic?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reflection is a mechanism for dynamically checking and operating types and their members at runtime. Its core uses include: 1. Obtain type information and create instances dynamically; 2. Dynamically call methods and access attributes, including private members; 3. Check the types in the assembly, suitable for plug-in systems, serialization libraries and other scenarios. Common usage methods include loading DLL to create objects, traversing attributes for unified processing, calling private methods, etc. However, the reflection performance is low, and the main problems include slow first calls, slower frequent calls, and inability to optimize inline. Therefore, it is recommended to cache the reflection results, use delegate calls or alternatives to improve efficiency. The rational use of reflection can balance flexibility and performance.

Pattern matching in C# makes the conditional logic more concise and expressive through is expressions and switch expressions. 1. Use the is expression to perform concise type checks, such as if (objisstrings), and extract values ??at the same time; 2. Use logical modes (and, or, not) to simplify conditional judgments, such as valueis>0and

TheyieldkeywordinC#simplifiesiteratorcreationbyautomaticallygeneratingastatemachinethatenableslazyevaluation.1.Itallowsreturningitemsoneatatimeusingyieldreturn,pausingexecutionbetweeneachitem,whichisidealforlargeordynamicsequences.2.yieldbreakcanbeus

DependencyInjection(DI)inC#isadesignpatternthatenhancesmodularity,testability,andmaintainabilitybyallowingclassestoreceivedependenciesexternally.1.DIpromotesloosecouplingbydecouplingobjectcreationfromusage.2.Itsimplifiestestingthroughmockobjectinject

The role of IDisposable and using in C# is to efficiently and deterministically manage unmanaged resources. 1. IDisposable provides Dispose() method, so that the class can clearly define how to release unmanaged resources; 2. The using statement ensures that Dispose() is automatically called when the object is out of scope, simplifying resource management and avoiding leakage; 3. When using it, please note that the object must implement IDisposable, can declare multiple objects, and should always use using for types such as StreamReader; 4. Common best practices include not relying on destructors to clean up, correctly handling nested objects, and implementing the Dispose(bool) pattern.

LambdaexpressionsandLINQsimplifydatamanipulationinC#byenablingconcise,readable,andefficientcode.1.Lambdaexpressionsallowinlinefunctiondefinitions,makingiteasiertopasslogicasargumentsforfiltering,transforming,sorting,andaggregatingdatadirectlywithinme

Span and Memory improve C# performance by reducing memory allocation. 1. Span avoids array copying and provides light references to existing memory, which is suitable for parsing binary protocols, string operations and high-performance buffer management; 2. Memory supports passing memory slices across asynchronous methods, which is suitable for scenarios where more flexible life cycles are required; 3. Both reduce GC pressure, optimize performance by reusing buffers and avoiding temporary copying; 4. Span is limited to use on the stack and cannot be stored in classes or used in asynchronous methods. Be careful to avoid reassignment operations such as calling.ToArray().

Nullablereferencetypes(NRTs)inC#8 helpcatchNullReferenceExceptionerrorsatcompiletimebymakingreferencetypesnon-nullablebydefault,requiringexplicitdeclarationfornullability.NRTsmustbeenabledeitherinthe.csprojfilewithenableoratthetopofa.csfileusing#null
