C# 9.0: Pattern Matching in Switch Expressions

In the previous blog posts about C# 9.0 you learned about different features:

  • Top-level statements
  • Init-only properties
  • Target-typed new expressions
  • Improved Pattern Matching

In this blog post, let’s look at C# 9.0 pattern matching in switch expressions .

In the previous blog post you learned about using patterns with the is pattern expression, and you learned about the new relational patterns in C# 9.0, and also about the new pattern combinators and and or . If you haven’t read the previous blog post, I recommend you to read it, as I don’t repeat the basics of relational patterns and pattern combinators in this blog post.

The is pattern expression allows you to evaluate patterns. But you can also evaluate patterns in a switch expression. In this blog post, we use switch expressions. But before we do that, let’s go a bit back and let’s look at switch statements before C# 7.0 to understand how they have evolved.

Switch Statements Before C# 7.0

Since C# 1.0, you can write switch statements in your code. You usually do this instead of writing if / else if / else logic like you see it in the code snippet below.

Instead of the if / else stuff above, you can create a beautiful switch statement like below:

But switch statements were a bit limited before C# 7.0. Let’s say you have the class structure like below:

Now let’s say that you want to switch an object variable by the type that was assigned to that variable. When you try to use an object variable as input for the switch statement, you get the error that you see below if you use C# 6.0 or earlier:

c# switch statement assignment

So, you see, before C# 7.0 you can only use bool , char , string , integral types like int and float , enumerations, and corresponding nullable types. But you can’t switch for example by an object variable like I try it in the screenshot above.

Another problem is that a case in the switch statement requires a constant value, and that constant value has the same type limitations. For example, the following switch statement does not work in C# 6.0 or earlier because of two reasons: Firstly, I try to switch by an object , and secondly, the typeof keyword resolves a type, it is not a constant value. This means that the code that you see in the snippet below does not compile. (Note: Using typeof for the case label does not compile in any C# version):

Before C# 7.0, you had to solve the problem above by switching by type name, which means that you switch by string , which is supported. In the code below I do this, and for the cases I use the string constants “Developer” and “Manager”. This works fine.

With the nameof keyword that was introduced with C# 6.0, you can even let the compiler generate the strings “Developer” and “Manager” from the class names like you see it below. This helps you to avoid typos in your code, as the compiler will generate the strings from the class names for you:

But now, what if you want to use the developer’s firstname? Then you have to cast the obj variable to a Developer like you see it in the statement below.

Patterns in Switch Statements with C# 7.0

C# 7.0 introduced the support for type patterns in switch statements. You can switch by any type, and you can use patterns in your switch statement. Look at the switch statement in the code snippet below. I switch by an object variable. Then I use the type pattern to check if the object is a Developer or a Manager . When you don’t need for example the Developer object to be stored in a variable, you use a discard, which is an underscore.

Instead of using a discard, you can define a variable that you use in the case block:

C# 7.0 also introduced when conditions for the cases. They work pretty much like an if statement, just inside of a switch statement on a specific case. Do you want to define a case that checks if the type is a Developer , and if they were born in the eighties? It’s like this in C# 7.0 with when conditions:

Note that the when condition is like an if condition, so don’t mix this up with relational patterns and pattern combinators that were introduced with C# 9.0. The when condition above uses like an if condition the relational operators (operators!!!, not patterns) >= and <= and the boolean logical AND operator && to combine the two bool values.

Important is now also the order of the cases. Look at the switch statement below. If you pass in a Developer object, three different cases match, and only the first one that matches is used:

That’s what was added with C# 7.0. Now, let’s move on to C# 8.0.

Switch Expressions and Pattern Matching in C# 8.0

C# 8.0 introduced switch expressions. Let’s take the simple switch statement that I wrote at the beginning of this blog post:

When you use C# 8.0 or later, you can put the cursor in Visual Studio on that switch statement, and Visual Studio will suggest you to convert it to a switch expression:

c# switch statement assignment

The code that you get is the beautiful switch expression that you see in the following code snippet. Note how all the case and break clutter went away, and how readable it is. A case in a switch expression is actually a so-called switch expression arm :

