csharp / expert
Snippet
Static Abstract Interface Members
Expert use of static abstract members in interfaces. This allows defining polymorphic operators and factory properties that can be called on the type parameter itself in generic logic.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
public interface IMonoid<T> where T : IMonoid<T>{static abstract T Identity { get; }static abstract T operator +(T left, T right);}public record Sum(int Value) : IMonoid<Sum>{public static Sum Identity => new(0);public static Sum operator +(Sum l, Sum r) => new(l.Value + r.Value);}
Breakdown
1
static abstract T operator +
Forces implementing types to provide a static addition operator.
2
where T : IMonoid<T>
Curiously Recurring Template Pattern (CRTP) to ensure type safety in static contexts.