Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int x = 10; x += x--; in .Net - Why?

Tags:

operators

c#

.net

int x = 10; x += x--; 

In C#/.Net, why does it equal what it equals? (I'm purposely leaving the answer out so you can guess and see if you're right)

like image 304
Tom Ritter Avatar asked Feb 19 '10 20:02

Tom Ritter


People also ask

What does <> mean in C#?

It is a Generic Type Parameter. A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.

What does i ++ mean in C#?

For example, in the statement "v=i++", where the operator is in the postfix form, the value of "i" is assigned to "v" before the increment operation. In the statement "v =++i", where the operator is in the prefix form, the value of "i" is incremented first before being assigned to "v".

What is the use of in C#?

operator returns the left-hand operand if it is not null, or else it returns the right operand.


1 Answers

Look at this statement:

x += x--; 

This is equivalent to:

x = x + x--; 

Which is equivalent to:

int a1 = x; // a1 = 10, x = 10 int a2 = x--; // a2 = 10, x = 9 x = a1 + a2; // x = 20 

So x is 20 afterwards - and that's guaranteed by the spec.

What's also pretty much guaranteed, although not by the spec, is that anyone using such code will be attacked by their colleagues. Yes, it's good that the result is predictable. No, it's not good to use that kind of code.

like image 70
Jon Skeet Avatar answered Sep 20 '22 08:09

Jon Skeet