The code above will blow up if the developer variable is null , as the FirstName property is accessed with the dot syntax. You can also pass the full Developer object to the switch expression to use property patterns like in the code snippet below. Property patterns were also introduced with C# 8.0:

Now let’s look at another C# 7.0 switch statement, where I switch by type:

Also the switch statement above can be converted to a switch expression that you see in the code snippet below:

Instead of the when condition to check the YearOfBirth property, you can use a property pattern:

But now, what if you want to check if the developer was born in the eighties? You can’t do that in C# 8.0 with a property pattern, as relational patterns and pattern combinators are not supported, they were introduced with C# 9.0. This means, to check in C# 8.0 if a developer was born in the eighties, you have to use a when condition like in this code snippet:

Relational Patterns and Pattern Combinators in C# 9.0

You learned already in the previous blog post about the relational patterns > , >= , < , and <= , and also about the pattern combinators and and or . Relational patterns and pattern combinators were introduced with C# 9.0, and you can use them not only with is expressions, but also in switch expressions. The following code snippet uses a C# 8.0 style when condition with relational operators to check if the developer was born in the eighties:

With C# 9.0, you can write the when condition also with the is expression and with relational patterns and the and pattern combinator like in the following snippet. Visual Studio actually suggests this to you. Note how you write the YearOfBirth property in the code snippet below just once, and then you use the is expression with combined relational patterns to check the shape of the property. In the code snippet above, we wrote the YearOfBirth property twice, as we didn’t use combined relational patterns, but instead combined bool values and relational operators.

But instead of using the when condition, you can also use a property pattern, which looks even nicer and more compact:

As you can see, you can use all the C# 9.0 pattern matching magic in your switch expression. Do you want to create a switch expression arm for developers born in the eighties, but not in 1984? Here we go:

Also an addition is that you don’t have to define a discard if you don’t need the variable. So, instead of

you can write with C# 9.0 just

You would still use a discard to define the default case in your switch expression:

If you have already a variable of type Developer , you don’t have to use the type pattern. You can use property patterns directly, you can also use for example the negotiated null pattern like you see it here:

Like with is expressions, you can also nest property patterns. To create a switch expression arm for developers whose manager is born in 1980, you can write it like this:

If you have a simple type like an int variable like you see it in the code snippet below, you can also write the patterns directly without any curlies:

Oh, one more thing: Did you notice the last comma behind the last switch expression arm in the code snippet above? I think so, as I added a comment there, right?! That is the so-called trailing comma, and it’s optional. Sometimes when you copy and paste switch expression arms to change the order, it’s a bit simpler if you can keep that trailing comma.

As you saw in this blog post, C# 7.0 introduced patterns in switch statements, C# 8.0 introduced switch expressions and more patterns like property patterns, and C# 9.0 introduced the relational patterns and pattern combinators that you can use in your switch expressions.

I hope you enjoyed reading this blog post.

Finally, I want to say that not all people born in the eighties listen to heavy metal. But I do. :-)

In the next blog post, you will learn about covariant return types in C# 9.0.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Share this post

' src=

Thomas Claudius Huber

Comments (19)

' src=

Awesome explanation.

Thank you Anil, great to hear that you like it.

' src=

I’d like to thank you for all courses on Pluralsight. They are awesome. You are teaching to C# developers with an amazing refactoring and abstraction mind-set. I ve learned so much about MVVM, XAML, TDD etc.. Definitely a 5-star MVP.

Hey Atilla, thank you so much for your feedback. I’m happy to read this, and your comment was worth creating all those courses! Thank you, Thomas

' src=

thx, very nice.

' src=

I was born in 1988, and I’m listening to metal while coding (while looking through this). That’s good to know about the property patterns.

That’s great to hear Nathan. I actually love metal from the 80s. :) Iron Maiden, Whitesnake, Skid Row, Manowar, W.A.S.P, Judas Priest, Metallica etc. :)

' src=

Clear explanation. Great. Thank you!

You’re welcome Tilahun

' src=

What about multiple variables, functions calls and etc under same case?

case 1 : functionA; functionB; break; case 2: functionC; break;

