C# Static interfaces - Take 2
So here it is.
No I don’t want to do this
The point was not to enable something like this :
int value = ICountable.Count;
Static interfaces have no implementation exactly like interfaces.
With interfaces, you need an instance (usually in a variable or member) to find the actual implementation and call it. With static interfaces, you need a type.
There are two ways to specify a type:
- with its type name (Sample4.Count)
- with a generic type parameter (T.Count)
I was also proposing a way to specify a type for extension methods.
Where it would be useful - operators
The reason why everybody is asking for static members in interfaces is ultimately to have operators in interfaces.
public static interface IArithmetic<T>
static T operator +(T x, T y);
static T operator -(T x, T y);
static T operator *(T x, T y);
static T operator /(T x, T y);
Now you can write generic code like :
public static T Power<T>(this T value, int count) where T : IArithmetic<T>
var result = T.Identity;
for (int i=0;i<count;i++)
result = result*value;
This way, no need for the 20 overloads of Enumerable.Sum, it would work for any type presenting the expected static interface.