Why do methods with only one statement need braces?

前端 未结 4 626
执念已碎
执念已碎 2020-12-15 12:17
public void Finalise()
    ProcessFinalisation(true);

Doesn\'t compile, but the correct version:

public void Finalise()
{
    Proce         


        
4条回答
  •  感动是毒
    2020-12-15 12:27

    Marc is basically right. To expand on his answer a bit: there are a number of places where C# requires a braced block of statements rather than allowing a "naked" statement. They are:

    • the body of a method, constructor, destructor, property accessor, event accessor or indexer accessor.
    • the block of a try, catch, finally, checked, unchecked or unsafe region.
    • the block of a statement lambda or anonymous method
    • the block of an if or loop statement if the block directly contains a local variable declaration. (That is, "while (x != 10) int y = 123;" is illegal; you've got to brace the declaration.)

    In each of these cases it would be possible to come up with an unambiguous grammar (or heuristics to disambiguate an ambiguous grammar) for the feature where a single unbraced statement is legal. But what would the point be? In each of those situations you are expecting to see multiple statements; single statements are the rare, unlikely case. It seems like it is not realy worth it to make the grammar unambiguous for these very unlikely cases.

提交回复
热议问题