Difference of Unary operators ( += , =+ , ++x , x++ )

Prageeth Liyanage picture Prageeth Liyanage · Feb 6, 2015 · Viewed 18.1k times · Source

What is the difference between these unary operators in C# ? . Can you provide me with example?

Please provide the name of each. :)

+= vs =+

++x vs x++

Answer

nxasdf picture nxasdf · Feb 6, 2015

This has no doubt been answered before, but anyway...

They differ in how they change the value and how they return the result.

The first two += and =+ behave in the way that the first increments a variable, the other sets a variable. They are not related. Observe the following code:

// +=
x = 1;
printf( x += 1 ); // outputs 2, the same as x = x+1
printf( x );      // outputs 2

// =+
x = 1;
printf( x =+ 1 ); // outputs 1, the same as x = 1;
printf( x );      // outputs 1

The next two, ++x and x++, differ in the order their function. ++x will increment your variable by 1 and return the result. x++ will return the result and increment by 1.

// ++x
x = 1;
printf( ++x ); // outputs 2, the same as x = x+1
printf( x );   // outputs 2

// x++
x = 1;
printf( x++ ); // outputs 1
printf( x );   // outputs 2

They are mostly useful for for loops and while loops.

In terms of speed, ++x is considered a lot faster than x++ since x++ needs to create an internal temporary variable to store the value, increment the main variable, but return the temporary variable, basically more operations are used. I learned this a looong time ago, I don't know if it still applies