what’s the difference between writing:
if (blabla <= 0) {
//code;
}
and:
if (blabla <= 0)
//code;
?
what’s the difference between writing:
if (blabla <= 0) {
//code;
}
and:
if (blabla <= 0)
//code;
?
No difference aside from if you don’t use { and } the if statement will apply to 1 line of code only. If you got the {} it applies to everything in the { }
It is just a shorthand way to use a if, for when your scope is only 1 line
With {}, you can put more than one instruction underneath.
As a general “best practices” guide, I’d recommend always putting braces around the contents of an if statement - even though it’s not required if there’s only a single line. That way, if you edit the code later and add some additional logic, the braces are already there and things function as intended.
The difference is the second one will eventually cause you numerous hours of tracking down a bug that you could have prevented by using braces in the first place.
Nah, I disagree. I often find it quite useful to avoid the curly braces like so:
if (transform.position.y < 50)
return;
I often take it to the next level and go all one line:
if (transform.position.y > 50) Die();
SomeStatement();
It’s just personal preference (obviously) because the compiler accepts both ways 100%. It’s purely for readability, comprehension, and compactness.
Another way:
// very readable
if (transform.position.y > 50) return;
if (transform.position.y < -50) return;
if (rigidbody.velocity.y > 100) return;
if(tooManyPosts)
UnwatchThread();
The only time I have ever, ever found one line if statements useful and acceptable is when you bail out of a function because of an input parameter:
// stupid example
bool MethodName(int value)
{
// always false when value is < 0, we dont have
// to do any calculations or anything else.
if(value < 0) return false;
// otherwise other stufff...
}
However, I have found these situations very very rare.
I find myself doing this somewhat often, but even on a single line I’ll still use brackets.
if(noExecute) { return; }
// do some stuff
I just don’t really like the way if statements look without them I suppose.
Ternary operators are also a type of shorthand for if-else statements, but I think I read somewhere they are a tad bit slower to compute. Regardless though I do like to use the Ternary when possible
bool newBool = (integer > 0) ? true : false;
Yeah I always use tenary operators instead of traditional if statements when the if statement is only used to assign a value to a variable. Doesnt the compiler just generate an if statement behind the scenes?
The only time I use one-liners is in the case of exception throwing. If I’m returning, I’ll use curly braces and put it on the next line. example:
public bool SomeMethod(string myParam)
{
if (myParam == null) throw new ArgumentNullException("myParam");
if (myParam == "...")
{
return false;
}
}