;
vote buttons
98
30 Dec 2014 by K Bonneau

Predict the output challenge (C#)

c#

How good is your C#? Can you predict the output of all the code snippets below? If you get it all wrong don't fret, even the most experienced programmers fumble and get it wrong most of the times. 

Dynamic Mess

The first Console.WriteLine statement displays the type as System.Byte, but magically the type changes to System.Int32 during the second call. Did you get it right? Basically this happens all the time. byte does not have a += operator. So the compiler converts it into Int32 calls the += overload, and converts it back to byte. However if it is a dynamic type, the last step of converting the result back to byte never happens, and the type remains as Int32.

EDIT: I received some comments that the output is Int32 the second time not because of above reasoning, but because we are adding 1 (Int32) to byte. I wrote another snippet to demonstrate that that even if we add a byte value the output still remains the same. Click here to view the snippet

IEnumerable Nuance 

Would the below code print "done!" or throw an exception?

The above code doesn't throw an exception as expected, because no code within the function GetChars() executes until we enumerate.

Captured Variables

Ok, this one is simple and you should get it right.

This will print 5, five times. We execute the actions not inside the loop but after the loop is over and the value of i is 5 for all executions.

Parameter Preference

The output might seem unexpected, but it is as per C# specifications. The value of T inferred as int is a much better match than the function with object parameter.


Comments