33

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?

Community
  • 1
  • 1
egyamado
  • 1,111
  • 4
  • 23
  • 44

20 Answers20

60

For cases like this, there's also the conditional operator:

output = (val % 2 == 1) ? "Number is odd" : "Number is even";

If you're definitely going to use an "if" I'd use version 2 or version 4, depending on the rest of your bracing style. (At work I use 4; for personal projects I use 2.) The main thing is that there are braces even around single statements.

BTW, for testing parity it's slightly quicker to use:

if ((val & 1) == 1)
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • To add, the "standard" and most encountered with c# is 2, however many Java or previously Java shops will have inherited 4. Unless you have reason not to, 2 would be best to make it readable to you and to other C# developers. It will also help you when reading reference material, which is mostly 2. – David Mar 12 '09 at 17:48
  • 2
    +1 for the ternary operator, -1 for the unnecessary braces. – Kevin Mar 12 '09 at 17:55
  • I love the conditional operator. +1 – nickohrn Mar 12 '09 at 19:13
  • Sometimes it's better to write one or two lines more code. Sure, there are a lot of nice possibilities to nest code, but all at the expense of readability. – Alexander Mar 12 '09 at 19:15
  • @Alexander: There are certainly times when a conditional operator makes the code less readable, but I don't personally think this is one of those times. – Jon Skeet Mar 12 '09 at 19:34
  • I think for C# option 2 should be preferred. – OscarRyz Mar 12 '09 at 20:18
  • Very good anwser ... It really handles every aspect of the question (I love the & detail ;) ). Anyway, I (almost) always use either 2 or 4, depending on the project style. – David Božjak Mar 12 '09 at 20:29
  • what in the world is this called: if (condition) ? true : false I can't find the name of that construct anywhere. – OldBuildingAndLoan Mar 12 '09 at 20:33
  • @42: http://msdn.microsoft.com/en-us/library/ty67wk28(VS.80).aspx – GEOCHET Mar 12 '09 at 20:35
  • @42: Also know as the conditional operator, like Jon Skeet says. – GEOCHET Mar 12 '09 at 20:36
  • @Rekreativc: What do you mean? Hoe can "The Project Style" decide which way to go? I know if it's personal project so i can chose any way, and if it's with a team i'll follow their style/way. So you meant the project style is the team style? – egyamado Mar 12 '09 at 20:38
  • @egyamado: That's certainly how I'd interpret the comment. Bear in mind that a single team may need to maintain codebases with several styles though, e.g. for historical reasons. I think a project is more likely to have a defined style than a team. – Jon Skeet Mar 12 '09 at 20:42
  • 2
    +1 for conditional operator, -1 for pointless bitwise hack – BlueRaja - Danny Pflughoeft Jan 18 '10 at 16:37
  • 7
    @BlueRaja: Pointless? It can improve performance in my experience. It also copes with signed values more easily. Not that I gave it as *an* option, not the *only* option. – Jon Skeet Jan 18 '10 at 17:17
  • Such lazy coding! I love it! `var c = mainText ? mainText.color : Color.black; if (mainText) mainText.color = locked ? new Color(c.r, c.g, c.b, colors.disabledColor.a) : mainText.color = new Color(c.r, c.g, c.b, 1);` – CausticLasagne Aug 28 '22 at 20:05
  • What else can I get away with!? `if (playSounds) GlobalAudiosource.PlaySound(locked ? clpLockedSel : clpSelect);` – CausticLasagne Aug 28 '22 at 20:12
  • @CausticLasagne: If they're both the same type, yes. – Jon Skeet Aug 29 '22 at 07:26
20

Version 2. I always include the brackets because if you ever need to put more than one line under the conditional you won't have to worry about putting the brackets in at a later date. That, and it makes sure that ALL of your if statements have the same structure which helps when you're scanning code for a certain if statement.

Bryan Marble
  • 3,467
  • 5
  • 26
  • 29
13

I use version 2.

One reason to use curly braces becomes more clear if you don't have an else.

if(SomeCondition)
{
  DoSomething();
}

If you then need to add another line of code, you are less likely to have an issue:

if(SomeCondition)
{ 
  DoSomething();
  DoSomethingElse();
}

Without the braces you might have done this:

if(SomeCondition)
   DoSomething();
   DoSomethingElse();
Khadaji
  • 2,147
  • 2
  • 17
  • 19
  • 6
    People keep using this as the reasoning for always using braces, but has this ever happened to you where you got confused? – Eclipse Mar 12 '09 at 19:23
  • 4
    Yes, it caused a bug for me once. I don't remember whether I was the developer responsible for putting "DoSomethingElse" call at the wrong indentation or not, but I certainly found and fixed it. It takes longer than you might expect, when the code really "looks" right. – Jon Skeet Mar 12 '09 at 19:35
10

I personally prefer 3. The extra curly braces just add too much unnecessary visual noise and whitespace.

