63

I've spent most of the last several years working mainly with C# and SQL. Every programmer I've worked with over that time was in the habit of placing the opening brace of a function or control flow statement on a new line. So ...

public void MyFunction(string myArgument)
{
     //do stuff
}

if(myBoolean == true)
{
    //do something
}
else
{
    //do something else
}

I have always been struck by how space wasteful this is, especially in if/else statements. And I know alternatives exist in later versions of C#, like:

if(myBoolean == true)
    //do something on one line of code

But hardly anyone used them. Everyone did the curly-brace-on-newline thing.

Then I got back into doing JavaScript after a long absence. In my memory, JavaScript developers used to do the exact same curly-brace-newline thing but with all the fancy new libraries and stuff, most developers put the opening brace after the declaration:

function MyJavaScriptFunction() {
    //do something
}

You can see the sense in this, because since using closures and function pointers has become popular in JavaScript, it saves a lot of space and makes things more readable. So I wondered why it wasn't seen as the done thing in C#. In fact, if you try the above construct in Visual Studio 2013, it actually reformats it for you, putting the opening brace on a new line!

Now, I just saw this question on Code Review SE: https://codereview.stackexchange.com/questions/48035/questions-responses-let-me-tell-you-about-you In which I learned that in Java, a language I'm not overly familiar with, it's considered de-rigour to open your curly braces right after the declaration, in modern JavaScript fashion.

I had always understood that C# was originally modelled after Java, and kept to a lot of the same basal coding standards. But in this instance, it seems not. So I presume there must be a good reason: what is the reason? Why do C# developers (and Visual Studio) enforce opening curly brackets on a new line?

35
  • 39
    Convention is simply that.
    – Oded
    Apr 25, 2014 at 13:12
  • 26
    Visual Studio enforces nothing, the code style is configurable. Something needs to be the default. Which default is "better" is bikeshedding of the highest order.
    – Phoshi
    Apr 25, 2014 at 13:13
  • 31
    The brace at the end of the line is the ancient K&R C standard. Kernighan and Ritchie invented the C language when computer displays only had 25 lines (23 if you add header and status lines). That isn't really the case any more, right? What is important is consistency throughout a project. There are also scientific studies showing that the brace on its own line (indented to the same level as the code, in fact) improves code comprehension despite what people think they think of the aesthetics. Apr 25, 2014 at 13:55
  • 13
    C# has always supported evaluating a single line of code after a conditional, by the way. In fact, that's the only thing it does, even now. Putting code in braces after a branching expression just makes that instruction a goto (the compiler creates scope using jmp instructions). C++, Java, C# and JavaScript are all more or less based on C, with the same underlying parsing rules, for the most part. So in that sense, C# is not "based on Java." Apr 25, 2014 at 13:59
  • 20
    As a side note, if(myBoolean == true) makes little sense to me. While we're at it, while not if ((myBoolean == true) == true)?? Just if (myBoolean) and that's enough. Sorry, a pet peeve of mine. Apr 25, 2014 at 14:42

5 Answers 5

81

The brace at the end of the line is the ancient K&R C standard, from Brian Kernighan and Dennis Ritchie's book The C Programming Language, which they published in 1978 after co-inventing the UNIX operating system and the C programming language (C was mostly designed by Ritchie, based on B, which another Bell employee Ken Thompson had adapted from the older BCPL programming language), at AT&T.

There used to be flame wars about "the one true brace style."

So Ritchie created the C language, and Kernighan wrote the first tutorial, when computer displays only showed a few lines of text. In fact, UNICS (later UNIX) development started on a DEC PDP-7, which used a typewriter, printer and paper tape for a user interface. UNIX and C were finished on the PDP-11, with 24-line text terminals. So vertical space was indeed at a premium. We all have slightly better displays and higher resolution printers today, right? I mean, I don't know about you, but I have three 24" 1080p displays in front of me right now. :-)

Also, so much of that little book The C Programming Language is code samples that putting the braces at the ends of the lines instead of on their own lines allegedly saved an appreciable amount of money on printing.

