.NET on RHEL

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:

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