DEV Community

loading...

Which do you prefer, and why?

Zohar Peled
By day, try to work. By night, try to sleep.
・1 min read

Yes, I'm here again with a c# coding style question - and today - between the following different coding styles - which do you prefer and why?

1:

if(condition) single-line-of-code;
Enter fullscreen mode Exit fullscreen mode

2:

if(condition) 
    single-line-of-code;
Enter fullscreen mode Exit fullscreen mode

3:

if(condition) 
{
    single-line-of-code;
}
Enter fullscreen mode Exit fullscreen mode

4:

if(condition) 
    {single-line-of-code;}
Enter fullscreen mode Exit fullscreen mode

5:

if(condition) {single-line-of-code;}
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
jayjeckel profile image
Jay Jeckel

Never 1 or 2, as the braces should always be included. These are just asking for some lazy, distracted, or inexperienced maintenance coder to come along and break the whole thing.

With 4, the opening brace should be aligned with the if, not indented passed it.

In general, 3 and 5 are my preferences, though the lack of proper spacing is bugging me. if is a keyword, not a function, so there should be a space between it and the opening parenthesis. Likewise, there should be a space after the opening brace and before the closing brace.
if (condition) { single-line-of-code; }

Collapse
peledzohar profile image
Zohar Peled Author

Thanks for your answer.
I totally agree with your comment on 1 and two. Personally I like option 3 the best.