How are operator methods static if they operate on instances?

Viewed 41
class Program {
    static void Main() {

        test b=new(2), n = new(5);
        test bh = b + n;

    }
}


class test {
    public test(int h) {
        i = h;
    }

    public int i { get; }

    public static test operator+(test i, test j) {
        return new test(i.i + j.i);
    }
}

How are operator methods static if they operate on instances? I mean I say b+n which clearly are instances.

1 Answers

This is a compiler trick. When it encounters the expression b + n, it first determines that an overloaded operator exists and calls it with test.operator+(b, n). I.e., the instances are passed as parameters to the static method.

Of course, this is an invalid C# syntax, as operator+ is an invalid identifier. In reality, the compiler creates this IL code:

call class test test::op_Addition(class test, class test)

The full Main method:

.method private hidebysig static
    void Main () cil managed 
{
    .maxstack 2
    .locals init (
        [0] class test, // local variable b
        [1] class test, // local variable n
        [2] class test  // local variable bh
    )

    IL_0000: nop

    // test b = new(2);
    IL_0001: ldc.i4.2
    IL_0002: newobj instance void test::.ctor(int32)
    IL_0007: stloc.0

    // test n = new(5)
    IL_0008: ldc.i4.5
    IL_0009: newobj instance void test::.ctor(int32)
    IL_000e: stloc.1

    // test bh = b + n;
    IL_000f: ldloc.0
    IL_0010: ldloc.1
    IL_0011: call class test test::op_Addition(class test, class test)
    IL_0016: stloc.2

    IL_0017: ret
} // end of method Program::Main
Related