简体   繁体   中英

Does C# support if codeblocks without braces?

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();

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.

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

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

是的,它支持如果没有大括号的代码块,只有if之后的第一个语句将包含在if块中,就像在你的第二个例子中一样

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();

当然“if”仅适用于“info = 4”。

它只需要下一行,因此您的示例将编译为第二个可能的结果示例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM