11 Jun 2015 by K Bonneau
Predict the Output Challenge (C#) - Part 5
Think what would be the output of below code and then run the code to assert if your were correct.
I was surprised when I realized not many people know about the rounding algorithm that the Round function uses. It works as follows:
2. If two numbers are equally near (e.g 10.5 is equally near to 10 and 11), round the number to the nearest even number.
Similarly 2.5 rounds to 2.
While normally we can always cast from int to double, the above code will throw an InvalidCastException exception at runtime. The reason is Cast<T> is defined as an extension method on the non-generic IEnumerable type instead of IEnumerable<T>. As enumerating an IEnumerable enumerates on object types, and casting from object (even if it is an boxed integer) to double is not permitted, the above code will throw an exception.
ALWAYS make sure structs are immutable
The above should be easy to predict, but I have seen several instances, where even experienced programmers introduce bugs due to code like above. When we say point1 = points, we are creating a copy of points and then we change the X property on that copy, leaving points unaffected. If you use structs, always make it a point to make structs immuatable. If you return a struct to a caller, the caller (the programmer) might assume it to be a class, and our brains are wired not to detect any bugs when we see code like above. By making structs immutable, you don't allow the state to be modified avoiding such bugs.
Bonus: Break the Code Puzzle - The Bug that Crashed Azure
In the below snippet, Call the GetExpirationDate() function from Main such that it throws an exception. You are not allowed to change the GetExpirationDate() function and the exception must originate from that function. You can change the Main() function. Similar bug caused Azure to Crash for 2 days.
Read Next: Predict the Output (C#) - Part 6