How to use pattern matching in C#?
Pattern matching in C# is a feature used to check objects against patterns and extract information concisely. 1. Type patterns allow checking and casting in one step, as shown with if (value is string str). 2. Constant patterns compare values against constants directly, such as checking if (input is null). 3. Switch expressions with patterns simplify logic, demonstrated by shape switch returning different strings based on shape type. 4. Recursive patterns match nested structures, like checking person is { Name: "Alice", Address: { City: "Wonderland" } }. Overall, pattern matching improves code readability and expressiveness when used appropriately.
Pattern matching in C# is a powerful feature that allows you to check an object against a pattern and extract information from it in a concise and readable way. It’s especially useful when working with different types, conditions, or structures.

Here are a few practical ways you can use pattern matching in your C# code:
1. Type Patterns – Check and Cast in One Step
One of the most common uses of pattern matching is to check the type of an object and cast it at the same time.

if (value is string str) { Console.WriteLine($"It's a string: {str.ToUpper()}"); }
This replaces older code like:
if (value is string) { string str = (string)value; // ... }
This is cleaner and avoids repeating the variable name or doing a separate cast.

2. Constant Patterns – Match Specific Values
You can use pattern matching to compare values against constants directly in a condition.
if (input is null) { Console.WriteLine("Input is null"); }
Or with numeric values:
switch (number) { case 0: Console.WriteLine("Zero"); break; case var n when n > 0: Console.WriteLine("Positive"); break; }
This can make conditional logic easier to read, especially when combined with switch
expressions.
3. Switch Expressions with Patterns
C# 8 introduced switch expressions, which work well with pattern matching to simplify logic.
string result = shape switch { Rectangle r => $"Rectangle: {r.Width}x{r.Height}", Circle c => $"Circle: radius {c.Radius}", null => "No shape", _ => "Unknown shape" };
This replaces longer switch
statements and makes the code more expressive. The _
is a discard pattern that matches anything not covered above.
4. Recursive Patterns – Match Nested Structures
In C# 9 and later, you can use recursive patterns to match nested properties. For example:
if (person is { Name: "Alice", Address: { City: "Wonderland" } }) { Console.WriteLine("Found Alice from Wonderland"); }
This is useful when you want to check deeply nested data without writing multiple nested if
conditions.
A few things to keep in mind:
- Pattern matching works best with
is
,switch
, and in some cases withswitch
expressions. - You can combine patterns with
when
clauses for more complex conditions. - Avoid overusing it in deeply nested logic where readability might suffer.
Pattern matching in C# helps you write cleaner, more expressive code once you get used to the syntax. It’s not overly complex, but it does take a bit of practice to know when and how to use it effectively.
The above is the detailed content of How to use pattern matching in C#?. 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.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

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)

The answer is to read appsettings.json using Microsoft.Extensions.Configuration. 1. Create appsettings.json and set the copy properties; 2. Install the Microsoft.Extensions.Configuration.Json package; 3. Load the configuration with ConfigurationBuilder; 4. Read the value through the indexer or GetConnectionString; 5. It is recommended to use strongly typed configuration classes Bind or Get binding.

Usestringforminimal,statictextoperations;useStringBuilderforfrequentmodificationsinloopsorlarge-scaleconcatenationstoimproveperformanceandreducememoryallocation.

HttpClient should be reused for a long time rather than created frequently. It is recommended to use IHttpClientFactory injection management to avoid socket exhaustion; if there is no DI, use static instances to ensure a reasonable life cycle.

Migrating .NET monomers to microservices should avoid one-time rewrites. 1. First, clear the migration of mobile machines and avoid common traps to ensure that the team has DevOps and observability capabilities; 2. Use strangler mode to gradually replace, route new functions to new services through API gateways; 3. Use domain-driven design to identify bounded contexts, split services according to business boundaries and isolate databases; 4. Select a suitable communication method, use HTTP/REST for user requests, and use asynchronous messages such as AzureServiceBus for events; 5. Ensure cross-service data consistency through event final consistency, Saga mode and Outbox mode; 6. Early integration of Serilog, OpenTelemetry and other tools to build date

First()throwsanexceptionifnoelementisfound,whileFirstOrDefault()returnsadefaultvalue;useFirst()whenthesequenceisexpectedtobenon-empty,andFirstOrDefault()tohandleemptysequencesgracefully.

Public members can be accessed by any code; 2.private is only accessible within the class; 3.protected allows access to classes and derived classes; 4.internal is limited to access within the same assembly; 5.protectedinternal is a union of protected and internal, used for access to derived classes or same assembly.

Create a CancellationTokenSource to get the CancellationToken, which is used to notify other threads or components to cancel the operation. 2. Pass the token to an asynchronous method that supports cancellation (such as Task.Run). The task can periodically check the cancellation request to achieve graceful termination.

PatternmatchinginC#isafeatureusedtocheckobjectsagainstpatternsandextractinformationconcisely.1.Typepatternsallowcheckingandcastinginonestep,asshownwithif(valueisstringstr).2.Constantpatternscomparevaluesagainstconstantsdirectly,suchascheckingif(input
