This is a really simple question but one I would like to know before moving forward so I understand the process.
In the tutorial I am following I was using an if statement. If you do the code below you don't need to use {}
if (userValue == "1")
message = "You won a new car!";
But if you use more than one line of code you do need {}.
if (userValue == "1")
{
WriteLine ("You won a new car!");
ReadLine ();
}
Can someone explain to me in very simple terms why this is the case? I just need a rule of thumb so I can understand why. Nothing overly complicated I'm just a beginner. I understand that they identify a block of code but am not sure why this makes a difference between one or two lines?
The {} indicates a block of code. If you have more than one statement that you want to be performed if the if is true, then you need to use these.
Example: Without the {} this block:
if (userValue == "1")
WriteLine ("You won a new car!");
ReadLine ();
Would perform the ReadLine() command whether or not the userValue is equal to 1.
Contrast that with the one with curly braces:
if (userValue == "1")
{
WriteLine ("You won a new car!");
ReadLine ();
}
Now in case the userValue is not equal to 1, both command inside the curly braces are skipped and the execution continues with the next statement after the } sign.