C# Coding Style – Using Prefix Incremented Loops

ccoding-style

Back when I started programming in college, a friend encouraged me to use the prefix incrementation operator ++i instead of the postfix i++, citing that there was a slight chance of better performance with no real chance of a downside. I realize this is true in C++, and it's become a general habit that I continue to do.

I'm led to believe that it makes little to no difference when used in a loop in C#, regardless of data type. Apparently the ++ operator can't be overridden. Nevertheless, I like the appearance more, and don't see a direct downside to it.

It did astonish a coworker just a moment ago though, he made the (fairly logical) assumption that my loop would terminate early as a result. He's a self-taught programmer, and apparently never came across the C++ convention. That made me question whether or not the equivalent behavior of pre- and post-fix increment and decrement operators in loops is well known enough.

Is it acceptable for me to continue using ++i in looping constructs because of style preference, even though it has no real performance benefit? Or is it likely to cause confusion amongst other programmers?


  • Note: This is assuming the ++i convention is used consistently throughout all code.

Best Answer

I think you should stick with the conventions that your co-workers are used to. The principle of least surprise. You don't want to sit and figure out why a simple operation is written in an uncommon manner for no reason, so why should the next guy who is reading your code?

Related Topic