Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# interface cannot contain operators

Can anyone please explain why C# interfaces are not allowed to contain operators?

Thanks.

like image 961
Jake Avatar asked Jul 06 '11 22:07

Jake


1 Answers

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

like image 75
dkackman Avatar answered Sep 18 '22 12:09

dkackman