Does C# support if codeblocks without braces?

…衆ロ難τιáo~ 提交于 2019-11-30 01:19:13

问题


How would C# compile this?

if (info == 8)
    info = 4;
otherStuff();

Would it include subsequent lines in the codeblock?

if (info == 8)
{
    info = 4;
    otherStuff();
}

Or would it take only the next line?

if (info == 8)
{
    info = 4;
}
otherStuff();

回答1:


Yes, it supports it - but it takes the next statement, not the next line. So for example:

int a = 0;
int b = 0;
if (someCondition) a = 1; b = 1;
int c = 2;

is equivalent to:

int a = 0;
int b = 0;
if (someCondition)
{
    a = 1;
}
b = 1;
int c = 2;

Personally I always include braces around the bodies of if statements, and most coding conventions I've come across take the same approach.




回答2:


if (info == 8)
{
    info = 4;
}
otherStuff();



回答3:


It works like C/C++ and Java. Without curlies, it only includes the next statement.




回答4:


Yes, it supports if codeblocks without braces, only the first statement after the if will be included in the if block, like in your second example




回答5:


In C#, if statements run commands based on brackets. If no brackets are given, it runs the next command if the statement is true and then runs the command after. if the condition is false, just continues on the next command

therefore

if( true )
    method1();
method2();

would be the same as

if( true )
{
    method1();
}
method2();



回答6:


Of course "if" only works for "info = 4".




回答7:


It only takes the next line, so your example would compile to the second possible result example.



来源:https://stackoverflow.com/questions/4345867/does-c-sharp-support-if-codeblocks-without-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!