In my current project, we have adopted Microsoft StyleCop as a tool to make sure everyone sticks to the same style of coding. One of the things we currently incorporate in our daily work is making sure our existing code conforms to the rules we agreed on. Today however, StyleCop refused to check a class because of a syntax error in the following line of code:
double fraction = totalStaff > 0
? fraction = (double)completed / (double)totalStaff
: fraction = 0;
The code you see here is part of a calculation to get the percentage of users that have completed a certain training module. The compiler sees no problem, and the result is as you would expect. But looking at the code, you do see something really weird. The variable fraction is always assigned twice. Maybe not a syntax problem, but strange and not necessary.
The following code does the same and only assigns the value once.
double fraction = totalStaff > 0
? (double)completed / (double)totalStaff
: 0;
So why would someone do it twice?