lundi 11 janvier 2021

What rules for curly braces inside an IF ELSE statement in C#

I'm doing a beginners course in C#, trying to understand how to use curly braces inside of IF ELSE statements. I find that if I have one statement in the IF or ELSE body, I don't need curlies, if I have 2 or more statements, then I need curlies. But > NOT ALWAYS!. I'm using Visual Studio, and sometimes it compiles without curlies, and other times I need to put them in. it's maddening.

As you can see here 2 statement lines printed fine on the console. (ignore the other stuff). No curlies.

2 statements with no curly braces

Now here I'm trying to compile the next day and it's requiring the braces (although this is now for the IF part of the IF ELSE, doesn't matter, I had it working yesterday with 2 statements no problems).

IF statement error

And here with the braces the error disappears.

with curlies

It's frustrating because sometimes VS requires curlies, other times it does not.

I believed if just one statement in the body I don't need curlies, If 2 or more statements in the body I need curly braces to show that everything in the braces get executed.

But Visual studio 19 seems to be changing its mind each day. I must be going mad.

Aucun commentaire:

Enregistrer un commentaire