4

In my answer here: C# Lock syntax - 2 questions, LukeH pointed out that try...catch...(finally) statements require curly braces.

I found the answers as to why, found here ( Why do try..catch blocks require braces? ) very interesting.

I'd like to know of any more examples where curly braces are required as opposed to good practice etc, ideally with code snippet and explanation as to why.

Community
  • 1
  • 1
George Duckett
  • 31,770
  • 9
  • 95
  • 162
  • 2
    If you use "razor", they are *always* required. I actually kinda wish I had a compiler switch for csc that enabled this mode. – Marc Gravell Aug 04 '11 at 09:59
  • Agreed, i find one-line statements under if's etc. much more readable when adding `{...}`. The sort and curly. :D – George Duckett Aug 04 '11 at 10:10

4 Answers4

2

Around a method body.

// not allowed:
int Inc(int x) 
     return x+1; 

The why is not so easy, it would seem old-style C needed it more than C++/C#.

A little more about the why part, in (very) old C you would write

int Sum()
int a, b; // parameters, very informal
{
   int s; // local var
   ...
}

So this ancient syntax needed the braces. And in all the languages that are based on C, nobody ever saw a point in making them optional, assuming that was possible in some cases.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Can you think of a reason as to why? I'm trying to think of when there would be ambiguity (like the answer re. the try...catch example) but can't. – George Duckett Aug 04 '11 at 10:17
  • It might be possible to make them optional in the C# syntax, but why would the designers even table that? – H H Aug 04 '11 at 10:23
1

You must use either braces or parentheses with checked and unchecked, depending on whether you're treating them as operators or statements:

// legal operator
int y = checked(x * 2);

// legal statement
unchecked
{
    if ((a * b) > c)
    {
        DoSomething();
    }
}

// illegal operator
int y = checked x * 2;

// illegal statement
unchecked
    if ((a * b) > c)
        DoSomething();
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • To emphasize, the existence of the operator/expression version `checked()` answers the _why_ part here very well. – H H Aug 04 '11 at 10:31
  • @Henk: Indeed, although I don't see why the compiler couldn't perform some sort of contextual analysis to determine which version was being used. (But just because I can't see the potential pitfalls doesn't mean there aren't any. I'm sure there'd be some knotty corner-cases. Easier and less ambiguous to just enforce the brace/paren rule.) – LukeH Aug 04 '11 at 10:40
  • Maybe better split this into 2 answers. The switch cases are `labels`, as in `goto label12;` and follow that syntax pattern. Some special rules for switch and scope though. – H H Aug 04 '11 at 11:02
  • @Henk: True. I think I might just delete the `switch` stuff altogether; I just mentioned it out of curiosity really. Although switch sections aren't *just* plain labeled statements. For example, the compiler won't allow switch sections to fall through from one case to the next. – LukeH Aug 04 '11 at 11:15
  • And I still think that `switch` sort-of fits the "requires braces" spirit of the question. For example, `while (expression) {}` is legal and so is `while (expression);`, whereas `switch (expression) {}` is legal but `switch (expression);` isn't. – LukeH Aug 04 '11 at 11:28
1

Certain parts of language require braces to be present. For example, when you start a method you have to open and close braces to identify that as a code block. Inside a function certain language features like loops, conditinal statements, etc. also accept braces although in some cases they are not required. For example:

if (someValue == true)
    doSomething();

In this case braces are not required, however you can surround this statement with braces, because you have just one statement that will be executed after if check, but if you want to execute multiple statement inside an if you need to use braces. For example,

if (someValue == true)
{
    doSomething();
    doSomeMoreWork();
}

Trying something like this is not allowed:

if (someValue == true)
    doSomething();
    doSomeMore();
else
    doWork2();
    int i = 1 + 2;

Compiler will complain in this case.

The problem can best be seen in the following loop:

while(i < 10)
    doSomeWork();
    i++;

Here you would expect i to increment, but this never happens. Basically this loop is the same as this one:

while(i < 10)
{
    doSomeWork();
}

i++;

The statement inside the block will execute infinetly and i will never increment. In that case the proper way to write this statement would be:

while(i < 10)
{
    doSomeWork();
    i++;
}

Now you have a properly working statement. I like to use braces all the time regardless of number of statements that are being executed. The reason for this is that sooner or later I might need to add some more work in my if statement or inside a for or foreach loops. It's just a good practice.

Huske
  • 9,186
  • 2
  • 36
  • 53
  • @Downvoter any particular reason why the posts are downvoted? – Huske Aug 04 '11 at 10:31
  • Huske, a long answer but completely missing the question. – H H Aug 04 '11 at 10:38
  • I don't quite agree with you Henk, but fair enough. I think answering when and why it is required is pretty hard so I tried to picture a few cases and give an idea of when and how to use braces. – Huske Aug 04 '11 at 10:43
  • I think maybe George could have picked a more specific title. – H H Aug 04 '11 at 10:48
0

class/struct/interface declaration

class X { int _myval }

mishal153
  • 1,498
  • 3
  • 26
  • 37
  • True, but very different part of the syntax. A class does not contain statements but declarations. – H H Aug 04 '11 at 10:27