To Brace or not to Brace in C# ifs and other Constructs

Posted by Peter Kellner on October 19, 2009 · 5 mins read

In my last post, I found a use for inverting if statements.  That is, I postulated that it is better to have an explicit else when it’s impossible for that code to be executed.  The argument for just falling through the loop with no else is that why have unnecessary code.

My argument is intent.  I personally like to make the intent of my code as clear as possible and having the extra else provides that for me.

Now, for the braces discussion.  That is, is it OK to do this:

if (myObject1==null) err = "bad1";
if (myObject2==null) err = "bad2";
if (myObject3==null) err = "bad3";
if (myObject4==null) err = "bad4";
if (myObject5==null) err = "bad5";

or should you be required by coding standards to do this:

if (myObject1==null)
{
 err = "bad1";
}
if (myObject2==null) 
{
 err = "bad2";
}
//...

I always follow the second, even though the code is clumsier.  I’m a creature of small errors and have found that it can lead to insidious errors when I don’t  That is, I may  say the following and expect both to be executed and will be sadly surprised.

if ( myObject==null)  err1 = "bad1"; errorno=3;

Of course, in the above example, errno will always be 3 whether or not myObject is null or not.

I’m supported in my thinking by Juval Lowy of IDesign in his coding standard 2.32. I’m not in 100% agreement with these coding specs (specifically around the use of m_, but overall, I like them very much.

image

I’m also supported by one of my favorite .net guys, Brad Abrams in his writings.

image

HTH’s!