Overloading the ++ and -- operators in c#
Asked Answered
P

3

5

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?

Photocompose answered 5/11, 2009 at 4:13 Comment(0)
B
13

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.

Bebe answered 5/11, 2009 at 4:21 Comment(1)
Though this explanation clearly expresses the general concept of postfix decrement, it's at odds with EricLippert's detailed explanation of prefix & postfix operators (see https://mcmap.net/q/87822/-what-is-the-difference-between-i-and-i-in-c). If Eric is to be believed, Function(oldValueOf_y) is called AFTER the variable known as y is decremented. What is passed to Function() is a copy of y before it was decremented. Thus it would seem that in C#, just as in C++, the semantics of postfix increment/decrement prevent obvious optimizations that the compiler may be able to make with prefix increment/decrement.Espionage
O
1

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;
Opuscule answered 5/11, 2009 at 4:27 Comment(0)
D
0

It doesn't matter. In the context of the variable being operated on, there's no difference between the prefix and postfix operators. It's only in the context of the calling code that the difference matters.

Depose answered 5/11, 2009 at 4:19 Comment(1)
so it just uses the same "increment" operator, doesn't matter if it's post or pre increment?Photocompose

© 2022 - 2024 — McMap. All rights reserved.