Jan Schreuder on .Net

.Net code samples, experiences, observations

View my professional profile on LinkedIn

Recent Posts

Tags

News

  • Inappropriate comments will be deleted at my discretion.

    The information and code samples in this weblog is provided "AS IS" without warranty of any kind, either expressed or implied, including but not limited to the merchantability and/or fitness for a particular purpose.

Community

Email Notifications

Tool suppliers

Tools

General

Microsoft

Favorite blogs

Archives

Syntax error? Really?!?!

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?

Comments

Wim said:

Because [s]he doesn't know the correct syntax or workings of the ?: construction ?

Wim

# November 4, 2008 8:04 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 4 and 6 and type the answer here: