The semi-colon isn't a line terminator... it's a statement terminator. There's a semi-colon at the end of every expression statement and declaration statement.
(if
, for
etc statements aren't expression or declaration statements.)
So for example:
public class Foo // Part of a class declaration
{
int x = 0; // Declaration statement
public void Bar() // Part of a method declaration
{
Console.WriteLine(x); // Expression statement (using an invocation expression)
} // End of the method declaration, but not a declaration statement
} // End of class declaration, but not a declaration statement
The purpose of requiring them is so that the compiler can tell when you wanted to end the statement instead of continuing on the next line:
int x = 5;
int y = x // This isn't the end of the statement!
+ 5; // This is...
One alternative (used by VB, for example) is to have a line continuation where you want to explicitly continue onto the next line even though the current line would be a valid statement.
As noted in comments, the do
statement is an anomaly here. I see no obvious reason why this shouldn't be valid:
do { } while (false)
... but it isn't. It may be related to the fact that the plain while
statement needs a statement body, e.g. while (true);
(empty statement) or while (true) {}
(block statement). The closest I can come is "because the C# specification says the do
statement needs a semi-colon at the end..."
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…