Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat 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
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud 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

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • 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# 11: Pattern matching and static abstract interfaces

January 2, 2023
Tom Deseyn
Related topics:
.NET
Related products:
Red Hat Enterprise Linux

Share:

    This is the second article of our series about C# 11, the new major version of the C# programming language. The first article discussed new features, including raw strings, required members, and auto-default structs. In this article, we will describe improvements in pattern matching, and then we'll look at static abstract interfaces and how they enable generic math.

    Follow the C# 11 series:

    • Part 1: Raw strings, required members, and auto-default structs
    • Part 2: Pattern matching and static abstract interfaces
    • Part 3: 5 new advanced features improving C# 11

    1. New features in pattern matching

    C# 7 introduced pattern matching. It enables checking if an object instance matches a particular shape, like a type and property values. C# 11 introduces list patterns, which allow matching list elements to patterns.

    In the following example, we match constant patterns with each list element. The list needs three elements for a match: 1, 2, and 3.

    if (integers is [1, 2, 3]) { ... }

    We can introduce a range pattern (..) to match zero or more elements in the list.

    if (integers is [1, .., 3]) { ... }

    With this pattern, we specified the first element must be 1, the last must be 3, and there can be zero or more elements between them with any value.

    It is possible to capture the value of the range by naming it.

    if (integers is [1, .. var middle, 3])

    To capture the range value, the type needs to support either an indexer operator that accepts a Range or a Slice method that takes two int parameters.

    Types like array and span meet these requirements, but List<T> does not. So if numbers is a List<int>, the compiler gives an error like: cannot convert from 'System.Range' to 'int' as it tries to match with the indexer.

    Any existing pattern can be used to match the elements. In the following example, we’re using a property pattern to match with the first element, a discard pattern to ignore the second, and a range pattern to capture the remaining elements.

    if (people is [ { Name: "John" }, _, .. var other]) {  }

    Span to string matching

    When parsing strings, the most efficient way to represent parts of a string is by using the ReadOnlySpan type: it refers to the original string and doesn't make new allocations to represent the substring.

    As part of the parsing, we may want to check that substring against a known set of literal values.

    C# 11 enables matching [ReadOnly]Span<char> against a literal string.

    static HttpVerb ParseHttpVerb(ReadOnlySpan<char> verb) =>
       verb switch
       {
           "GET" => HttpVerb.Get,
           "POST" => HttpVerb.Post,
           ...
           _ => HttpVerb.Unknown
       };

    Note that this pattern is not supported between [ReadOnly]Span<byte> and the C# 11’s UTF-8 string literals, which we’ll cover in the next article.

    2. Static abstract interface members

    Like other object-oriented programming languages, C# has always supported polymorphism where derived classes implement virtual or abstract members of their base classes or interfaces. The member that gets called at runtime depends on the actual type of the instance.

    C# 10 introduced static abstract interface members. This gives us polymorphism where the method called depends on the compile-time type rather than the runtime instance type.

    The interface members describe the required members for a type, and generic algorithms can be written that work against all types that implement the interface. At compile-time the type used with the algorithm is known so there is no runtime cost.

    For example, we can describe types that need a factory method as follows:

    interface IFactory<T> where T : IFactory<T>
    {
       static abstract T Create();
    }

    Note the recurring pattern. The type that implements the interface is a generic parameter (<T>), so we can use it when defining the static members. And a where clause indicates T implements the interface.

    Similar to default interface methods (added in C# 8), we can also add static virtual members that have a default implementation. Thanks to the where constraint on T these methods can call the other static members defined by the interface.

    The following method uses the interface we’ve just defined to create an object.

    T CreateObject<T>() where T : IFactory<T>
    {
       return T.Create();
    }

    Types that implement the interface need to provide the static members it defines.

    class MyClass : IFactory<MyClass>
    {
       public static MyClass Create() => new MyClass();
    }

    We can now call CreateObject with this type.

    var instance = CreateObject<MyClass>();

    The following section describes how this powers .NET 7’s generic math feature.

    How static abstract interfaces enable generic math feature

    Built on the static abstract interface members described in the previous section, .NET 7 comes with a set of interfaces in System.Numerics that describe numeric types. Though this is not a C# feature, we’ll look at it as an interesting use case of static abstract members.

    Let’s take a closer look at two of these interfaces:

    public interface INumberBase<TSelf> : IAdditionOperators<TSelf, TSelf, TSelf>, ...
       where TSelf : INumberBase<TSelf>?
    {
       static abstract TSelf One { get; }
       ...
    
    public interface IAdditionOperators<TSelf, TOther, TResult>
       where TSelf : IAdditionOperators<TSelf, TOther, TResult>?
    {
       static abstract TResult operator +(TSelf left, TOther right);
       ...

    The INumberBase type is a base interface. In the code snippet, you can see it has a member named One that represents the value of 1 for the type. The type supports operations also described as interfaces, like the IAdditionOperators which defines the + operation. A generic algorithm can require these granular interfaces on the generic type, allowing it to work with a larger set of types.

    C# base numeric types such as int and double implement these interfaces.

    public struct Int32 : ISignedNumber<int>, IMinMaxValue<double>, ...
    
    public struct Double : IBinaryFloatingPointIeee754<double>, , IMinMaxValue<double>, ...

    Both of these types implement the INumberBase<T> we’ve shown earlier (and INumber<T>, which we’ll use next).

    Before C# 11, there was no way to write an algorithm that worked against int and double. Thanks to these interfaces, we can now do that:

    Add(1, 2);
    Add(1.0, 2.0);
    
    T Add<T>(T lhs, T rhs) where T : INumber<T>
      => lhs + rhs;

    Checked mathematical operators

    C# 11 supports implementing separate checked and unchecked variants of mathematical operators to provide the generic math feature. As a reminder: unchecked means the operator doesn't throw when the result can't be represented (like with an overflow), and conversely checked means it throws.

    A separate checked operator can be defined using the checked keyword as follows:

    public static T operator +(T lhs, T rhs) {...}
    public static T operator checked +(T lhs, T rhs) {...}
    … // similar for other operators.

    By default, C# projects are unchecked, so if you’re implementing a checked operator, you may want to enable checking by wrapping the code in a block with the checked keyword. Then it applies to the operators you use in the implementation method.

    C# 11 new features: More to come

    In this article, we looked at the new features in pattern matching. We also described how static abstract members enable type-level polymorphism and how they enable the generic math feature. Learn more about the new features of C# 11 in the final article in this series. Please comment below if you have questions. We welcome your feedback.

    Last updated: August 14, 2023

    Related Posts

    • C# 11: Raw strings, required members, and auto-default structs

    • Build Your "Hello World" Container Using C#

    • .NET 7 now available for RHEL and OpenShift

    Recent Posts

    • Migrating Ansible Automation Platform 2.4 to 2.5

    • Multicluster resiliency with global load balancing and mesh federation

    • Simplify local prototyping with Camel JBang infrastructure

    • Smart deployments at scale: Leveraging ApplicationSets and Helm with cluster labels in Red Hat Advanced Cluster Management for Kubernetes

    • How to verify container signatures in disconnected OpenShift

    What’s up next?

    Ready to level up your Linux knowledge? Our Intermediate Linux Cheat Sheet presents a collection of Linux commands and executables for developers and system administrators who want to move beyond the basics.

    Get the cheat sheet
    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