Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c# - Why do methods with only one statement need braces?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...