Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

C# 8 pattern matching

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

    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

    • Tekton joins the CNCF as an incubating project

    • Federated identity across the hybrid cloud using zero trust workload identity manager

    • Confidential virtual machine storage attack scenarios

    • Introducing virtualization platform autopilot

    • Integrate zero trust workload identity manager with Red Hat OpenShift GitOps

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.