is it like that:

1=> functionA, FunctionB, 2=> functionC, _ default…. ?

I have a question about this pattern:

if I have multiple lines under same case, how can I write this in new C# switch case?

for example

swtich (x){ case 1: something = list1(); something2 = list2(); break; case 2: something3 = lsit3(); break; default: break;

thank you very much..

' src=

Really grateful for such clear and precise explanation. It’s a pleasure to read this article!

Thank you David

' src=

Thanks Thomas. What I like most: 1984 => “Read George Orwell’s book” :) You are awesome! Hope you’re doing well!

' src=

Nice post. https://stackoverflow.com/questions/59687295/can-i-use-pattern-matching-for-code-like-this-on-generic-types

' src=

I think it’s one of the simplest explanation I’ve read. Thank you.

Thank you Edward

' src=

“Stare into the void”. I lost it lolllll. Good post.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Spam protection: Sum of 9 + 10 ? *

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Related Posts

C# 12: alias any type.

In the previous blog posts of this C# 12 series you learned about different C# 12 features: Primary Constructors Collection Expressions In this... read more

C# 12: Collection Expressions

In the previous blog post you learned about C# 12 primary constructors. In this blog post, you will learn about... read more

C# 12: Primary Constructors

In November 2023, Microsoft released .NET 8.0, and since then you can use C# 12.So, it might be a good... read more

Create a GitHub Action in Visual Studio to Deploy Your .NET Web App automatically to Azure on Every Commit

When building a web application, it can be helpful to deploy your application with the latest features and code changes... read more

C# 11.0: Generic Math, C# Operators and Static Abstract/Virtual Interface Members

In the previous blog posts you learned about different C# 11.0 features: Raw String Literals Generic Attributes In this blog post, let's look... read more

C# 11.0: Generic Attributes

In the previous blog post you learned about C# 11.0 raw string literals. In this blog post, you will learn about another... read more

C# 11.0: Raw String Literals

In November 2022, .NET 7.0 was released, and since then, you can use C# 11.0. In version 11.0, the C# language... read more

C# 10.0: Extended Property Patterns – Use the Dot Token to Access Nested Members

In the previous blog posts you learned about different C# 10.0 features: File-scoped namespaces Global using directives In this blog post, let's look... read more

C# 10.0: Global Using Directives – Make Important Namespaces Available in Your Whole Project

In the previous blog post you learned about C# 10.0 file-scoped namespaces. In this blog post you learn about another C# 10.0... read more

C# 10.0: File Scoped Namespaces – Get More Space For Your Code

C# 10.0 and .NET 6.0 will be released in November 2021. Time to look at the new language features with... read more

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, introduction.

  • C# Hello World
  • C# Keywords & Identifiers
  • C# Variables
  • C# Operators
  • C# Operator Precedence
  • C# Bitwise Operators
  • C# Basic I/O
  • C# Expressions & Statements
  • C# Comments

Flow Control

  • C# if...else

C# switch Statement

  • C# Ternary Operator
  • C# for Loop
  • C# while Loop
  • C# Nested Loops

C# break Statement

  • C# continue Statement
  • C# Multidimensional Arrays
  • C# Jagged Array
  • C# foreach Loop
  • C# Class and Objects
  • C# Access Modifiers
  • C# Variable Scope
  • C# Constructors
  • C# this Keyword
  • C# static Keyword
  • C# Inheritance
  • C# Abstract Class & Methods
  • C# Nested Class
  • C# Partial Class
  • C# Sealed Class
  • C# Interface
  • C# Method Overloading
  • C# Constructor Overloading

Additional Topics

  • C# Type Conversion
  • C# Preprocessor Directives
  • C# Namespaces

C# Tutorials

C# if, if...else, if...else if and Nested if Statement

C# Expressions, Statements and Blocks (With Examples)

  • C# Basic Input and Output

Switch statement can be used to replace the if...else if statement in C#. The advantage of using switch over if...else if statement is the codes will look much cleaner and readable with switch.

The syntax of switch statement is:

