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条回答
The star\"
2楼-- · 2020-05-18 11:55

It's strange that nobody mentioned this:

if ( x == 1) {
   ...
}
else {
   ...
}

To me, this is the only correct way, of course :-)

查看更多
ゆ 、 Hurt°
3楼-- · 2020-05-18 11:59

I use a #2 with a minor change

if (condition1) 
{
      doStuff();
} else 
{
      doSomethingElse();
}
查看更多
走好不送
4楼-- · 2020-05-18 12:02

I prefer #2. Easy readability.

查看更多
冷血范
5楼-- · 2020-05-18 12:02

I'd always use #2. #4 is a truly awful layout and would only be done by someone who believes that a method must be one screen size in length and will do anything to cram it in, rather than refactor the code!!!

查看更多
放荡不羁爱自由
6楼-- · 2020-05-18 12:03

Version #2 for me - easiest to see, easiest to read, easy to see where the if starts and ends, same for else, you dont have to worry about putting in brackets if you want to add more than one statement.

查看更多
男人必须洒脱
7楼-- · 2020-05-18 12:03

Example 2 is without a doubt the least error prone approach. Please see this answer I gave to a similar question for the reason why:

What is the prefered style for single decision and action statements?

Although the Visual Studio default for brace usage is to put braces on a newline (my preferred method), the Framework Design Guidelines book (first edition) by Krzysztof Cwalina and Brad Abrams propose a different convention, example 4, placing the opening brace at the end of a preceding if statement (Page 274). They also state "Avoid omitting braces, even if the language allows it".

Not having the second edition at hand, I couldn't say if these conventions have changed or not.

查看更多
登录 后发表回答