开发者

Why does C# not require a semicolon after a class definition?

in C++, a semicolon is required to end the class definitio开发者_如何学编程n. I am wondering why c# does not require it?


The C++ language permits declaring a variable in the class declaration. Similar to:

class Mumble {
  // etc...
} globalMumble;

The semi-colon is required syntax to let the compiler know whether or not a variable is being declared as well. This syntax is a chronic source of very hard to interpret compile error messages. The worst one is this:

mumble.h:

class Mumble {
  // etc...
}      // <== note: semi-colon forgotten

mumble.cpp:

#include "stdafx.h"
#include "mumble.h"

int main() {
    Mumble* obj = new Mumble;
}

This produces these wonderful error message:

main.cpp(8): error C2628: 'Mumble' followed by 'int' is illegal (did you forget a ';'?)
main.cpp(9): error C3874: return type of 'wmain' should be 'int' instead of 'Mumble'
main.cpp(10): error C2440: 'return' : cannot convert from 'int' to 'Mumble'

Note that all the error messages refer to the .cpp file, not the .h file that contains the mistake. Desperate programmers have lost hours on this, along with large clumps of head hair.

The C# language was designed by highly skilled C++ programmers. Who set out to design a language that avoided these kind of real-life syntax problems. This is evident in many places in the C# syntax. Long story short: C# doesn't permit this kind of C++ syntax, no semi-colon was required to help the compiler.


Semicolons delimit statements in C#.

Because classes are not statements (and a brace already ends the class definition), a semicolon would be redundant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