I can somewhat see the reasoning for 2/4 to reduce bugs, but I have personally never had a bug because thinking extra lines were inside an if statement. I do use C# and visual studio so my code always stays pretty well formatted. This could however be a problem if I was a more notepad style programmer.

Jacob Adams
  • 3,944
  • 3
  • 26
  • 42
  • Exactly my thought as well. :) – David Mar 12 '09 at 18:24
  • Just wait for that time when you're still in the office at 1130pm on beer and curry night scratching your head.... :D – Kev Mar 12 '09 at 19:07
  • +1 for 3. If you're so tired that you can't tell the difference between an if without braces and one with braces, you are too tired to code and you're just going to be writing crap. – Eclipse Mar 12 '09 at 19:27
  • Do you still like #3; even if writing cascading if else statement? – egyamado Mar 12 '09 at 19:46
  • I only like 3 when the thing inside the if is one line of code. I personally don't like the cascading branches – Jacob Adams Mar 12 '09 at 20:52
6

I prefer #2. Easy readability.

RuudKok
  • 5,252
  • 2
  • 26
  • 27
5

None of the above.

If my execution block only has one line (even if it's a huge for statement) then I don't use braces, but I do indent it, similar to #3

if (num > 3)
     print "num is greater than 3";
else
     print "num is not greater than 3";

An example with multiple statements that do not need curly braces:

if (num > 3)
    for (int i = 0; i < 100)
        print i + "\n";
else
    print "booya!";

That said, Jon Skeet's response in this question is the best

belgariontheking
  • 1,351
  • 1
  • 10
  • 15
  • This is too prone to errors, someone else might start working on the project and add one line thinking it's in the conditional block and break the application. – mbillard Mar 12 '09 at 19:20
  • @crossbrowser, I have never seen that happen. – Kevin Mar 12 '09 at 19:40
  • 1
    @Crossbrowser: Well yeah, if they're an idiot. Do you let idiots that don't know the language maintain your code? – belgariontheking Mar 12 '09 at 19:43
  • Agreed with the people above.. I find the brackets ugly and unnecessary when I only have one statement.. Also, I have never seen it happen that people do not understand it... I do tend to see the grammar police arguing about it a lot... – Arcturus Mar 12 '09 at 20:53
  • If another developer tasked with maintaining your code screws it up, I don't see how you could possibly sit there and blame the original author for doing something which is perfectly legal and not WTFy – TheTXI Mar 13 '09 at 12:33
4

It is more important to be consistent than to select the best.

These styles have different advantages and drawbacks, but none is as bad as mixing them within a project or even a compilation unit or within a function.


Ternary operator is the obvious choice for this specific code. For simple single statement if/else's that can't be otherwise expressed, I'd prefer a properly indented case 3:

if (val % 2 == 1)
    output = “Number is odd”;
else
    output = “Number is even”;

I understand the motivation behind "always use braces", but I've personally never been bitten by their omission (OK, once. With a macro.)

From the above styles, I'd pick (2). (4) would be ok if "properly" indented.
(1) I'd attribute to a young developer who hopefully will grow out of "compact code", or someone who can't afford a decent monitor. Still, I'd go with it if it was the local style.

peterchen
  • 40,917
  • 20
  • 104
  • 186
3

I use version 2.

Grzenio
  • 35,875
  • 47
  • 158
  • 240
3

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.

Bryan Rowe
  • 9,185
  • 4
  • 26
  • 34
3

It's strange that nobody mentioned this:

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

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

dmityugov
  • 4,390
  • 23
  • 18
1

I prefer 4 myself, but I think 2 is definitely good too.

Todd Friedlich
  • 662
  • 1
  • 5
  • 13
1

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.

mbillard
  • 38,386
  • 18
  • 74
  • 98
1

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.

Surgical Coder
  • 1,086
  • 1
  • 16
  • 25
0

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

Jay
  • 1,869
  • 3
  • 25
  • 44
0

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.

Community
  • 1
  • 1
Kev
  • 118,037
  • 53
  • 300
  • 385
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.

Kevin
  • 7,162
  • 11
  • 46
  • 70
  • 1
    Oh I've debugged issues caused by omitting braces on lots of occasions. Whilst it's true that omitting them in a simple if like this is unlikely to cause you issues, the bugs arise though subsequent maintenance where additional condition layers are added. Once you get nested ifs and omit the braces then all bets are off for maintained code being understood properly. ALWAYS using braces is the simplest way to forestall future issues and frankly it's lazy and unprofessional not to. You and I may be able to always pick up the logic just fine without them :-^, but there's a lot of dumb coders! – Cruachan Jan 18 '10 at 16:52
0

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!!!

Sean
  • 60,939
  • 11
  • 97
  • 136
0

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!

Alexander
  • 3,724
  • 8
  • 42
  • 50
0

I use a #2 with a minor change

if (condition1) 
{
      doStuff();
} else 
{
      doSomethingElse();
}
0

Single short statements:

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

Multiple or long statements

if (condition) {
   output = firstChoice;
   ...
} else {
   ...
}
TrayMan
  • 7,180
  • 3
  • 24
  • 33