csharp / expert
Snippet
Static Abstract Interface Members
C# 11 introduced static abstract members in interfaces, enabling 'Generic Math'. This allows developers to define static properties or operators that must be implemented by the conforming type. It solves the long-standing limitation where generic types could not perform arithmetic or access static factory methods without complex workarounds or reflection.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public interface IMonoid<T> where T : IMonoid<T>{static abstract T Identity { get; }static abstract T operator +(T left, T right);}public readonly record struct Sum(int Value) : IMonoid<Sum>{public static Sum Identity => new(0);public static Sum operator +(Sum left, Sum right) => new(left.Value + right.Value);}public static class Aggregator{public static T Accumulate<T>(IEnumerable<T> items) where T : IMonoid<T>{T result = T.Identity;foreach (var item in items) result += item;return result;}}
Breakdown
1
static abstract T Identity { get; }
Declares a static contract that implementing types must provide a static 'Identity' property.
2
T result = T.Identity;
Accesses the static member directly from the type parameter T, which was previously impossible in C#.