Use braces.
If you don’t use braces, only the line immediately underneath an if statement is part of that statement. (Technically “only the statement after the if statement”.) A lot of people don’t like using this syntax. That means:
Despite the indentation, this will print “B”.
You get errors because based on this syntax rule, your else
statements don’t match up with an if
statement.
To fix it, use braces always, even if you have one line.
That way you can’t confuse yourself even if you don’t indent the code properly. An if..else
should look like:
C# doesn’t care about indentation, the compiler ignores whitespace. It’s a convenience for humans.
this is a great explanation, thank you so much
If (…) { . : : }
If the items in your if statement are more than one line then they must be wrapped in brackets {} So If(something here) Do something;
Is valid but if you have more than one do something they must be in brackets like this:
If(something here) { Do something; Do something; } Else { Do something; Do something; }
Dental plan! You forgot your braces.
C# devs
null reference exceptions