Mr. Smith
Mr. Smith

Reputation: 5558

Explanation for one line if statement behaviour?

Example code:

int hour = 0;
bool saveData = true;

if(hour > 0) doSomeMethod(); saveData = false;

In the code above, saveData will always be set to false, yet doSomeMethod() won't be fired. I figured that the compiler treats the semi-colon after doSomeMethod() as an indicator to move to the next statement, ignoring that it's on the same line as the if statement. What's the reason for this behaviour?

Upvotes: 0

Views: 550

Answers (3)

Aaron Anodide
Aaron Anodide

Reputation: 17196

In C# an if statement can either be:

if(expression) statement;

or

if(expression) { statement1; ... statementN; }

You're code's lack of braces makes it the former, thus your guess is correct.

Upvotes: 1

wRAR
wRAR

Reputation: 25560

C# ignores newlines, just as C and its other descendants, and uses ; to separate statements. Your code is completely equivalent to

int hour = 0;
bool saveData = true;

if(hour > 0)
    doSomeMethod();
saveData = false;

which is better style, by the way.

Upvotes: 4

kitti
kitti

Reputation: 14834

An if statement can contain either a single statement, or a code block. Once the compiler finds the ; it ends the if.

Your code above is equivalent to:

if (hour > 0)
    doSomeMethod();
saveData = false;

What you want is:

if (hour > 0)
{
    doSomeMethod();
    saveData = false;
}

or:

if (hour > 0) { doSomeMethod(); saveData = false; }

Upvotes: 6

Related Questions