Skip to content

Instantly share code, notes, and snippets.

@lgolubyev
Created May 24, 2022 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lgolubyev/39766ee9d149175cba3b176726095bf2 to your computer and use it in GitHub Desktop.
Save lgolubyev/39766ee9d149175cba3b176726095bf2 to your computer and use it in GitHub Desktop.
// 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