public void Finalise()
ProcessFinalisation(true);
Doesn't compile, but the correct version:
public void Finalise()
{
ProcessFinalisation(true);
}
Compiles fine (of course).
If I am allowed if's without brackets when the following code has only one line:
if(true)
CallMethod();
Why is the same not allowed for methods with one following line? Is there a technical reason?
Since C# 6.0 you can declare:
And then call it as usual:
Short answer: C# is styled after C, and C mandates that functions be braced because of how C function declarations used to be.
Long version with history: Back in K&R C, functions were declared like this:
Of course you couldn't have unbraced functions in that arrangement. ANSI C mandated the syntax we all know and love:
but didn't allow unbraced functions, because they would cause havoc with older compilers that only knew K&R syntax [and support for K&R declarations was still required].
Time went on, and years later C# was designed around C [or C++, same difference in terms of syntax] and, since C didn't allow unbraced functions, neither did C#.
The obvious answer is the language spec; for reasoning... I guess mainly simplicity - it just wasn't worth the overhead of sanity-checking the spec and compiler for the tiny tiny number of single-statement methods. In particular, I can potentially see issues with generic constraints, etc (i.e.
where T : IBlah, new()
on the end of the signature).Note that not using the braces can sometimes lead to ambiguities, and in some places is frowned upon. I'm a bit more pragmatic than that personally, but each to their own.
It might also be of interest that C# inside razor does not allow usage without explicit braces. At all (i.e. even for
if
etc).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:
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.