Does C# support if codeblocks without braces?

Kevin Boyd picture Kevin Boyd · Dec 3, 2010 · Viewed 12.4k times · Source

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

Answer

Jon Skeet picture Jon Skeet · Dec 3, 2010

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.