Created
May 24, 2022 12:07
-
-
Save lgolubyev/39766ee9d149175cba3b176726095bf2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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