The switch statement evaluates the expression (or variable ) and compare its value with the values (or expression) of each case ( value1 , value2 , …). When it finds the matching value, the statements inside that case are executed.

But, if none of the above cases matches the expression, the statements inside default block is executed. The default statement at the end of switch is similar to the else block in if else statement.

However a problem with the switch statement is, when the matching value is found, it executes all statements after it until the end of switch block.

To avoid this, we use break statement at the end of each case. The break statement stops the program from executing non-matching statements by terminating the execution of switch statement.

To learn more about break statement, visit C# break statement .

Example 1: C# switch Statement

When we run the program, the output will be:

In this example, the user is prompted to enter an alphabet. The alphabet is converted to lowercase by using ToLower() method if it is in uppercase.

Then, the switch statement checks whether the alphabet entered by user is any of a, e, i, o or u .

If one of the case matches, Vowel is printed otherwise the control goes to default block and Not a vowel is printed as output.

Since, the output for all vowels are the same, we can join the cases as:

Example 2: C# switch Statement with grouped cases

The output of both programs is same. In the above program, all vowels print the output Vowel and breaks from the switch statement.

Although switch statement makes the code look cleaner than if...else if statement, switch is restricted to work with limited data types. Switch statement in C# only works with:

  • Primitive data types: bool, char and integral type
  • Enumerated Types (Enum)
  • String Class
  • Nullable types of above data types

Example 3: Simple calculator program using C# switch Statement

The above program takes two operands and an operator as input from the user and performs the operation based on the operator.

The inputs are taken from the user using the ReadLine() and Read() method. To learn more, visit C# Basic Input and Output .

The program uses switch case statement for decision making. Alternatively, we can use if-else if ladder to perform the same operation.

Table of Contents

  • Switch statement and its syntax
  • Example 1: How switch statement works?
  • Example 2: Grouping cases in switch statement
  • Example 3: Simple calculator using switch statement

Sorry about that.

Related Tutorials

C# Tutorial

c# switch statement assignment

C# - Switch Statement

The switch statement can be used instead of if else statement when you want to test a variable against three or more conditions. Here, you will learn about the switch statement and how to use it efficiently in the C# program.

The following is the general syntax of the switch statement.

The following example demonstrates a simple switch statement.

Above, the switch(x) statement includes a variable x whose value will be matched with the value of each case value. The above switch statement contains three cases with constant values 5, 10, and 15. It also contains the default label, which will be executed if none of the case value match with the switch variable/expression. Each case starts after : and includes one statement to be executed. The value of x matches with the second case case 10: , so the output would be Value of x is 10 .

The switch statement can also include an expression whose result will be tested against each case at runtime.

Switch Case

The switch cases must be unique constant values. It can be bool, char, string, integer, enum, or corresponding nullable type.

Consider the following example of a simple switch statement.

Multiple cases can be combined to execute the same statements.

Each case must exit the case explicitly by using break , return , goto statement, or some other way, making sure the program control exits a case and cannot fall through to the default case.

The following use the return keyword.

The switch cases without break, return, or goto statement or with the same constant values would give a compile-time error.

Nested Switch Statements

A switch statement can be used inside another switch statement.

c# switch statement assignment

  • The switch statement is an alternative to if else statement.
  • The switch statement tests a match expression/variable against a set of constants specified as cases.
  • The switch case must include break, return, goto keyword to exit a case.
  • The switch can include one optional default label, which will be executed when no case executed.
  • C# compiler will give errors on missing : , constant value with cases, exit from a case.
  • C# 7.0 onward, switch cases can include non-unique values. In this case, the first matching case will be executed.
  • Difference between Array and ArrayList
  • Difference between Hashtable and Dictionary
  • How to write file using StreamWriter in C#?
  • How to sort the generic SortedList in the descending order?
  • Difference between delegates and events in C#
  • How to read file using StreamReader in C#?
  • How to calculate the code execution time in C#?
  • Design Principle vs Design Pattern
  • How to convert string to int in C#?
  • Boxing and Unboxing in C#
  • More C# articles

c# switch statement assignment

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Learn more about us .

.NET Tutorials

