Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

C# 8 pattern matching

February 27, 2020
Tom Deseyn
Related topics:
.NET
Related products:
Red Hat OpenShift

Share:

    In the previous article, we looked at C# 8 asynchronous streams. Another new C# 8 feature is extended support for pattern matching. In this article, we’ll take a look at what was possible with C# 7 and what was added in C# 8.

    C# 7 pattern matching

    Pattern matching is a feature that was introduced in C# 7. It allows you to check whether an object is of a particular type and check its value in a concise way through the use of is patterns and case patterns.

    The is pattern

    The is pattern allows you to check whether a variable is of a certain type, and then assign it to a new variable. Further checks can then be made on that variable:

    if (input is int count && count > 100)
    

    This pattern can also be used to check if a variable is null:

    if (input is null)
    

    This second statement is guaranteed to do a null reference check. When you use == null, the operator== might be overloaded, causing a different check to be performed.

    The case pattern

    The switch statement cases also support patterns. These patterns can include a type check, plus additional conditions:

    switch (i)
    {
        case int n when n > 100:
          ...
        case Car c:
          ...
        case null:
          ...
        case var j when (j.Equals(10)):
          ...
        default:
          ...
    }
    

    In the examples above, you see the case statement for null, default, a type check, conditions, and using conditions without a type check (case var). Note that case var can also match null, so to avoid that happening we’ve placed it below case null.

    The classic switch statement allowed only constants. Because of the dynamic conditions, the order of pattern cases matters.

    C# 8 pattern matching

    C# 8 expands the support for patterns and where they can be used.

    switch expressions

    A switch expression is a concise way to return a specific value based on another value:

    var rgbColor = knownColor switch
    {
        KnownColor.Red   => new RGBColor(0xFF, 0x00, 0x00),
        KnownColor.Green => new RGBColor(0x00, 0xFF, 0x00),
        ...
        _                => throw new ArgumentException(message: "invalid enum value", paramName: nameof(knownColor)),
    };
    

    A regular switch does not return a value. This syntax is more concise. There are no case keywords, and the default case was replaced with a discard (_).

    The case conditions can be patterns. It’s not possible to include statements for handling a case. For each case, a single expression must be provided that represents the resulting value. This expression can be a switch expression.

    It's also possible to start from multiple input values by collecting them into a tuple:

    public decimal GetDiscount(CustomerType customer, DiscountPeriod period)  =>
        (customer, period) switch
        {
            (CustomerType.Gold,   DiscountPeriod.Christmas)  => 0.2m,
            (CustomerType.Silver, DiscountPeriod.Christmas)  => 0.1m,
            (_,                   DiscountPeriod.Christmas)  => 0.05m,
            (_, _)                                           => 0m,
        };
    

    The conditions for the switch are now also tuples. Their items have patterns that are matched against the corresponding input tuple element. In the example, we've used the discard (_) to ignore a tuple item. Other patterns can also be used.

    The is keyword can also be used with tuple patterns.

    Tuple patterns can also be used against types that are deconstructable to a tuple:

    static Sector GetSector(Point point)  => point switch
    {
        (0, 0) => Sector.Origin,
        (2, _) => Sector.One,
        var (x, y) when x > 0 && y > 0 => Sector.Two,
        (1, var y) when y < 0 => Sector.Three,
        _ => Sector.Unknown
    };
    

    Property patterns

    Property patterns express a property that needs to have a specific constant value:

    switch (location)
    {
       case { State: "MN" }:
          ...
    }
    

    The above case will match when location.State equals MN. Property patterns can be used in switch expressions also.

    A special case is the { } pattern, which means: not null. This pattern can also be used with the is keyword:

    if (location is { State: "MN" })
    

    We can check both on the type and property, for example:

    switch (vehicle)
    {
        case Taxi { Occupants: 2 } t:
          ...
    }
    

    Conclusion

    In this article, we’ve looked at C#’s support for pattern matching. Pattern matching provides us with a concise syntax match against a type, checks properties, and combines these patterns with additional conditions. In the next article, we'll explore the enhancements for C# 8's default interface methods.

    C# 8 can be used with the .NET Core 3.1 SDK, which is available on Red Hat Enterprise Linux, Fedora, Windows, macOS, and other Linux distributions.

    Last updated: March 29, 2023

    Recent Posts

    • AI meets containers: My first step into Podman AI Lab

    • Live migrating VMs with OpenShift Virtualization

    • Storage considerations for OpenShift Virtualization

    • Upgrade from OpenShift Service Mesh 2.6 to 3.0 with Kiali

    • EE Builder with Ansible Automation Platform on OpenShift

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue