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# 11: Pattern matching and static abstract interfaces

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

    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

    • Red Hat Hardened Images: Top 5 benefits for software developers

    • How EvalHub manages two-layer Kubernetes control planes

    • 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

    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

    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.