Morteza
Morteza

Reputation: 341

Difference between a+=1 and a=a+1 in C#

I found out that in C# a+=1 is not equal to a = a+1.

For example, the following code compiles without any error: byte b = 10; b += 5;

while the following code has a compilation error: byte b = 10; b = b + 5;

Can somebody let me know why?

Upvotes: 1

Views: 8077

Answers (3)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

Because b += 5 is compiled as if it read b = (byte)(b + 5). The cast takes care of the conversion to the proper type, so there is no error.

Upvotes: 1

joshuahealy
joshuahealy

Reputation: 3569

The compiler is probably treating the 5 as an Int32 in the second one. You'll need to cast it

Upvotes: 0

manojlds
manojlds

Reputation: 301347

Because b + 5 becomes an integer ( Int32) ( mainly because there is possibility of overload)

And the compound assignment specification states below:

Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.

Upvotes: 7

Related Questions