Question

I constantly find myself writing similar code like the example below:

if (object["Object Name"] != null) {
    if (object["Object Name"] == "Some Value") {
        // Do Statement A
    } else {
        // Do Statement B
    }
} else {
    // Do Statement B
}

The problem here is that I much check if an object is null or not and then I can check it for it's actual contents.

"Statement B" is always the same and in my case is usually a SQL statement.

There must be a better way around this?

Thanks
Stephen

Was it helpful?

Solution

There is short circuiting in C# so you can do:

if(null != object && object.name == foo)
  do A
else
  do B

C# always evaluates the first expression in the conditional statement first and if that fails, it doesn't try anything else in that part of the statement.

To further this point, if you are going to have an expensive operation in the conditional statement along with one or more inexpensive operations, it's good to put it at the end if possible, so it will only check the expensive operation when it really needs to. So something like

if(trivial comparison && trivial comparison && REALLY EXPENSIVE OPERATION)

It will now only execute the expensive operation as a last resort.

OTHER TIPS

Since C# does short circuiting, yes. Try this:

if (object["Object Name"] != null && object["Object Name"] == "Some Value") 
{
    // Do Statement A
} 
else 
{
    // Do Statement B
}

I think rewriting the if-then-else to this will make it look nicer because of the single B-statement.

if ((object["Object Name"] != null) && (object["Object Name"] == "Some Value")) 
{
    // Do Statement A
} 
else 
{
    // Do Statement B
}

Why the double check? Surely this would be sufficient:

if(object["Object Name"] == "Some Value") {
    // Do statement A
} else {
    // Do statement B
}

I sort of see what you're getting at with null checking, but the particular example you give doesn't require it.

EDIT: Now if you had written this instead:

if (object != null) {
    if (object["Object Name"] == "Some Value") {
        // Do Statement A
    } else {
        // Do Statement B
    }
} else {
    // Do Statement B
}

then the solution would be:

if(object != null && object["Object Name"] == "Some Value") {
    // Do Statement A
} else {
    // Do Statement B
}

DISCLAIMER: Not doing the general short circuit method.

Well, you could create a separate function to perform the lookup, especially if the query remains the same. So something like this: (pseudocode incoming)

private bool IsNullCheck(string objectName)
{
  if (object["Object Name"] != null)
     return false;
  else
     // statement B
}

if (!IsNullCheck("Object Name") && if(object["Object name"] == "Value") {
   // stuffs

} 
else 
{
        // Do Statement B
}

Or the like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top