'Difference between unary operators ( += , =+ , ++x , and x++)

What is the difference between these unary operators in C#?

What would an example be? What is the name of each?

+= vs. =+

++x vs. x++



Solution 1:[1]

Let's visualize the first ones, += and =+.

Because "+" is action, "=" is assignment, so

+= is to add BEFORE assignment

=+ is a bit confusing with "+", it could be "-", for example a=+7 or a=-7, anyway, it's a direct assignment.

Similarly,

++x is "increment then return"

x++ is "return then increase"

Solution 2:[2]

++x vs x++ are unary operators. ++x means pre increment and x++ means post increment.

int temp;
temp = 1;
Console.WriteLine(++temp); // Outputs 2
temp = 1;
Console.WriteLine(temp++); // outputs 1
Console.WriteLine(temp); // outputs 2

Prefix increment means:

The result of the operation is the value of the operand after it has been incremented.

Postfix increment means:

The result of the operation is the value of the operand before it has been incremented.

Now the following: += means temp += 10; // same as temp = temp + 10;

This =+ isn't a valid operator. If one does this:

str = + str;  // will throw an error.
int a;
a = +2; // sort of meaningless . 2 and +2 means same.

More here: Is there such thing as a "=+" operator?

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/increment-operator

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Gauravsa