Database tutorials, javascript tutorials, programming tutorials.

  • C# Questions & Answers
  • C# Skill Test
  • C# Latest Articles

Home » C# Tutorial » C# switch

Summary : in this tutorial, you’ll learn how to use the C# switch statement to select a block for execution if an expression matches a pattern.

Introduction to the C# switch statement

The switch statement evaluates an expression and selects a block for execution if the expression satisfies a condition. The syntax of the switch statement is as follows:

In this syntax, the switch statement matches the expression with label1 , label2 , label3 , … in each case clause from top to bottom.

If the expression matches a label , the switch statement will execute the corresponding block and pass the control to the following statement.

If the expression doesn’t match any label, the switch statement executes the block in the default clause.

The default clause is optional. If you don’t specify it and the expression doesn’t match any label , the switch statement doesn’t execute any block and passes the control to the statement after it.

The switch statement uses many patterns to match the expression with the labels. In this tutorial, you’ll focus on the following patterns:

  • A constant pattern: test if the result of the expresion is equal to a constant.
  • A relational pattern: compare the result of the expression with a constant using a relational operator such as <, <=, >, >=.

The following flowchart illustrates how the switch statement works.

C# switch statement example

The following program uses the switch statement to display the month name based on the month number entered by users:

How it works.

First, prompt users to input a number from 1 to 12:

Second, match the input month number with a number from 1 to 12 using the switch statement and assign the month name accordingly.

If the month number is not in the range of 1 to 12, the month name will be “Invalid month”:

Third, display the month name:

Group case in the C# switch statement

If you have the same block that corresponds to multiple cases, you can group cases in the switch statement like this:

In this syntax, the switch statement will execute block 1 if the expression matches the firstCase and secondCase . Likewise, it’ll execute block 2 if the expression matches the thirdCase and fourthCase .

If the expression doesn’t match any labels in the case clauses, it’ll execute the block n in the default clause.

The following example prompts users to input a month number and display the corresponding quarter name of that month:

First, prompt users to input a month number from 1 to 12:

Second, set the quarter based on the month number using the switch statement with group cases:

Third, display the quarter name:

C# switch statement with relation pattern example

Starting in C# 9, you can use use the relational operator > , >= , < , <= to match the result of the expression with constants in the switch statement.

We’ll rewrite the body mass index (BMI) calculation program in the if else if statement tutorial using the switch statement with the relational pattern:

First, prompt users to enter their weight in kg and height in m :

Second, calculate the BMI by taking the weight divided by the square of height:

Third, assign the weight status based on the BMI value:

Finally, display the BMI and weight status:

As you can see, the switch statement is much more readable than the if else if statement.

  • Use the switch statement to execute a block if an expression matches a pattern.
  • The switch statement uses many matching patterns.
  • Use the constant pattern to test if the expression result is equal to a constant.
  • Use the relational pattern to test the expression result with a constant using the relational operator <, <=, >, >=.
  • Use a group case to execute the same block that corresponds to multiple cases.
  • The switch statement executes the block in the default clause if the expression doesn’t match any cases. The default clause is optional.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Pattern matching - the is and switch expressions, and operators and , or and not in patterns

  • 3 contributors

You use the is expression , the switch statement and the switch expression to match an input expression against any number of characteristics. C# supports multiple patterns, including declaration, type, constant, relational, property, list, var, and discard. Patterns can be combined using Boolean logic keywords and , or , and not .

The following C# expressions and statements support pattern matching:

  • is expression
  • switch statement
  • switch expression

In those constructs, you can match an input expression against any of the following patterns:

  • Declaration pattern : to check the run-time type of an expression and, if a match succeeds, assign an expression result to a declared variable.
  • Type pattern : to check the run-time type of an expression.
  • Constant pattern : to test if an expression result equals a specified constant.
  • Relational patterns : to compare an expression result with a specified constant.
  • Logical patterns : to test if an expression matches a logical combination of patterns.
  • Property pattern : to test if an expression's properties or fields match nested patterns.
  • Positional pattern : to deconstruct an expression result and test if the resulting values match nested patterns.
  • var pattern : to match any expression and assign its result to a declared variable.
  • Discard pattern : to match any expression.
  • List patterns : to test if sequence elements match corresponding nested patterns. Introduced in C# 11.

