Extension operator overloading in C# 14

Overloading the pipe `|` operator allows you to customize conversions and give your code more expressive semantics.

With C# 14, it's now possible to define operator overloads through extension members, even for types you don't own, such as string.

For example:

CSHARP
quot;{left} | {right}"; } } }" aria-label="Copiar código"> Copiar
public static class StringExtensions
{
    extension(string)
    {
        public static string operator |(string left, string right)
        {
            return $"{left} | {right}";
        }
    }
}

The example itself isn't particularly useful—the interesting part is what it enables.

One idea I find interesting is combining this feature with an enum to build a pipe conversion API (or whatever name it ends up having).

CSHARP
string md5 = "name" | FormatAs.MD5;
string sha = "name" | FormatAs.Sha256;
string base64 = "name" | FormatAs.Base64;

The implementation is as straightforward as overloading the operator to accept the enum:

CSHARP
extension(string)
{
    public static string operator |(string value, FormatAs format)
    {
        return format switch
        {
            FormatAs.MD5 => ...,
            FormatAs.Sha256 => ...,
            FormatAs.Base64 => ...,
            _ => throw new ArgumentOutOfRangeException()
        };
    }
}

I'm not saying this is the best use case for the feature, but I think it's a good example of how extension operators can make APIs more expressive over existing types, without introducing wrappers or long chains of extension methods.

#extensions #operators