Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading the ++ and -- operators in c#

Tags:

c#

.net

reflector

It appears in C# you can not override the post decrement operator?

I was "reflectoring" and ran across some code that reflector translated to decimal.op_Decrement(x) and I was trying to figure out whether it meant --x or x--.

public struct IntWrapper
{
    public static IntWrapper operator --(IntWrapper value)
    {
        return new IntWrapper(value.value - 1);
    }

    public static IntWrapper operator (IntWrapper value)--
    {
        ???
    }

    private int value;

    public IntWrapper(int value)
    {
        this.value = value;
    }
}

Does the framework just use the "pre-decrement" version for the "post-decrement" operation?

like image 774
David Avatar asked Nov 05 '09 04:11

David


2 Answers

Postfix ++/-- operator is the same as it's prefix counterpart, except the first creates a copy (if needed) of the variable before assigning.

So, this code:

int x = Function(y--);

Is equal to this code:

int x = Function(y);
--y;

That's why there is no need to overload the postfix operator.

like image 61
LiraNuna Avatar answered Oct 04 '22 19:10

LiraNuna


Basically, there is no need to make a distinction because:

decimal x = y--;

is equivalent to

decimal x = y;
decimal.op_Decrement(y);

and

decimal x = --y;

is equivalent to

decimal x;
decimal.op_Decrement(y);
x = y;
like image 22
cdmckay Avatar answered Oct 04 '22 18:10

cdmckay