Logical , property , positional , and list patterns are recursive patterns. That is, they can contain nested patterns.

For the example of how to use those patterns to build a data-driven algorithm, see Tutorial: Use pattern matching to build type-driven and data-driven algorithms .

Declaration and type patterns

You use declaration and type patterns to check if the run-time type of an expression is compatible with a given type. With a declaration pattern, you can also declare a new local variable. When a declaration pattern matches an expression, that variable is assigned a converted expression result, as the following example shows:

A declaration pattern with type T matches an expression when an expression result is non-null and any of the following conditions are true:

The run-time type of an expression result is T .

The run-time type of an expression result derives from type T , implements interface T , or another implicit reference conversion exists from it to T . The following example demonstrates two cases when this condition is true:

In the preceding example, at the first call to the GetSourceLabel method, the first pattern matches an argument value because the argument's run-time type int[] derives from the Array type. At the second call to the GetSourceLabel method, the argument's run-time type List<T> doesn't derive from the Array type but implements the ICollection<T> interface.

The run-time type of an expression result is a nullable value type with the underlying type T .

A boxing or unboxing conversion exists from the run-time type of an expression result to type T .

The following example demonstrates the last two conditions:

If you want to check only the type of an expression, you can use a discard _ in place of a variable's name, as the following example shows:

For that purpose you can use a type pattern , as the following example shows:

Like a declaration pattern, a type pattern matches an expression when an expression result is non-null and its run-time type satisfies any of the conditions listed above.

To check for non-null, you can use a negated null constant pattern , as the following example shows:

For more information, see the Declaration pattern and Type pattern sections of the feature proposal notes.

Constant pattern

You use a constant pattern to test if an expression result equals a specified constant, as the following example shows:

In a constant pattern, you can use any constant expression, such as:

  • an integer or floating-point numerical literal
  • a string literal.
  • a Boolean value true or false
  • an enum value
  • the name of a declared const field or local

The expression must be a type that is convertible to the constant type, with one exception: An expression whose type is Span<char> or ReadOnlySpan<char> can be matched against constant strings in C# 11 and later versions.

Use a constant pattern to check for null , as the following example shows:

The compiler guarantees that no user-overloaded equality operator == is invoked when expression x is null is evaluated.

You can use a negated null constant pattern to check for non-null, as the following example shows:

For more information, see the Constant pattern section of the feature proposal note.

Relational patterns

You use a relational pattern to compare an expression result with a constant, as the following example shows:

In a relational pattern, you can use any of the relational operators < , > , <= , or >= . The right-hand part of a relational pattern must be a constant expression. The constant expression can be of an integer , floating-point , char , or enum type.

To check if an expression result is in a certain range, match it against a conjunctive and pattern , as the following example shows:

If an expression result is null or fails to convert to the type of a constant by a nullable or unboxing conversion, a relational pattern doesn't match an expression.

For more information, see the Relational patterns section of the feature proposal note.

Logical patterns

You use the not , and , and or pattern combinators to create the following logical patterns :

Negation not pattern that matches an expression when the negated pattern doesn't match the expression. The following example shows how you can negate a constant null pattern to check if an expression is non-null:

Conjunctive and pattern that matches an expression when both patterns match the expression. The following example shows how you can combine relational patterns to check if a value is in a certain range:

Disjunctive or pattern that matches an expression when either pattern matches the expression, as the following example shows:

As the preceding example shows, you can repeatedly use the pattern combinators in a pattern.

Precedence and order of checking

The pattern combinators are ordered from the highest precedence to the lowest as follows:

When a logical pattern is a pattern of an is expression, the precedence of logical pattern combinators is higher than the precedence of logical operators (both bitwise logical and Boolean logical operators). Otherwise, the precedence of logical pattern combinators is lower than the precedence of logical and conditional logical operators. For the complete list of C# operators ordered by precedence level, see the Operator precedence section of the C# operators article.

To explicitly specify the precedence, use parentheses, as the following example shows:

