;
vote buttons
9
11 Jun 2015 by K Bonneau

Predict the Output Challenge (C#) - Part 5

c#

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:


1. Round the Number to the nearest integer (or to the specified precision).

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.


So 1.5 rounds to 2 as 1 and 2 are both equally near but 2 is an even number.

Similarly 2.5 rounds to 2.


This is called the Banker's Rounding. The reasoning behind this is not to have a bias towards one side (lower if it always chooses the lower nearest number, or higher if it always chooses the higher nearest number). If you take a large set of numbers, round them and take an average, the Banker's Rounding provides a much closer average.

IEnumerable.Cast<T>

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[0], we are creating a copy of points[0] and then we change the X property on that copy, leaving points[0] 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

Comments