01 Feb 2016 by K Bonneau

Predict the Output Challenge (C#) - Part 1

Predict the Output Challenge (C#) - Part 2

Predict the Output Challenge (C#) - Part 3

Predict the Output Challenge (C#) - Part 4

Predict the Output Challenge (C#) - Part 5

Postfix Increments

How well do you know about postfix increments? Try to predict the output of the following snippet, then hit run to test your assumption:

Well that was easy, isn't it? Here is another one hopefully a bit more challenging, before we move on to the explanations:

Let's first understand how postfix increment/decrement operators work.

A statement x++ gets translated to roughly the following statements:

temp = x; x = temp + 1; return temp;

So when you say someVariable = x++, value of x is incremented first, then the assignment to someVariable happens. But the value assigned to someVariable is the old value before x was incremented, as the statement returns the old value of x (stored in temp) instead of x itself. Important thing to note is that the value of x is already incremented when the assignment to someVariable happens.

Lets analyze the statement data[i++] = data[i] + 10 from the first problem

// i is 1 here data[i++] // i++ increments i to 2 and returns 1 => data[1] = data[i] // i is 2 => data[2] whose value is 3 + 10 // 13

So the above translates to: data[1] = data[2] + 10 = 33

Based on similar reasoning, the second example should now be clear.

Finicky Compiler

What's wrong with the snippet below?

It doesn't compile! To fix it try removing the brackets around i++ and it should work. Nothing much to explain here. The compiler thinks that the statement (x++) is stupid, and likely you missed something.

Immuatable Optimizations

This one is very simple. Go ahead and give it a try:

Both x, y & string.Empty are exactly the same objects. Interning not just happens on compile time strings, but also empty strings constructed using string constructor with empty char array.



