Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Interface specifies static properties and operators
interface IAddable<T> where T : IAddable<T>
{
static abstract T Zero { get; }
static abstract T operator +(T t1, T t2);
}
// Classes and structs (including built-ins) can implement interface
struct Int32 : …, IAddable<Int32>
{
// Explicit
static Int32 I.operator +(Int32 x, Int32 y) => x + y;
// Implicit
public static int Zero => 0;
}
// Generic algorithms can use static members on T
public static T AddAll<T>(T[] ts) where T : IAddable<T>
{
// Call static operator
T result = T.Zero;
// Use `+`
foreach (T t in ts) { result += t; }
return result;
}
// Generic method can be applied to built-in and user-defined types
int sixtyThree = AddAll(new [] { 1, 2, 4, 8, 16, 32 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment