C# return value of (int) +=

In C#, you can use int Previous = x++; to load the value of x, before being incremented, into Previous (Previous=0, x=1). However, int Previous = x += 5 does not behave the same way (Previous=5, x=5).

Is there a suitable shorthand statement to increase an integer by an interval larger than 1, while storing the original variable, that I'm unaware of?

Jon Skeet
people
quotationmark

Is there a suitable shorthand statement to increase an integer by an interval larger than 1, while storing the original variable, that I'm unaware of?

No, there's no general compound post-increment operator.

You could fake it with a method if you really want:

public static int PostIncrement(ref int variable, int amount)
{
    int original = variable;
    variable += amount;
    return original;
}

Then:

int previous = PostIncrement(ref x, 5);

I would personally try to avoid doing this though, just in terms of readability... I pretty much always use compound assignment operators as standalone statements.

people

See more on this question at Stackoverflow