Different ways of writing the “if” statement [clos

2020-05-18 11:38发布

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”;
}

Similar question:

Why is it considered a bad practice to omit curly braces?

标签: c#
20条回答
欢心
2楼-- · 2020-05-18 11:48

Single short statements:

if (condition) output = firstChoice;
else doSomethingElse();

Multiple or long statements

if (condition) {
   output = firstChoice;
   ...
} else {
   ...
}
查看更多
▲ chillily
3楼-- · 2020-05-18 11:49

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).

查看更多
戒情不戒烟
4楼-- · 2020-05-18 11:50

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.

查看更多
地球回转人心会变
5楼-- · 2020-05-18 11:51

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!

查看更多
\"骚年 ilove
6楼-- · 2020-05-18 11:53

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.

查看更多
可以哭但决不认输i
7楼-- · 2020-05-18 11:54

Personally, there are two methods that I find being good-practice:

For if-blocks, there's only this way:

if(...)
{
    // ...
}
else if (...)
{
    // ...
}
else
{
    // ...
}

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.

var objectInstance = condition ? foo : bar;

// Or the binary operator when dealing with null values
var objectInstance = condition ?? foo;

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.

查看更多
登录 后发表回答