The order in which patterns are checked is undefined. At run time, the right-hand nested patterns of or and and patterns can be checked first.

For more information, see the Pattern combinators section of the feature proposal note.

Property pattern

You use a property pattern to match an expression's properties or fields against nested patterns, as the following example shows:

A property pattern matches an expression when an expression result is non-null and every nested pattern matches the corresponding property or field of the expression result.

You can also add a run-time type check and a variable declaration to a property pattern, as the following example shows:

A property pattern is a recursive pattern. That is, you can use any pattern as a nested pattern. Use a property pattern to match parts of data against nested patterns, as the following example shows:

The preceding example uses the or pattern combinator and record types .

Beginning with C# 10, you can reference nested properties or fields within a property pattern. This capability is known as an extended property pattern . For example, you can refactor the method from the preceding example into the following equivalent code:

For more information, see the Property pattern section of the feature proposal note and the Extended property patterns feature proposal note.

You can use the Simplify property pattern (IDE0170) style rule to improve code readability by suggesting places to use extended property patterns.

Positional pattern

You use a positional pattern to deconstruct an expression result and match the resulting values against the corresponding nested patterns, as the following example shows:

At the preceding example, the type of an expression contains the Deconstruct method, which is used to deconstruct an expression result. You can also match expressions of tuple types against positional patterns. In that way, you can match multiple inputs against various patterns, as the following example shows:

The preceding example uses relational and logical patterns.

You can use the names of tuple elements and Deconstruct parameters in a positional pattern, as the following example shows:

You can also extend a positional pattern in any of the following ways:

Add a run-time type check and a variable declaration, as the following example shows:

The preceding example uses positional records that implicitly provide the Deconstruct method.

Use a property pattern within a positional pattern, as the following example shows:

Combine two preceding usages, as the following example shows:

A positional pattern is a recursive pattern. That is, you can use any pattern as a nested pattern.

For more information, see the Positional pattern section of the feature proposal note.

var pattern

You use a var pattern to match any expression, including null , and assign its result to a new local variable, as the following example shows:

A var pattern is useful when you need a temporary variable within a Boolean expression to hold the result of intermediate calculations. You can also use a var pattern when you need to perform more checks in when case guards of a switch expression or statement, as the following example shows:

In the preceding example, pattern var (x, y) is equivalent to a positional pattern (var x, var y) .

In a var pattern, the type of a declared variable is the compile-time type of the expression that is matched against the pattern.

For more information, see the Var pattern section of the feature proposal note.

Discard pattern

You use a discard pattern _ to match any expression, including null , as the following example shows:

In the preceding example, a discard pattern is used to handle null and any integer value that doesn't have the corresponding member of the DayOfWeek enumeration. That guarantees that a switch expression in the example handles all possible input values. If you don't use a discard pattern in a switch expression and none of the expression's patterns matches an input, the runtime throws an exception . The compiler generates a warning if a switch expression doesn't handle all possible input values.

A discard pattern can't be a pattern in an is expression or a switch statement. In those cases, to match any expression, use a var pattern with a discard: var _ . A discard pattern can be a pattern in a switch expression.

For more information, see the Discard pattern section of the feature proposal note.

Parenthesized pattern

You can put parentheses around any pattern. Typically, you do that to emphasize or change the precedence in logical patterns , as the following example shows:

List patterns

Beginning with C# 11, you can match an array or a list against a sequence of patterns, as the following example shows:

As the preceding example shows, a list pattern is matched when each nested pattern is matched by the corresponding element of an input sequence. You can use any pattern within a list pattern. To match any element, use the discard pattern or, if you also want to capture the element, the var pattern , as the following example shows:

The preceding examples match a whole input sequence against a list pattern. To match elements only at the start or/and the end of an input sequence, use the slice pattern .. , as the following example shows:

A slice pattern matches zero or more elements. You can use at most one slice pattern in a list pattern. The slice pattern can only appear in a list pattern.

You can also nest a subpattern within a slice pattern, as the following example shows:

For more information, see the List patterns feature proposal note.

C# language specification

For more information, see the Patterns and pattern matching section of the C# language specification .

