I have seen different ways of writing an if
statement.
Which one do you prefer and why?
Example 1:
if (val % 2 == 1){output = “Number is odd”;}else{output = “Number is even”;}
Example 2:
if (val % 2 == 1)
{
output = “Number is odd”;
}
else
{
output = “Number is even”;
}
Example 3:
if (val % 2 == 1)
output = “Number is odd”;
else
output = “Number is even”;
Example 4:
if (val % 2 == 1){
output = “Number is odd”;
} else {
output = “Number is even”;
}
Single short statements:
Multiple or long statements
using with the braces is suggested, I have seen some issue with the if else statement without braces ,(I don't remember exactly) i.e. Statement under if was not executed, when I added the same with braces then only worked.( Using Visual studio & C#4.0).
I would use them in the following order: 1) the Ternary operator 2) example 3, but indented properly 3) either 2 or 4, they are basically the same. I would go with whatever the general styl was where I worked.
I agree with what jake said about omitting the unnecessary curly braces. I have never caused or seen a bug caused by new code being added and someone thinking they were part of an if statement but they weren't because of the lack of curly braces. If someone ever did do that, I would ridicule them mercilessly.
You'd have to torture me to get me to use number 1.
Personally I prefer version 2. But since it's only formating it doesn't matter. Use which is best readable for you and your team members!
I agree with the ternary operator. Very under utilized in code that I come across, and I think it is much easier and nicer to read than all the extra brackets and indents it takes to write out an if/else statement.
Personally, there are two methods that I find being good-practice:
For if-blocks, there's only this way:
This is the safest and most comprehensible way to write if-else-blocks.
For one liners (true one liners that are comprehensible on one line), you can use the ternary operator.
You shouldn't call methods that do something that do not help the current assignation.
I wouldn't use any other way than those stated above.