C# interface cannot contain operators
Can anyone please explain why C# interfaces are not allowed to contain operators?
Thanks.
C# operators have to be static. Interfaces, by definition, apply to instances. There is no mechanism to require a type to implement static members.
EDIT:
Since C# 8.0, as you can see here, it is now possible to define local methods in interfaces and implement them within the interface itself, e.g. allowing to create method overloads without requiring implementations to care about those overloads as well, when they might just supply an additional parameter to the overload that has to be implemented.
Along with this, you can also define operators within interfaces, though they must be static and so they must be implemented in the interface.
So in C# 8.0 this will print "this works in C# 8" followed by "1":
interface ICanAdd
{
int Value { get; }
public static int operator+ (ICanAdd lvalue, int rvalue)
{
Console.WriteLine("this works in C# 8");
return lvalue.Value + rvalue;
}
}
class Add : ICanAdd
{
public int Value => 0;
}
class Program
{
static void Main(string[] args)
{
ICanAdd foo = new Add();
var x = foo + 1;
Console.WriteLine(x);
}
}
Edit 2020-01-23
You cannot add conversion, equality or inequality operators to interfaces, otherwise you'll hit the following error:
CS0567 C# Interfaces cannot contain conversion, equality, or inequality operators
You can't define operators on interfaces because a class can implement multiple interfaces. Imagine if this code were possible:
static class Fooness {
public static operator==(IFoo l, IFoo r) { ... }
}
static class Barness {
public static operator==(IBar l, IBar r) { ... }
}
public class Foobar : IFoo, IBar { ... }
Which == implementation should prevail if used on instances of Foobar? (And before you answer, imagine if IFoo/Fooness come from one DLL and IBar/Barness comes from another).
Even if you could somehow resolve that ambiguity, we should ask ourselves whether it would even be a good idea. I hope the above shows that with operator== it's a seriously bad idea. The author of the per-interface == operator presumes that the only important aspects of an object when it comes to comparison are those encompassed by the interface. Sometimes that can be true, but it's not generally true.
That's why it's prudent to only use operators on sealed classes. Only then can you be sure that your operator knows enough about the object to work correctly.