Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Curly Brackets after if condition

In powershell we faced a peculiar issue where a statement worked on a system and not on another

if (condition)
    DoSomething

Missing statement block after if ( condition )

I know I can fix by adding curly braces { DoSomething } but I need to find why this happened. Is it a Powershell syntax upgrade which worked on one and not on another?

PS version where it worked

enter image description here

Upvotes: 1

Views: 2591

Answers (1)

kim
kim

Reputation: 3421

I tried to replicate this but wasn't able to in any of my Windows boxes, Windows 7, 8.1 and latest 10 (1803).

However, personally, I consider writing code like

if(condition)
    Statement

to be bad practice.

Imagine what happens if you would comment out that Statement.

if(condition)
    //Statement
OtherStatement

If you are not careful you could potentially have the if statement target some entirely different code, that you didn't intend to, and this way introduce a bug.

If you absolutely need to have a an if statement without curly brackets, then

if(condition) Statement

would be cleaner and less error-prone. However, I still prefer to always use { and } in any conditional statement.

Upvotes: 2

Related Questions