What is truly important is consistency throughout a project, or at least within a given source code file.

There are also scientific studies showing that the brace on its own line (indented to the same level as the code, in fact) improves code comprehension despite what people think they think of the aesthetics. It makes it very clear to the reader, visually and instinctively, which code runs in which context.

if( true )
    {
    // do some stuff
    }

C# has always supported evaluating a single command after a branching expression, by the way. In fact, that's the only thing it does, even now. Putting code in braces after a branching expression just makes that one command a goto (the compiler creates scope using jmp instructions). C++, Java, C# and JavaScript are all more or less based on C, with the same underlying parsing rules, for the most part. So in that sense, C# is not "based on Java."

Summing up, this is a bit of a religious/flame-war issue. But there are studies making it pretty clear that arranging code in blocks improves human comprehension. The compiler couldn't care less. But this is also related to the reason why I never put a line of code after a branch without braces--it's just too easy for me or another programmer to slap another line of code in there later and slip on the fact that it will not execute in the same context with the line right before or after it.

EDIT: Just go look at the Apple goto fail bug for a perfect example of this exact issue, which had very serious real world consequences.

if( true )
    doSomething();

becomes...

if( true )
    doSomething();
    doSomethingElse();

In this case, doSomethingElse() executes every time, regardless of the outcome of the test, but because it is indented to the same level as the doSomething() statement, it's easy to miss. This isn't really arguable; studies back this up. This is a big source of bugs introduced into source code during maintenance.

Still, I'll admit that JavaScript closure syntax looks a little silly with braces on their own lines...aesthetically. :-)

43
  • 16
    The part about blocks in conditionals is slightly misleading. In C, the conditional always has a single statement, but a block (aka compound statement) is a kind of statement. C# follows this precedent. Anyway, conditional evaluation always implies some kind of conditional goto or branching instruction, due to the linear nature of all common instruction sets. A conditional without a block is not qualitatively different from a conditional with a block (except with regards to scoping).
    – amon
    Apr 25, 2014 at 14:44
  • 4
    @Craig, remember, this was at Bell Labs, back when Bell Labs was chartered to "do interesting stuff" that was not necessarily required to be practical for anything. Put smart people in a building, tell them to do some interesting research, move them out of what they do isn't "interesting", and, funny thing, INTERESTING stuff (like transistors and Unix) tends to pop out. DARPA had sort of the same focus, back in the beginning, and they funded a LOT of good work, in the name of basic research. Apr 25, 2014 at 20:21
  • 25
    Please provide references for "... scientific studies showing that the brace on its own line ... ". Without at least two references (otherwise it would be study, not studies), it's just shooting randomly into the air.
    – ErikE
    Jul 17, 2015 at 19:01
  • 8
    @Craig, could you provide some clues how to find those research studies you mentioned? Mar 9, 2016 at 9:27
  • 9
    I second other commenters. Please provide references for "scientific studies" you mentioned. Absence of verifiable sources makes that particular argument lack credibility. Aug 15, 2017 at 0:25
36

The reason C# developers do it is because it is the default setting of the Visual Studio auto-formatter. While this setting can be changed, most people don’t, and thus all developers in a team have to go with the majority.

As for why this is the default in Visual Studio, I don’t know.

11
  • 17
    It's the default in Visual Studio because it was the generally-accepted coding style at Microsoft going way, way back, and in fact on at least some teams at Microsoft the style was not only braces on their own lines, but braces on their own lines and indented. So that is an option in Visual Studio, as well (I personally prefer it). Apr 25, 2014 at 14:58
  • 27
    @Craig: Ewwwwwwwww Feb 14, 2016 at 15:39
  • 7
    @PreferenceBean Hmm. Personally I dislike the K&R style, because the brackets are just lost in noise at the ends of the lines and the text looks clumpy to me, which isn't just an aesthetic preference, but has an actual impact on readability/comprehension. I like vertical whitespace. It was a little different on 12" monitors with 24 lines of text back in the old days when vertical space was precious. Feb 14, 2016 at 23:28
  • 13
    @Craig: That's no excuse for indenting the braces :P Feb 15, 2016 at 0:20
  • 3
    @Craig To make Microsoft employees miserable? Feb 29, 2016 at 20:10
