locked
Curly Braces in C# RRS feed

  • Question

  • Hello All,

    Learning C# now. I am little confused of curly braces here. Though I know the concept of curly braces like a class should be opened and closed by curly braces, but I am lost in the curly braces used in FOR loops. Can some please help me with examples from their experiences.

    Thanks,

    John

    Tuesday, October 17, 2006 12:21 AM

All replies

  • in the for loop its like its own "block" of code. It helps us for example, us developers, visually to indicate what part of a loop belongs to which. Now I don't know technically in the background if it does something other than say "here is the block of code for this loop here".

    in VB it can be tricky reading sometimes on which for loop belongs to which, in a nested loop, but in C# all we do is remove the curly brace then readd it as it will indicate to us, in the IDE, which one its "closed" off - perhaps you can do this in VB.NET I don't know.

    you can have curly braces in an if..elseif statement also, as well as the using, try {} catch{} blocks etc.... - more if a "block of code for this statement" type thing going on

    Tuesday, October 17, 2006 12:56 AM
  • Hello ahmed,

    Thanks for the support.

    Here is my code,

     int[] nums = new int [5]{10,20,30,40,50};
                   int avg=0;
                   for (int i = 0; i < 5; i++)
                   {

                       avg = avg + numsIdea;

                       Console.WriteLine(avg);
                       Console.WriteLine(numsIdea);
                   }

    If I remove the curly brace from the "FOR" loop then error happens (i is not known at the last Console.Writeline())

    If I put the curly brace everthing is OK. Why is that so?

    Thanks,

    John

    Tuesday, October 17, 2006 1:39 AM
  • Curly braces are used to impart a scope but they are optional. For example



    for (int index; index<12; ++index)
    {
       a++; // Run 12 times
       c++; // Run 12 times
    } // End of the scope of the for

    for (int index; index<12; ++index)
        a++; // Run 12 times (in scope of for)
    c++; // Run once after the for loop ends. (Out of the scope of the for)

     


    The rule is that without curly braces the next statement, not line, is considered within the scope. Hence why the two code statements are acceptable and compile, but the logic is quite different. Same is true with the if statement.

    Use the curly braces to group a session,; but if only one statement is needed, it is not needed.


    if ( ...)
    {
       a++;
    }

     




    if (...)
       a++;

     


    Both are the same. Problems arise when one forgets and removes the braces and expects the second statement to be exceuted with the firsrt...but it is not. When in doubt, place the braces, specially in tricky if statements.
    • Proposed as answer by EmreAydemir Thursday, October 18, 2012 6:40 AM
    Tuesday, October 17, 2006 1:47 AM
    Moderator
  • I know this thread is old, but for others reading, it's pretty simple... Any code construct that has a defined beginning and ending point needs curly braces to delimit those points.

    namespaces begin and end

    classes begin and end

    methods begin and end

    Loops begin and end

    Branching statements AND the branches within them have a begin and end

    etc.

    All these need { at the begin and } at the end.

    DO NOT TAKE ADVANTAGE OF THE OPTIONAL CURLY BRACE "FEATURE" AS IT INVITES BUGS!

    Friday, October 12, 2012 5:44 PM
  • I know this thread is old, but for others reading, it's pretty simple... Any code construct that has a defined beginning and ending point needs curly braces to delimit those points.

    namespaces begin and end

    classes begin and end

    methods begin and end

    Loops begin and end

    Branching statements AND the branches within them have a begin and end

    etc.

    All these need { at the begin and } at the end.

    DO NOT TAKE ADVANTAGE OF THE OPTIONAL CURLY BRACE "FEATURE" AS IT INVITES BUGS!

    You contradict yourself; you say that they are needed and also that they are optional.  They are not *needed* on looping/branching constructs, or even for all methods (they are optional on lambdas).

    As for whether or not you should omit them, that is personal preference.  Some people always add them, regardless of whether they are needed or not; some people never use them unless they have to, and some people (I put myself in this category) make judgement calls on a per-instance basis on whether or not the redundant braces are needed for readability.

    Between whitespace and code indentation (especially with auto-formatting for indentation) it often makes it  clear what the scope of such blocks are.

    Friday, October 12, 2012 6:34 PM
  • There is no contradiction in my statement, if you read it within the context of this thread.

    The original question was asking about curly braces in a for loop. During that discussion, the C# optional curly brace "feature" was brought up.

    My response gave a simple explanation of where curly braces are needed and what they do.Curly braces are required around all the blocks I mentioned, with one exception (which is what I brought up and which is discussed in this thread) which is when the block contains only one statement - - That's the optional curly brace "feature" that I mentioned.

    There is no exception for Lambda's.  If your lambda consists of one statement, you may omit the curly braces, when it doesn't, you can't.

    When your block contains more than one statement, you MUST use curly braces to delimit the block, including lambda's.

    It is general programming practice not to follow some syntactic rules sometimes and not in others.  It invites bugs and hinders the readability of your code. Most experienced developers will tell you (and even Microsoft suggests) not to omit the curly braces in one statement situations because the moment a second statement gets added, there is a good possibility that the curly braces won't get added (as they will now need to be) and the code will not process correctly, which is exactly what the OP was asking about.

    Friday, October 12, 2012 9:36 PM
  • There is no contradiction in my statement, if you read it within the context of this thread.

    Nowhere in your previous reply was there any qualification of "if there are multiple statements" or "to do what you're trying to do" or anything like that. You simply said, "Any code construct that has a defined beginning and ending point needs curly braces to delimit those points."

    My response gave a simple explanation of where curly braces are needed and what they do.  Curly braces are required around all the blocks I mentioned, with one exception (which is what I brought up and which is discussed in this thread) which is when the block contains only one statement - - That's the optional curly brace "feature" that I mentioned.

    There is no exception for Lambda's.  If your lambda consists of one statement, you may omit the curly braces, when it doesn't, you can't.

    When your block contains more than one statement, you MUST use curly braces to delimit the block, including lambda's.

    First off; the quoted section includes qualifications you didn't include in your previous reply; those qualifications are essential to the correctness of your point.

    Next, you can think of all loop/branching constructs entirely independently from curly braces.  Each of those constructs simply apply to the following statement.  An if block evaluates an expression; if true it executes the following statement, if not, it doesn't.  A `for` loop executes the first parameter statement once, and then while the second parameter statement evaluates to true it executes the statement that follows the `for` loop followed by the third parameter statement.  A while loop evaluates the expressions and, if true executes the following statement and then returns to the start of the while loop.  

    Then, independently of considering each of those constructs, you can say that any number of statements (from 0 to N) can be combined into a single statement by surrounding them by curly braces.  This can be done anywhere a statement would be expected.

    By combining these two statements you can say that any loop/branching construct is *always* followed by *exactly one* statement.  That statement may simply involve executing multiple other statements as a result.

    None of that is true for namespace, class, method, or inline delegate definitions.  All of those constructs must be followed by curly braces and cannot simply be followed by a single statement.

    Now we move onto thinking from another perspective.  If you, as a programmer, would like to execute multiple statements after an `if` how can you do it?  Well, one way is to use curly braces to make a single statement that executes the multiple statements that you really want to execute.  Another way is to create a method that performs the multiple statements, since calling that one method will require only a single statement.

    It is general programming practice not to follow some syntactic rules sometimes and not in others.  It invites bugs and hinders the readability of your code. Most experienced developers will tell you (and even Microsoft suggests) not to omit the curly braces in one statement situations because the moment a second statement gets added, there is a good possibility that the curly braces won't get added (as they will now need to be) and the code will not process correctly, which is exactly what the OP was asking about.

    I would simply say that I don't ever follow the rule, "Always add curly braces after loop/branch constructs".  I know *many* developers that also don't (ever) follow that rule.  I, and many others, instead follow the rule, "Use curly braces around loop/branch constructs when it results in simpler code, or when it improves the readability of that statement."  Note that "when it improves the readability of that statement" is not equal to "always".  That is a (more complex) rule that I *always* follow.

    I also disagree with your reasoning.  I know that the concern you've voiced is of virtually no concern to me as a programmer, nor many other programmers I know.  Fist off, I will usually only omit curly braces at times where it's clear, logically, that there will only ever be one statement that needs to be executed, and that the code would need to fundamentally change for another to need to be added.  Next, if you are adding a statement to such a construct it is usually quite clear whether or not it's using braces to start with.  When braces are omitted it should be because the block is very small, easy to digest, etc.  When adding to such a construct it's a "big" change, and adding braces is simply something you need to think about.  As for "missing" it or not realizing that it's not part of the construct, as I said in my previous reply, code formatting/indention takes care of that.  If you have an `if` without braces and add a statement that statement will have one less indent than the line above it.  That *really* stands out to the eye; it is such attention getters that make it  *very* hard not to notice that something is wrong.  It's one of the reasons why I press the auto-format-document keyboard shortcut *very* frequently.  It's a great way to notice problems such as that, or missing parenthesis/braces/brackets/semi-colons or other types of errors.

    Friday, October 12, 2012 10:26 PM
  • All I can say is that your problem with my reply about "including qualifications that weren't in my first reply" is that you read my reply in isolation from the rest of the thread when the optional curly brace was first mentioned.

    My reply boils the entire issue down to a simple explanation and simple rules to follow the requirements without ever having a problem.

    Your opinion as to whether you use them may be fine for you, but ignoring the optional curly brace "feature" is a well-known best practice, advocated by even Microsoft and, although you have chosen not to use them in certain cases, you are the exception to this practice, not the rule.

    In any programming language, the tried and true rule of "follow a consitent usage of the language's syntax" is always considered best. It's best for you, it's best for the people who have to support your code (because what was "clear" to you isn't necessarially going to be for them) and it's best to avoid bugs.

    As for the IDE automatically indenting upon changes, yes that's a nice feature, but again we shouldn't be relying on the IDE to structure our code in a scalable way.  YOU may pick up on the indentation, but other less-experienced developers may not.

    In the end, you have to ask yourself if the practice that you are following adds or detracts from the overall quality of the code.  Omitting curly braces will NEVER add to the quality of your code, but it will certainly add a level of inconsistency and the possibility of bugs, where if you just add them all the time, the entire issue goes away.

    Say what you will, but this is not my opinion, it is a well-known and documented practice across many programming paradigms.

    Here is a resouce you may or may not be familiar with that analyzes code for consistency:

    http://stylecop.codeplex.com/

    ...And here's what it has to say about optional curly braces.

    http://stylecop.soyuz5.com/SA1503.html

    ...and they are hardly the minority voice on this topic.

    • Edited by Scott M. _ Friday, October 12, 2012 11:22 PM
    Friday, October 12, 2012 10:47 PM
  • All I can say is that your problem with my reply about "including qualifications that weren't in my first reply" is that you read my reply in isolation from the rest of the thread when the optional curly brace was first mentioned.

    Your reply should be correct in isolation. If you're going to make a statement that is only valid in response to another statement you should reference that statement. You didn't quote it, you didn't mention it, etc. You shouldn't rely on other people filling in blanks for your statements to be valid; they should just be valid. Fortnunetly you actually corrected that mistake when prompted. I'm not sure why you are so intent on saying that omiting imprtant grammatical details is okay (when your argument is that gramatical details, even when just optional, shouldn't be omitted; oh the irony).

    My reply boils the entire issue down to a simple explanation and simple rules to follow the requirements without ever having a problem.

    And that's okay. If you want to use that rule instead of others I don't have a problem with that. The main problem that I had with your replay is that you stated it wasn't a choice (which it is) but a mandate (which it's not). You can even advocate that it's a better choice if you belive that.

    Your opinion as to whether you use them may be fine for you, but ignoring the optional curly brace "feature"

    A rather large section of my reply was explaining why this assertion of yours is false. It's not a "feature" that curly braces can be omitted, and that they are inhierently required. They are inherently *not* required, and it is a *feature* to be able to use them to allow for multiple statements to make up the body of certain types of loop/branch constructs.

    is a well-known best practice

    Yes, it's a fairly common practice. It's also quite common for more experienced programmers to choose to not follow it. It's often something that's told to brand new programmers who don't yet have a good grasp of how to program and haven't really conceptualized code constructs, and is often shed when dealing with even mediocre developers.

    , advocated by even Microsoft

    Microsoft, in some way or another, advocates almost *all* practices. There are lots of absoutely *terrible* practices advocated in some way by microsoft. That's not a measure of good best practices in my mind.

    and, although you have chosen not to use them in certain cases, you are the exception to this practice, not the rule.

    Both practices are quire common; neither is "extraordinarily rare"

    In any programming language, the tried and true rule of "follow a consitent usage of the language's syntax" is always considered best.

    I don't know if I'd agree with that. Consistancy has *some* inherent value, but it can also come at a cost. When the cost is greater than the value you should do what's inconsistant. *Always* being consistant without even considering the cost doesn't really make sense.

    It's best for you, it's best for the people who have to support your code (because what was "clear" to you isn't necessarily going to be for them) and it's best to avoid bugs.

    Well, I don't need to work with people who have only been programming for a few weeks much at my work. Everyone there, even the interns, will have been programming for several years. I can assume that they can read the following block of code without scratching their head too much:

    if(stringValue == null)
      return "";
    else
      return stringValue;


    If it's too much for them to understand then I'll go talk to them and help them understand it rather than fixing the code, because it's perfectly fine without curly braces.

    As for the IDE automatically indenting upon changes, yes that's a nice feature, but again we shouldn't be relying on the IDE to structure our code in a scalable way.  YOU may pick up on the indentation, but other less-experienced developers may not.

    I disagree that it's a feature you can life without. Using an IDE for any non-trivial code snippets (and often even trivial code snippets) adds an extraordinary amount of productivity. You shouldn't be programming in a production environment (particularly in C# without a quality IDE. Again, if a co-worker of mine had trouble working with some of my code because they weren't using an IDE then *that* would be the problem; I'd fix it by having them get visual studio because they shouldn't be programming without it. It is programming without an IDE that's not scalable.

    In the end, you have to ask yourself if the practice that you are following adds or detracts from the overall quality of the code. 

    Yes, I absolutely agree there

    Omitting curly braces will NEVER add to the quality of your code

    Well, that didn't last long. I disagree here; it may not be *significant* but I do feel that certain blocks of code are easier to read without superfluous braces.

    , but it will certainly add a level of inconsistency

    If you reject the rule that loop/branch constructs should always use braces then it's not inconsistent actually.

    and the possibility of bugs

    There's a possibility of bugs regardless of whether you use braces or not. The probability of generating a bug *might* change. There are certainly situations where omiting braces is possible but confusing or in some way detracts from readability; note that I'm *not* saying that they should be omitted whenever possible, merely that there are situations where the intent of the code is perfectly clear without any braces.

    , where if you just add them all the time, the entire issue goes away.

    At the cost of code bloat, which isn't something you can just categorically ignore.

    Say what you will, but this is not my opinion, it is a well-known and documented practice across many programming paradigms.



    Well, it is your opinion. It's an opinion that you share with many others, but whether it's "more readable" is an entirely subjective statement, aka opinion, not a matter of fact. Yes, adding superfluous braces is a practice by many people from many languages, and also note that not using them (when they aren't needed) is also a practice followed by many people from many programming languages.

    Note that I have followed the practice that I have stated for  *years* and I have *never* had a problem as a result, nor have I ever known anyone to have a problem with code that I wrote as a result.

    Friday, October 12, 2012 11:34 PM
  • If you are going to be involved with forums like this, but expect each individual post to be assimilated without the context of the thread it appears in, and you are going to make statements that fly in the face of accepted wisdom and simply imply that you are such a superior programmer you don't need to follow that wisdom, then you have really telegraphed that you like the way you do things and everyone else be dammed.

    And, to be clear, there was nothing incorrect in my first post, you just didn't interpret it correctly.  I said that curly braces are required when something has a defined beginning point and a defined ending point and the curly braces delimit those places.  If you are using a single statement, then you don't have that condition.

    I boiled the entire issue down to a simple rule that, if followed, makes any additional concern irrelevant.  You just don't want someone telling you that your wrong.

    I have just a little experience in this arena and have the benefit of 20 years of working with various organizations around the globe, from mom and pop shops to Fortune 500 clients to governments.  I get paid to teach and consult with these Enterprises on how they can best apply pattern and practices and I have to show that my advice is accurate and will cause measurable results. Now, I don't say this to blow my own horn, but I bring it up because I've been able to see an extremely large data-set of environments and feel very confident when I say that you are in the clear minority on this. It's not even close.  You may not feel that way based on the community that you work in.  But your fish bowl is not representative of where the development and architecture community is today.

    I can tell you that the more experienced a developer is, the more they rely on consistent, standards based approaches that road-block known pathways to unstable code, hard to read code and code that doesn't scale well.  Sometimes putting curly braces in and sometimes not will ALWAYS open that door.  Always putting them in will NEVER open it.  That's just a fact, not opinion.  If you ALWAYS add the braces, you will NEVER be burned by additional lines of code not executing at the right time. If you ALWAYS add the braces, you will NEVER have someone scratching their head as to why they are sometimes there and sometimes not.  You make these two issues simply go away by following the practice of ALWAYS adding {}.  You simply cannot make any reasonable case to disprove that or any reasonable case for straying from that.

    Really, your only response against doing this was code bloat? I think you need to look up what that means because 2 extra characters in a compiled language is not what people mean when they talk about code bloat.

    In the end, I think my point has been made and I think readers have enough information to be able to decide for themselves.

    Good luck to you and your very experienced team of pro's.

    Saturday, October 13, 2012 12:10 AM
  • and you are going to make statements that fly in the face of accepted wisdom and simply imply that you are such a superior programmer you don't need to follow that wisdom, then you have really telegraphed that you like the way you do things and everyone else be dammed.
    Really my point was that you shouldn't do do things for no other reason that that they're the "accepted practice" or because "my professor at school told me to do it that way" or "there's this one article that says this is the only way to do it". It's worth taking the time and effort to investigate why best practices are best practices. It's worth experimenting to see what works for you, and what doesn't. Rather than just not doing something because someone told you to [assuming you have at least some idea of what the consequences are] it can be worthwhile to try things out for yourself and see what's best. If you find that, when you omit braces from time to time, you end up with bugs (even occasionally) then you should consider it worth your time and effort to add the braces. If you find that some naming convention that is considered "standard" results in lines of code being ambigous or harder to read for you then try another one, etc. until you find what works for you. It's worth listening to the opinions of others to see what works for them, and what has bitten them in the past. Rather than writing your rules in stone, take the time to think about it. Once you've come to realize *why* some practice exists, assuming you agree with it's reasoning, it will make it that much easier to follow it, and it will also help you realize when it's holding you back or not appropriate.
    And, to be clear, there was nothing incorrect in my first post, you just didn't interpret it correctly.  I said that curly braces are required when something has a defined beginning point and a defined ending point and the curly braces delimit those places.  If you are using a single statement, then you don't have that condition.
    Sure you do. An `if` block that is followed by just a single condition still has a start and an end. It ends before the start of that statement and ends just after it.
    I boiled the entire issue down to a simple rule that, if followed, makes any additional concern irrelevant.
    It doesn't make *any* additional concern irrelivant. It makes *certain* other concerns irrelivant. You can't sit there and says that nothing can ever be wrong with a statement that uses curly braces.
      You just don't want someone telling you that your wrong.
    Well I don't *just* dislike it. Sure, it's not exactly appealing, but it's not like I can't have a rational arguement with someone I disagree with.
    I have just a little experience in this arena and have the benefit of 20 years of working with various organizations around the globe, from mom and pop shops to Fortune 500 clients to governments.  I get paid to teach and consult with these Enterprises on how they can best apply pattern and practices and I have to show that my advice is accurate and will cause measurable results. Now, I don't say this to blow my own horn, but I bring it up because I've been able to see an extremely large data-set of environments and feel very confident when I say that you are in the clear minority on this. It's not even close.
    All right. Since you have such a vast wealth of experience; how often do you know of programmers (with more than a month of experience) who have introduced bugs (reaching production code) that resulted from them not using curly braces around a loop/branch statement?
      You may not feel that way based on the community that you work in.  But your fish bowl is not representative of where the development and architecture community is today.
    Well, my "fish bowl" also includes several major programming sites, this one (to a degree) but more so stackoverflow.com. The site contains a very large number of highly experienced programmers and involve collaboration and critique from the entire community. That has much more of an influence of my opinion of developer communities worldwide than the people I work with in my office. There is substantially more diversity online than at my work where, I will be the first to admit, there is not a whole lot of academic diversity.
    I can tell you that the more experienced a developer is, the more they rely on consistent, standards based approaches that road-block known pathways to unstable code, hard to read code and code that doesn't scale well.
    We don't disagree on those points. We disgree on whether this particular practice violates those points.
      Sometimes putting curly braces in and sometimes not will ALWAYS open that door.
    No matter what you do; whether you follow every standard practice you hear of or none of them, you open the door to bugs. That's inevitable. Some decisions increase the chances of bugs, some decrease them, and some have no measurable difference. Since I have never seen a programmer (that wasn't just starting out) have a problem as a result of my practices, I consider this practice in that last bucket.
      Always putting them in will NEVER open it.
    Again, you think that using braces makes your code bug free? Or are you just saying that it makes this one problem that *I've never seen impact any professional programmer* go away. Making problems that people don't have in the first place go away isn't hard.
      That's just a fact, not opinion.
    It's not really either. As is, it's such a vague statement that it doesn't really mean anything. If it's designed to summarize your entire point; that it makes the code more readable, then it most certainly is opinion.
      If you ALWAYS add the braces, you will NEVER be burned by additional lines of code not executing at the right time.
    Congrats, you've come up with a suggestion to make a problem that doesn't exist go away. That takes real skill.
    If you ALWAYS add the braces, you will NEVER have someone scratching their head as to why they are sometimes there and sometimes not.
    I've never really found this to be an issue either. Why would anyone *care* why someone sometimes uses braces and sometimes doesn't. As long as it's perfectly clear what the code does when reading it without adding redundant braces I see no reason to question the decision. If it's actually unclear within which control block a statement is a part of then that code wasn't written well, regardless of whether it used braces or not.
    You simply cannot make any reasonable case to disprove that or any reasonable case for straying from that.
    Well, actually I already have.
    Really, your only response against doing this was code bloat? I think you need to look up what that means because 2 extra characters in a compiled language is not what people mean when they talk about code bloat.
    So you think that over the course of an entire program you're only adding 2 extra characters? loop/branch statements make up a significant portion of code. What if you saw someone that added an additional blank line after every single line in your program? Do you think that would have no impact on readability at all? Now, just like with so many things, there are extremes at both ends, and there is certainly a place for braces in loop constructs, and whitespace, but adding it in when it isn't needed comes with some cost. You seem to think that omitting it is the end of the world. I'm trying to tell you that the benefits you're saying are there are minuscule. Not nothing, but very, very small. The benefits of excluding braces, even when they are needed least, is still not enormous; I never said they were. My point is that the decision, in either direction, involves such little change that it's perfectly reasonable to let programmers do what they prefer, and what works best for them. I wouldn't call out a team member of mine because they *always* used braces around even the tiniest `if` statement, nor would I call them out for removing them in a location where the code was perfectly clear without it. I would let them do what works for them so long as it wasn't causing problems for anyone else (because I wouldn't expect it to).
    Saturday, October 13, 2012 2:40 AM
  • Your entire responses come down to the following:

      • You are refuting things I never said.

        You keep responding that I stated that the suggested course of action will eliminate *all bugs* and that I indicated that you should do something just because it's the accepted practice and someone told you to do it. 

        I never said either of those things:

        I pointed out that it is the vastly accepted practice and I pointed out *why*.  I said that if you follow this guidance, you will NEVER encounter a bug related to the omission of curly braces.  That is what is irrefutably true and no argument can be made to disprove it.


        (As an aside, people who take online forum threads off-topic by intentionally mis-chacterizing an opposing point of view are not contributing anything productive to the discussion.  Because you have continuosly kept responding with statements refuting things I never said, I can only begin to wonder what your motivation is. You seem like you just want to argue for the sake of it.)
      • You indicate that the suggested guidance has no merit because it's not been an issue that you've ever had to deal with. 

        As I pointed out, your experience is atypical in the development world at large.  And your attitude of dismissing this guidance because of your personal experience is rather arrogant, pardon me for saying, as you are not a fortune teller and have no idea how your or your team's code will need to scale in the future, nor do you know who will be doing that scaling.  That's the whole reason we have accepted standards, patterns and practices, because a single application, developer or development team doesn't live in a vaccum. 
      • You asked how often I have encountered this becomming an issue that reached production code.

        I have already responded that it comes up often enough for a standard practice to be adopted, not just at one Enterprise, but in the entire development world at large. As do other, seemingly simple things, like following a known worst-practice of trying to optimize code as it's being written, failure to test for nulls and failure to initialize fields.

        Poor quality code makes it into production for a variety of reasons: the most frequent is code that addresses a problem domain, goes into production and then the problem domain changes and the original code is expected to handle that change (you have never heard of a client changing the requirements of an application?).  This is where the fragility and poor coding standards usually come to light.

        What you do at the foundation level of a code-base will have ripple effects as the code changes/scales.  Large Enterprises certainly do run into this issue and often it cannot be tracked back to a single developer.  Most frequently, it traces back to some legacy code that must be maintained because it has become so integrated into the application that it makes little financial sense to perform a rewrite.

        Again, your responses have been:

        "I've never really found this to be an issue either. Why would anyone *care* why someone sometimes uses braces and sometimes doesn't."

        and

        "My point is that the decision, in either direction, involves such little change that it's perfectly reasonable to let programmers do what they prefer, and what works best for them."

        This just not practical advice since your advocating for inconsistent syntax (sometimes using braces and sometimes not IS inconsistent usage of curly braces) that could open the door to bugs (if additional lines get added and the absent braces are not noticed) and my advice is for consistent syntax that will never open that door.

        In just about every Enterprise I work with, there are internal standards documents that dictate exactly what the expectations are from all developers, down to the most minute details.  This is not a rare practice.  This is so that all code written will be in a standardized form that can meet the requirements of a code review (both human and automated). Most Enterprises simply do not let the developer make these decisions.

        Again, this doesn't  seem to be the case for YOU, but I think it's been made clear that your experience is not representative of the industry.
    • Edited by Scott M. _ Saturday, October 13, 2012 7:31 PM
    Saturday, October 13, 2012 4:35 PM
  • Intersting to watch how such a petty question from 2006 can generate such controversy in opinion.

    João Miguel

    Saturday, October 13, 2012 6:42 PM
  • I actually find it absurd, rather than interesting, but I hate it when people want to put up incorrect statements and then justify them by responding to things that no one even said.

    My goal is to make sure that someone who may come across this (like yourself) gets accurate information that is helpful and not advice that ultimately is counter-productive.

    Saturday, October 13, 2012 7:26 PM
  • I didn't read all of your and servy42's opinions, but I think that the matter is quite simple and that both of you will agree with this: curly braces limit blcks of code.

    If they increase or decrease redability, that's mere opinion; I use them almost all the time, however it is just my opinion I should use them in such a way. To answer a question I think opinion should be given, but the most important is fact, let people develop their own opinion from that.

    For expl. (about curly braces), in a nutshell, we use them to include all code between them in an if, loop, or any other compound statement. They're optional when you only wantto include one statement in the block.

    That's it.


    João Miguel

    Sunday, October 14, 2012 6:53 PM
  • Well, yes and no.

    If there are no ramifications to using them or not, then the choice is entirely stylistic and, I agree, whatever you like is the way to go.  Just like if we were talking about putting the opening curly brace at the end of the line that declares the coding construct vs. putting them at the beginning of the next line is purely stylistic in C# and has absolutely no ramifications to the way the code executes.  Again, for that type of discussion, readability and developer choice rules.

    But (and this is the key to this discussion), there ARE ramifications to using them or not and the decision to optionally omit the curly braces is not purely a stylistic choice.

    servy42 has his fundamental disagreement with me right here, as he believes that there are no ramifications because a developer should just know enough to know and be able to spot how this choice needs to be addressed when the code needs to be changed later.

    But the flaw in his approach is that it relies on an additional action being taken by the developer in the future (over and above adding the additional functionality that the new problem domain requires). And, unlike in servy42's experiences, we know that people aren't perfect and things get overlooked, especially as code-bases grow over time and have multiple developers (with various levels of knowledge and experience) maintaining that code (off-shore maintenance of code is usually a good example of this).

    A better, more scalable approach relies on the principle that making someone remember to take additional actions (that they may not realize need to be taken) later is not as good as completely removing that requirement with the little to no effort of following a good standard today.

    By adopting the standard of letting various developers decide, you WILL have an inconsistent code-base that *sometimes* requires you to remember something and *sometimes* doesn't.  This inconsistency, coupled with the REAL adverse side-efffects of not remembering is why this approach is widely considered better.

    Sunday, October 14, 2012 7:21 PM
  • OK, I agree it's a good practice to use curly braces, but no one will forget something like that. If even if they do, they'll debug the code and check for the problem (expl., if one forgot to surround the block in a loop with curly braces) that can be easily found.

    João Miguel

    Sunday, October 14, 2012 7:59 PM
  • Well, let's consider this...

    "but no one will forget something like that"

    In fact, they do and more often than you may think.  Think about Enterprise applications that are supported by large groups (some off-shore) with differentl levels of experience and caffiene in them! Remembering to add something beyond the functionality your trying to implement is harder than just implementing the new functionality.

    "Even if they do, they'll debug the code and check for the problem...it can easily be found."

    If you don't add the braces, you may not get an exception of any kind (depends on what the additional lines are doing), you'll just get anomolous, and in the case of an "if", sporratic behavior.  These are not as easily tracked down, but even if they are, wouldn't it be better to not have the problem disrupt production code and have someone go find and fix the problem in the first place?

    If you just add braces all the time, which is also no big deal to do, you ELIMINATE even the possibility of this ever coming up.



    • Edited by Scott M. _ Sunday, October 14, 2012 10:22 PM
    Sunday, October 14, 2012 8:08 PM
  • There is no exception for Lambda's.  If your lambda consists of one statement, you may omit the curly braces, when it doesn't, you can't.


    That's not exactly true. If you don't use braces, the body of the lambda must be an expression. If you use the braces, it must contain statements.
    Func<int, int> test1 = x => x + 1; // ok
    Func<int, int> test2 = x => { return x + 1; }; // ok
    Func<int, int> test3 = x => return x + 1; // wrong
    Func<int, int> test4 = x => { x + 1; }; // wrong

    Monday, October 15, 2012 4:27 PM
  • He's right, I didn't notice it though. I read tjis thread "diagonally" as it was too long.

    João Miguel

    Monday, October 15, 2012 6:58 PM
  • How many expressions can you have with no braces?

    Could you show an example of a lambda that has multiple expressions but no braces?

    Monday, October 15, 2012 10:48 PM
  • The question is not stylistic. If the body of a lambda expression is a statement block, it cannot be converted to an expression-tree. The number of statements you put in it is irrelevant.
    Tuesday, October 16, 2012 12:50 PM
  • Too old question, can make too many differents opinions.

    Please Alternate TextMark As Answer whenever a replied post satisfy your question.
    Web Developer

    Tuesday, October 16, 2012 3:22 PM
  • MSDN states that, when you don't have the curly braces it's called a lambda expression. When you do, it's an expression lambda. You can't return implicitally in an expression lambda, you must use the 'return' keyword (unless you return void, of course).

    João Miguel


    • Edited by JMCF125 Tuesday, October 16, 2012 3:30 PM correction
    Tuesday, October 16, 2012 3:30 PM
  • MSDN states that, when you don't have the curly braces it's called a lambda expression. When you do, it's an expression lambda.

    If you refer to http://msdn.microsoft.com/en-us/library/bb397687.aspx they differentiate between expression lambda and statement lambda, both being lambda expressions.

    You can't return implicitally in an expression lambda, you must use the 'return' keyword (unless you return void, of course).

    If that was the only difference, it would be only a stylistic choice. The real difference is when you convert it to an expression tree, in which case you need an expression lambda.

    When you convert to a delegate, there is no difference between x => exp and x => { return exp; }

    Wednesday, October 17, 2012 12:42 PM