In C/C++,
The compound-assignment operators combine the simple-assignment operator with another binary operator. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand. For example, a compound-assignment expression such as
expression1 += expression2can be understood as
expression1 = expression1 + expression2However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation.
(Quoted from Microsoft Docs)
For example:
- For
i+=2;,iwould be modified directly without any new objects being created. - For
i=i+2;, a copy ofiwould be created at first. The copied one would be modified and then be assigned back toi.
i_copied = i;
i_copied += 2;
i = i_copied;
Without any optimizations from compiler, the second method will construct a useless instance, which degrades the performance.
In C#, operators like += are not permitted to be overloaded. And all simple types like int or double are declared as readonly struct (Does that mean all of structs in C# are immutable in truth?).
I wonder in C#, is there a certain expression to force object be modified (at least for simple types) directly, without any useless instances being created.
And also, is it possible the C#-compiler optimizes the expression x=x+y to x+=y as expected, if there's no side-effect from constructors and deconstructors.