Is it true that for all .NET operator overload methods must be public and static?

Tag: operator-overloading , clr , cls-compliant Author: zhanpinxin Date: 2013-06-25

Quoted from C# From CLR

The CLR specification mandates that operator overload methods be public and static methods.

I checked ECMA-335, but couldn't find any evidence.

So far I know it is true for C# and F#. Is it true for all CLS-compliant language?

It is most certainly mentioned in ECMA-335, chapter I.10.3.1 and 3.2: ` They are represented as static methods on the class`
@HansPassant Thx, found that!

Best Answer

It looks like it's not really required to be public, but making it non-static is problematic at execution time. I experimented by starting with this code:

using System;

class Oddity
    public static Oddity operator+(Oddity x, Oddity y)
        Console.WriteLine("Adding oddities");
        return null;

class Test
    static void Main()
        var x = new Oddity();
        var y = new Oddity();
        var z = x + y;

... and then running it through ildasm, changing things, then using ilasm and running the result.

  • Changing the accessibility modifier to assembly (equivalent to internal): all was fine
  • Changing the accessibility modifier to private: it assembled (which surprised me) but then failed at execution time:

    Unhandled Exception: System.MethodAccessException: Attempt by method 'Test.Main()' to access method 'Oddity.op_Addition(Oddity, Oddity)' failed.
    at Test.Main()

  • Removing the static part: it assembled (again, surprising me) but then failed at execution time:

    Unhandled Exception: System.MissingMethodException: Method not found: 'Oddity Oddity.op_Addition(Oddity, Oddity)'.
    at Test.Main()

I suspect these really should be caught at assembly time, but as languages are only expected to produce operators which are public and static, the validator is a little lax.