For information about features added in C# 8 and later, see the following feature proposal notes:

  • Recursive pattern matching
  • Pattern-matching updates
  • C# 10 - Extended property patterns
  • C# 11 - List patterns
  • C# 11 - Pattern match Span<char> on string literal
  • C# operators and expressions
  • Pattern matching overview
  • Tutorial: Use pattern matching to build type-driven and data-driven algorithms

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

IMAGES

  1. Better C# Switch Statements for a Range of Values

    c# switch statement assignment

  2. C# Switch Statement vs Switch Expression Explained

    c# switch statement assignment

  3. Switch and case c#. C Language Switch Case with Examples. 2022-10-23

    c# switch statement assignment

  4. Switch Statement in C#

    c# switch statement assignment

  5. C# SWITCH Statement Video Tutorial and Source code

    c# switch statement assignment

  6. C# switch statements example

    c# switch statement assignment

VIDEO

  1. Hiç Birşey Bilmeden C#

  2. ✅Switch Statement && ✅Break && ✅ Continue in C

  3. C#: Switch Case

  4. C# Conditional statement

  5. If Statement Assignment

  6. C# Switch case

COMMENTS

  1. c# - Setting a Variable to a Switch's Result - Stack Overflow

    If you're interested in having a "switch" expression, you can find the little fluent class that I wrote here in order to have code like this: a = Switch.On(b) .Case(c).Then(d) .Case(e).Then(f) .Default(g); You could go one step further and generalize this even more with function parameters to the Then methods.

  2. switch expression - Evaluate a pattern match expression using ...

    In this article. You use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an input expression. For information about the switch statement that supports switch-like semantics in a statement context, see the switch statement section of the Selection statements article.

  3. Possible to assign a return from a switch case in C#?

    All the examples I've seen of C# switch statements are as follows. var variable, result; switch (variable) {. case 1: result = somevalue; break; case 2: result = someothervalue; break; } However, I would like to have something like. var result = switch (variable) {. case 1: return <somevalue>;

  4. if and switch statements - select a code path to execute - C#

    The if, if-else and switch statements select statements to execute from many possible paths based on the value of an expression. The if statement executes a statement only if a provided Boolean expression evaluates to true. The if-else statement allows you to choose which of the two code paths to follow based on a Boolean expression.

  5. C# 9.0: Pattern Matching in Switch Expressions – Thomas ...

    As you saw in this blog post, C# 7.0 introduced patterns in switch statements, C# 8.0 introduced switch expressions and more patterns like property patterns, and C# 9.0 introduced the relational patterns and pattern combinators that you can use in your switch expressions. I hope you enjoyed reading this blog post.

  6. C# switch Statement (With Examples) - Programiz

    The switch statement evaluates the expression (or variable) and compare its value with the values (or expression) of each case (value1, value2, …). When it finds the matching value, the statements inside that case are executed. But, if none of the above cases matches the expression, the statements inside default block is executed. The default ...

  7. C# Switch Statement - TutorialsTeacher.com

    The switch statement can include any non-null expression that returns a value of type: char, string, bool, int, or enum. The switch statement can also include an expression whose result will be tested against each case at runtime. Example: C# Switch Statement. int x = 125; switch (x % 2) {.

  8. C# switch Statement By Practical Examples - C# Tutorial

    First, prompt users to input a number from 1 to 12: Console.Write( "Enter a month(1-12): " ); int month = Convert.ToInt32(Console.ReadLine()); Code language: C# (cs) Second, match the input month number with a number from 1 to 12 using the switch statement and assign the month name accordingly.

  9. Patterns - Pattern matching using the is and switch ...

    Logical patterns. Show 8 more. You use the is expression, the switch statement and the switch expression to match an input expression against any number of characteristics. C# supports multiple patterns, including declaration, type, constant, relational, property, list, var, and discard. Patterns can be combined using Boolean logic keywords and ...

  10. All the ways you can use the switch keyword in C# today">All the ways you can use the switch keyword in C# today

    Up to C# 7. The classic switch statement we are all familiar with: ... You need a separate declaration, every assignment turns out to be at least 3 lines long, including case and break statements.