|<<>>|5 of 339 Show listMobile Mode

Using extensions for operators in C# 14

Published by marco on

The article C# 14 Extension Members: Complete Guide to Properties, Operators, and Static Extensions by Laurent Kempe writes,

“Perhaps the most powerful C# 14 capability is extension operators. You can now add user-defined operators to types you don’t control, enabling natural mathematical operations.

When I first saw this, I thought it was kind of gimmick-y. But I just realized why it’s very nice that you can declare operators separately—optionally—from the type. Adding operators by default is a heavy decision in most APIs. You generally don’t do it except for the most obvious cases, like matrices, etc. where there is really only one possible way to implement the standard operators.

However, for a lot of other types, it would be convenient to have these operators but they might be annoying for some. This way, you can either add them in yourself—tailoring the implementation for your needs—or you can pull in a NuGet package that extend standard types with operators. This allows you to opt in to the operators.

With these new extensions, we’re probably going to see more lightweight types that are delivered in multiple NuGet packages, the satellite packages being extensions that enhance the base type for specific scenarios.

The author demonstrates such a custom operator, using tuples.

extension(Point point)
{
    public static Point operator +(Point point, (int dx, int dy) offset) =>
        new Point(point.X + offset.dx, point.Y + offset.dy);
}

// Usage:
Point translated = myPoint + (5, -3);

Nice.