Kevin Boyd
Kevin Boyd

Reputation: 12379

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

Upvotes: 27

Views: 23018

Answers (6)

Qwerty01
Qwerty01

Reputation: 779

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

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1501646

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.

Upvotes: 71

Trygve
Trygve

Reputation: 2531

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

Upvotes: 1

user32826
user32826

Reputation:

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

Upvotes: 0

dejanb
dejanb

Reputation: 156

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

Upvotes: 9

Lou Franco
Lou Franco

Reputation: 89202

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

Upvotes: 4

Related Questions