क्रिश्चियन शॉ
  • होम
  • Blog
    • प्रोग्रामिंग
      • C#
      • पॉवरशेल
      • Python
      • SQL
    • वर्डप्रेस
      • ट्युटोरियल
    • क्लाउड
    • होम ऑटोमेशन
      • होम असिस्टेंट
        • Node-Red
    • Career
  • सेवाएं
  • शब्दकोष
  • About
No Result
View All Result
क्रिश्चियन शॉ
  • होम
  • Blog
    • प्रोग्रामिंग
      • C#
      • पॉवरशेल
      • Python
      • SQL
    • वर्डप्रेस
      • ट्युटोरियल
    • क्लाउड
    • होम ऑटोमेशन
      • होम असिस्टेंट
        • Node-Red
    • Career
  • सेवाएं
  • शब्दकोष
  • About
No Result
View All Result
क्रिश्चियन शॉ
No Result
View All Result
Home प्रोग्रामिंग C#
pattern matching in switch

How to do pattern matching in switch statements – C# version >= 7.0

by ईसाई
2022-11-जुलाई
in C#
0

This is not a new feature, pattern matching in switch statements has been around since C# 7.0. I got a question the other day from a co-worker about how I would do pattern matching when working with a switch. I told him to consider it a mix of a switch and if statements (this way we can avoid nesting both of them). I thought it would be a good idea to make an article showing how it’s done.

In this article, I will teach you how to do pattern matching in switch statements and briefly what the C# compiler produces when processing switch statements. If you are ready – let’s get started.

विषय-सूची
  1. Video Tutorial for Article
  2. How does a C# switch work?
  3. What is break in a C# switch?
  4. What is default in a C# switch?
  5. How to do pattern matching in switch statements?
    • Testing pattern matching in switch statements
  6. Summary

Video Tutorial for Article

I normally use the switch statement to select one of many code blocks to be executed. First, let’s have a look at what a normal switch statement looks like.

switch(expression) 
{
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
    break;
}

How does a C# switch work?

I have sliced the functionality of a switch statement into four steps, below:
1. The switch expression is evaluated once
2. The value of the expression is compared with the values of each case
3. If there is a match, the associated block of code is executed
4. The break and default keywords will be described later in this article
The example above would evaluate the expression and choose a case depending on a match from one of the matches.

What is break in a C# switch?

When your C# code reaches the break keyword, it will break out of the switch block. When it breaks out, no more execution will be done in terms of case testing inside the switch block. When your code finds a match to its expression, it will take a break. By using breaks you can save yourself a lot of execution time because it simply ignores the execution of the rest of your code inside the switch block.

What is default in a C# switch?

The default keyword in a C# switch is optional and specifies some code to run if your expression doesn’t match any case in your switch block.

How to do pattern matching in switch statements?

C# 7.0 were the version of C# to introduce a new concept allowing us to do pattern matching (inline kind of like if statements). In the example below I have made a switch to tell me if a rectangle is a square because length and width are equal. The switch will take a Shape as a parameter. A shape can be a circle, rectangle, triangle, etc…

public void DefineShape(Shape shape)
{
  switch (shape)
    {
        case Rectangle s when (s.Length == s.Height):
            Console.WriteLine($"{s.Length} x {s.Height} is not a rectangle, but a square.");
            break;
        case Rectangle r:
            Console.WriteLine($"{r.Length} x {r.Height} is a rectangle.");
            break;
       case Circle c:
            Console.WriteLine($"Circle with area of {Math.PI * c.Radious * c.Radious}.");
            break;
      case Triangle t:
            Console.WriteLine($"Triangle with area {(t.Height * t.Width)/2}cm2.");
        default:
            Console.WriteLine("Unknown shape, please try agian.");
            break;
        case null:
            Console.WriteLine("Provided shape is null");
            break;
    }
}

The first case is including a when keyword (an if statement). When we add the when keyword to our case, we can add constraints to our cases. As you can see it’s possible to give the switch one rectangle but get two different case matches.

If the shape got equal length and width the first case will give a match and break out of the switch block. If not we will continue to the next rectangle case and show the length and along with a small text in the console. If we switched the ordering of the two cases, the first case would evaluate to a match and break out of the switch block, giving us a wrong result. Please be careful when adding your cases as they can end up matching with the wrong case if you are using the when keyword.

I also introduced the optional keywords default and null. If we receive a shape that we don’t recognize, we will return a message showing the requester that we don’t know that shape. If the provided shape is null, the last case will be a match.

Testing pattern matching in switch statements

To make sure the switch above works as expected, I have made a small test showing the different outputs.

PatternMatching.DefineShape(new Circle
  {
    Radius = 6
  });

// Output: "Circle with area of 113.097335529233"

PatternMatching.DefineShape(new Rectangle
  {
    Length = 4,
    Width = 4
  });

// Output = "4 x 4 is not a rectangle, but a square."

PatternMatching.DefineShape(new Trapeze());
// Output: "Unknown shape, please try agian."

PatternMatching.DefineShape(null);
// Output: "Provided shape is null"

As you can see the switch will do its pattern matching and match the shape on the right case.

Summary

Pattern matching in switch statements has been here for a while (since C# 7.0). It’s a great feature I use to write cleaner code as I don’t have to nest a lot of if statements. When using the pattern matching feature, we have to keep in mind that the order of the case statements is very important.

When you add the default clause in a switch you can do it where you want, because it will always be evaluated last no matter its location in the switch. I hope you learned something new and now are able to use pattern-matching switch statements in your own applications. If you got any questions, please let me know in the comment. Until next time – Happy coding!

Tags: .NET 5.0.NET 6.Net CoreC#C# 7.0DevelopmentPattern MatchingSwitch
Previous Post

C# Tuple – How to use Tuples in C#

Next Post

SQL Views – A Complete 101 guide to work with SQL Views

ईसाई

ईसाई

Hello 👋 My name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Related Posts

watchdog
ASP.NET Core

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

by ईसाई
2022-13-अगस्त
0

A reader recently asked me for a more modern way to view log files for requests and exceptions in a...

Read more
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

2022-25-जुलाई
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

2022-23-जुलाई
Dockerize ASP.NET Core

How to Compose an ASP.NET Core Web API (.NET 6) with an MS SQL Server 2022 on Linux in Docker

2022-19-जुलाई
tuple, c# tuple, tuples

C# Tuple – How to use Tuples in C#

2022-6-जुलाई
Next Post
sql views

SQL Views - A Complete 101 guide to work with SQL Views

प्रातिक्रिया दे जवाब रद्द करें

आपका ईमेल पता प्रकाशित नहीं किया जाएगा. आवश्यक फ़ील्ड चिह्नित हैं *

क्रिश्चियन शॉ

क्रिश्चियन शॉ

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website
Career

Top 6 things to add on your personal website to get hired for a tech job

by ईसाई
2022-7-अगस्त
0

Back in the days before the internet was a thing like it is today, we used to have business cards...

Read more
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

2022-13-अगस्त
get hired for a tech job

5 tips to help you get hired for a tech job

2022-31-जुलाई
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

2022-25-जुलाई
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

2022-23-जुलाई

क्रिश्चियन शॉ

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website

Top 6 things to add on your personal website to get hired for a tech job

2022-7-अगस्त
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

2022-13-अगस्त
get hired for a tech job

5 tips to help you get hired for a tech job

2022-31-जुलाई
  • hi_INहिन्दी
    • da_DKDansk
    • en_USEnglish
    • de_DEDeutsch
    • pt_BRPortuguês do Brasil
  • Contact
  • गोपनीयता नीति
  • सेवा की शर्तें

© 2022 क्रिश्चियन शॉ - All rights reserved.

No Result
View All Result
  • होम
  • Blog
    • प्रोग्रामिंग
      • C#
      • पॉवरशेल
      • Python
      • SQL
    • वर्डप्रेस
      • ट्युटोरियल
    • क्लाउड
    • होम ऑटोमेशन
      • होम असिस्टेंट
    • Career
  • सेवाएं
  • शब्दकोष
  • About

© 2022 क्रिश्चियन शॉ - All rights reserved.

मैं आपकी वरीयताओं को याद करके और बार-बार आने वाली यात्राओं को याद करके आपको सबसे अधिक प्रासंगिक अनुभव देने के लिए अपनी वेबसाइट पर कुकीज़ का उपयोग करता हूं। “स्वीकार करें” पर क्लिक करके, आप सभी कुकीज़ के उपयोग के लिए सहमति देते हैं।
मेरी निजी जानकारी न बेचें.
कुकी सेटिंगACCEPT
गोपनीयता और कुकीज़ नीति

गोपनीयता अवलोकन

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
CookieDurationDescription
__gads1 year 24 daysThe __gads cookie, set by Google, is stored under DoubleClick domain and tracks the number of times users see an advert, measures the success of the campaign and calculates its revenue. This cookie can only be read from the domain they are set on and will not track any data while browsing through other sites.
_ga2 yearsThe _ga cookie, installed by Google Analytics, calculates visitor, session and campaign data and also keeps track of site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognize unique visitors.
_ga_0J2F6JVWSD2 yearsThis cookie is installed by Google Analytics.
_gat_gtag_UA_84232734_11 minuteSet by Google to distinguish users.
_gid1 dayInstalled by Google Analytics, _gid cookie stores information on how visitors use a website, while also creating an analytics report of the website's performance. Some of the data that are collected include the number of visitors, their source, and the pages they visit anonymously.
YouTube2 yearsYouTube sets this cookie via embedded youtube-videos and registers anonymous statistical data. I embed YouTube videos in my articles/tutorials - you won't get the full experience of the articles if this is deactivated.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
CookieDurationDescription
IDE1 year 24 daysGoogle DoubleClick IDE cookies are used to store information about how the user uses the website to present them with relevant ads and according to the user profile.
test_cookie15 minutesThe test_cookie is set by doubleclick.net and is used to determine if the user's browser supports cookies.
VISITOR_INFO1_LIVE5 months 27 daysA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.
YSCsessionYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.
yt-remote-connected-devicesneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
yt-remote-device-idneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Powered by CookieYes Logo