Hi everyone. I'm new to C# (or any programming language for that matter) and am trying to figure something out. I'll give the following example.
Code:
int SomeValue = 24;
if (SomeValue == 24)
{
MessageBox.Show("The Value is 24");
}
For the above piece of code, why is it that the semicolon used to declare the variable, and for the MessageBox.Show statement, but not the if statement? What I'm getting at is, are there rules and what are they for when a semicolon is used and when is it not?
In C# the semicolon ";" indicates the end of a complete statement. So the statement int SomeValue = 24 is followed by one. The "if" is not a statement, but a flow control construct.
The "if" is not a statement, but a flow control construct.
Actually, although it is a control flow construct (a branching command, if you will), it is also a statement. The difference is that the if statement contains a code block (the { ... } part) in this case. As CGKevin said, the ";" marks an end of a simple statement. This enables you to spread them across multiple lines, which is sometimes convenient (say, when a function call is too long). In essence, this may be ugly, but it compiles:
Code:
int
i
= 5;
// same as: int i = 5;
So, it's not required for a statement to be in one line. The compiler can tell where it ends, by looking for the ";". Now, some statements, like if, allow you to specify the code to be executed when a certain condition is met. This code can be a simple statement, ending with ";", or it can be a group of statements we call a code block, and bound it with { and }. In the latter case, the "}" marks the end of the compound statement, so there's no need for the ";".
You can write
Code:
if (x == y)
x = 0;
// or
if (x == y)
{
x = 0;
}
It's the same thing. The 2nd version is a block wit only one statement. If you have more than one statement, then you must use the syntax with the "{" and "}".
Bookmarks