Search code examples
c#curly-bracescurly-brackets

When are curley braces required around single statements?


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.


Solution

  • 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.