亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Basic Syntax and Usage
Matching Multiple Values
Using Patterns Beyond Simple Values
Type Matching
Relational Patterns (C# 9)
Tips for Using Switch Expressions Effectively
Home Backend Development C#.Net Tutorial How to use C# switch expressions?

How to use C# switch expressions?

Jul 28, 2025 am 12:48 AM

<p></p> <p>Switch expressions are a simpler and easier to read in C# to handle multiple conditions than traditional switch statements. It was introduced in C# 8.0 and is suitable for scenarios based on conditional assignment without writing a large number of case and break statements. Its basic syntax uses the => operator to return the result of each matching pattern, for example, to judge the week through the dayOfWeek switch and return the corresponding string description. Use the _ symbol as the default. 1. It supports matching multiple values through or keywords to make the code more concise; 2. Type matching can be performed and different logics are performed according to the input type; 3. C# 9 supports relational pattern matching, such as using and other operators to judge the numerical range; 4. It is recommended to keep each branch short and use it for return values rather than complex logic; 5. Replace traditional switch statements as much as possible to improve code tidyness; 6. Remember to add defaults when necessary to ensure integrity. In short, C# switch expressions are a powerful and expressive feature that simplifies code structure and improves readability. </p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175363492366204.jpg" class="lazy" alt="How to use C# switch expressions?"></p> <p> Switch expressions in C# are a more concise and readable way to handle multiple conditions compared to traditional <code>switch</code> statements. They were introduced in C# 8.0 and are especially useful when you want to assign a value based on a condition without writing a lot of <code>case</code> and <code>break</code> statements. </p> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175363492554742.jpg" class="lazy" alt="How to use C# switch expressions?"><hr> <h3 id="Basic-Syntax-and-Usage"> Basic Syntax and Usage</h3> <p> A switch expression evaluates a value and returns a result based on matching patterns. The syntax is clean and uses the <code>=></code> operator to return a value for each case.</p> <p> Here's a simple example: </p> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175363492712401.jpg" class="lazy" alt="How to use C# switch expressions?"><pre class='brush:php;toolbar:false;'> string day = DateTime.Now.DayOfWeek switch { DayOfWeek.Monday => "Start of the workweek", DayOfWeek.Friday => "Almost weekend!", DayOfWeek.Saturday or DayOfWeek.Sunday => "Weekend!", _ => "Midweek" };</pre><ul><li> Each line inside the braces represent a pattern and its corresponding result.</li><li> The <code>_</code> symbol is the discard operator, acting as a default case.</li></ul><p> This is much cleaner than writing a full <code>switch</code> block with <code>case</code> , <code>break</code> , and variable assignments.</p><hr /><h3 id="Matching-Multiple-Values"> Matching Multiple Values</h3><p> You can match multiple values using the <code>or</code> keyword. This helps avoid repetition and keeps your code DRY (Don't Repeat Yourself). </p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175363492867744.png" class="lazy" alt="How to use C# switch expressions?" /><p> For example:</p><pre class='brush:php;toolbar:false;'> string mood = feeling switch { "happy" or "excited" => "Great to hear!", "sad" or "tired" => "Take care!", _ => "Hope you&#39;re doing OK" };</pre><p> This makes it easy to group related cases together without duplicating logic.</p><hr /><h3 id="Using-Patterns-Beyond-Simple-Values"> Using Patterns Beyond Simple Values</h3><p> C# switch expressions support more advanced pattern matching features, such as checking types or relational patterns.</p><h4 id="Type-Matching"> Type Matching</h4><pre class='brush:php;toolbar:false;'> string Describe(object obj) => obj switch { int i => $"An integer: {i}", string s => $"A string: {s}", null => "Nothing", _ => "Unknown type" };</pre><p> This allows you to write logic that behaves differently depending on the type of the input.</p><h4 id="Relational-Patterns-C"> Relational Patterns (C# 9)</h4><p> You can also use relational operators like <code><</code> , <code>></code> , etc.</p><pre class='brush:php;toolbar:false;'> string GetResult(int score) => score switch { < 60 => "Fail", >= 60 and < 70 => "Pass", >= 70 and < 90 => "Good", _ => "Excellent" };</pre><p> This replaces what used to require <code>if-else if-else</code> chains and makes the logic more compact.</p> <hr> <h3 id="Tips-for-Using-Switch-Expressions-Effectively"> Tips for Using Switch Expressions Effectively</h3> <ul> <li> Keep each case short and focused — switch expressions are best when returning a value, not executing complex logic.</li> <li> Use them when you have multiple discrete values or conditions that map to results.</li> <li> Prefer them over traditional <code>switch</code> statements when possible for cleaner code.</li> <li> Don't forget the default case ( <code>_</code> ) unless you're sure all possible values are covered.</li> </ul> <hr> <p> Overall, C# switch expressions are a powerful and expressive feature that can simplify your code and improve readability. They're especially handy when dealing with enums, strings, or basic conditional mappings. Just remember to keep things clear and logical — don't overdo it with too many nested conditions or complex patterns.</p>

The above is the detailed content of How to use C# switch expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Creating and Applying Custom Attributes in C# Creating and Applying Custom Attributes in C# Jul 07, 2025 am 12:03 AM

CustomAttributes are mechanisms used in C# to attach metadata to code elements. Its core function is to inherit the System.Attribute class and read through reflection at runtime to implement functions such as logging, permission control, etc. Specifically, it includes: 1. CustomAttributes are declarative information, which exists in the form of feature classes, and are often used to mark classes, methods, etc.; 2. When creating, you need to define a class inherited from Attribute, and use AttributeUsage to specify the application target; 3. After application, you can obtain feature information through reflection, such as using Attribute.GetCustomAttribute();

Designing Immutable Objects and Data Structures in C# Designing Immutable Objects and Data Structures in C# Jul 15, 2025 am 12:34 AM

The core of designing immutable objects and data structures in C# is to ensure that the state of the object is not modified after creation, thereby improving thread safety and reducing bugs caused by state changes. 1. Use readonly fields and cooperate with constructor initialization to ensure that the fields are assigned only during construction, as shown in the Person class; 2. Encapsulate the collection type, use immutable collection interfaces such as ReadOnlyCollection or ImmutableList to prevent external modification of internal collections; 3. Use record to simplify the definition of immutable model, and generate read-only attributes and constructors by default, suitable for data modeling; 4. It is recommended to use System.Collections.Imm when creating immutable collection operations.

Handling Large Datasets Efficiently with C# Handling Large Datasets Efficiently with C# Jul 06, 2025 am 12:10 AM

When processing large amounts of data, C# can be efficient through streaming, parallel asynchronous and appropriate data structures. 1. Use streaming processing to read one by one or in batches, such as StreamReader or EFCore's AsAsyncEnumerable to avoid memory overflow; 2. Use parallel (Parallel.ForEach/PLINQ) and asynchronous (async/await Task.Run) reasonably to control the number of concurrency and pay attention to thread safety; 3. Select efficient data structures (such as Dictionary, HashSet) and serialization libraries (such as System.Text.Json, MessagePack) to reduce search time and serialization overhead.

Mastering C# Reflection and Its Use Cases Mastering C# Reflection and Its Use Cases Jul 06, 2025 am 12:40 AM

Reflection is a function in C# for dynamic analysis and modification of program structures at runtime. Its core functions include obtaining type information, dynamically creating objects, calling methods, and checking assembly. Common application scenarios include: 1. Automatically bind the data model, such as mapping dictionary data to class instances; 2. Implement the plug-in system, loading external DLLs and calling its interface; 3. Supporting automated testing and logging, such as executing specific feature methods or automatically recording logs. When using it, you need to pay attention to performance overhead, encapsulation corruption and debugging difficulties. Optimization methods include caching type information, using delegates to improve call efficiency, and generating IL code. Rational use of reflection can improve the flexibility and versatility of the system.

Creating Custom Middleware in ASP.NET Core C# Creating Custom Middleware in ASP.NET Core C# Jul 11, 2025 am 01:55 AM

Create custom middleware in ASP.NETCore, which can be implemented by writing classes and registering. 1. Create a class containing the InvokeAsync method, handle HttpContext and RequestDelegatenext; 2. Register with UseMiddleware in Program.cs. Middleware is suitable for general operations such as logging, performance monitoring, exception handling, etc. Unlike MVC filters, it acts on the entire application and does not rely on the controller. Rational use of middleware can improve structural flexibility, but should avoid affecting performance.

Writing Maintainable and Testable C# Code Writing Maintainable and Testable C# Code Jul 12, 2025 am 02:08 AM

The key to writing C# code well is maintainability and testability. Reasonably divide responsibilities, follow the single responsibility principle (SRP), and take data access, business logic and request processing by Repository, Service and Controller respectively to improve structural clarity and testing efficiency. Multi-purpose interface and dependency injection (DI) facilitate replacement implementation, extension of functions and simulation testing. Unit testing should isolate external dependencies and use Mock tools to verify logic to ensure fast and stable execution. Standardize naming and splitting small functions to improve readability and maintenance efficiency. Adhering to the principles of clear structure, clear responsibilities and test-friendly can significantly improve development efficiency and code quality.

Best Practices for Using LINQ in C# Effectively Best Practices for Using LINQ in C# Effectively Jul 09, 2025 am 01:04 AM

The following points should be followed when using LINQ: 1. Priority is given to LINQ when using declarative data operations such as filtering, converting or aggregating data to avoid forced use in scenarios with side effects or performance-critical scenarios; 2. Understand the characteristics of delayed execution, source set modifications may lead to unexpected results, and delays or execution should be selected according to requirements; 3. Pay attention to performance and memory overhead, chain calls may generate intermediate objects, and performance-sensitive codes can be replaced by loops or spans; 4. Keep the query concise and easy to read, and split complex logic into multiple steps to avoid excessive nesting and mixing of multiple operations.

Deep Dive into C# Generics Constraints and Covariance Deep Dive into C# Generics Constraints and Covariance Jul 12, 2025 am 02:00 AM

Generic constraints are used to restrict type parameters to ensure specific behavior or inheritance relationships, while covariation allows subtype conversion. For example, whereT:IComparable ensures that T is comparable; covariation such as IEnumerable allows IEnumerable to be converted to IEnumerable, but it is only read and cannot be modified. Common constraints include class, struct, new(), base class and interface, and multiple constraints are separated by commas; covariation requires the out keyword and is only applicable to interfaces and delegates, which is different from inverter (in keyword). Note that covariance does not support classes, cannot be converted at will, and constraints affect flexibility.

See all articles