25

As I hypothesized in this answer here - https://softwareengineering.stackexchange.com/a/159081/29029 - I suppose the decision to go with Allman's bracing could be a sign of Pascal heritage, given that Hejlsberg created Delphi before he designed C#. Same as Pascal case for method names.

Personally I believe in following the adage "in Rome do as Romans do". I use Allman's in C#, but K&R in Java. I am so used to it that switching the convention either way is jarring to me.

I believe that some convention diversity is actually beneficial for a "multilingual" developer as it helps to remember which language they're coding in at the moment and makes it easy to differentiate various habits. It's a mental equivalent of muscle memory, so to speak.

11
  • 7
    +1 for the "multilanguage developer" line, actually. I seriously prefer braces on their own lines and indented. However, in work on, for example, ASP.NET (MVC) projects, I find that I like C# with the "right" style, and JavaScript with "JavaScript" style. That's a little tongue-in-cheek, but honestly part of it is that JavaScript's closure syntax is more attractive with the brace at the end of the line. So I'm as much a slave to aesthetics as anyone else... Apr 25, 2014 at 15:10
  • 2
    Interestingly, I use Allman for all brace-block languages. However, I am becoming increasingly interested in what a pre-processing conversion of indents to curly-brace blocks might look like in Java. The "java" code might be extremely clean looking, once I wrapped my pattern recognition mind around it. I think Python might actually have it right: There's really no great reason for braces in a language. Nov 23, 2017 at 3:12
  • 1
    Using whitespace to control program flow is insanity. Python is popular these days, but this aspect of Python has been a little crazy since it first appeared. Dec 9, 2018 at 19:48
  • 2
    @Craig Python fan here, trying to get something done in javascript. Looking at your other answer, and your edit about the goto fail, using the indent to control program flow is what humans naturally want to do, so what you see is what executes. If it's indented wrong it plain doesn't work. Having to decode what those braces mean, whether they actually reflect the indentation, is additional work over and above understanding the program. Indentation is redundant to braces, so why do programmers use it if the braces are useful? Deep nesting is unintelligible in any language. Jus' sayin'.
    – Neil_UK
    Dec 13, 2018 at 6:15
  • 1
    You’re relying on human-invisible characters to control program flow. Tabs and spaces aren’t treated the same. It’s nuts. ;-) More to the point, though is that C-style languages are not Python and never will be, making it dangerous to approach them as if they are. Nor is there universal agreement on the issue, anyway. I completely agree with you re: deep nesting being a problem in any language—no argument here at all. The goto fail bug was not, however, a case of deep nesting. Your arguments are, in summary, making a strong case for including the braces every time. Dec 13, 2018 at 8:02
18

The convention that you associate with Java is the K&R style, or the "One true brace style," and originally comes from C. This page indent-style from the venerable Jargon File shows how old the distinction is.

I've always thought that the Allman style and its variants are a reflection of how the authors think about code, elevating the block delimiters to the level of keywords similar to how some languages use "begin" and "end" around blocks of code.

1
  • I'm under the impression that these days OTBS (one true brace style) also implies never leaving out the braces after control statements, even for single lines of code. See the Apple goto fail bug. Sep 17, 2017 at 16:42
-3

I assume it all started because the work is paid by number of code lines. (Now it is too late for fix). This is the most reasonable explanation to me.

Code is read by coders. I disagree that extra new lines will improve the code comprehension or make it more readable. Especially the cases with "else", "catch", "finally":

}
else
{

Code is not one line, no one is reading single line. The code is functions and function body is readable when it fits in one screen. Extra new lines are not helping. Opposite - it makes the code more un-readable.

The new line separate paragraphs in the books and the articles. The paragraphs are split by the story. That makes it more readable! (Not a simplified rules without meaning like - new line after 'if' and before 'then').

I like the comment from @Neil_UK:

...indent to control program flow is what humans naturally want to do...

...those braces ... actually reflect the indentation...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.