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
There is short circuiting in C# so you can do:
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
It will now only execute the expensive operation as a last resort.