I've got the following and was wondering if the initial test is overkill:
static void Main(string[] args) {
if (args.Length == 0 || args == null) {
//do X
}
else {
//do Y
}
}
in other words what I'm asking is are there possibilities of args.Length being zero, or args being null....or would just one of these conditions sufficed?
Well, Main
is defined to never ever ever ever be called with a null
parameter. If it does somehow receive a null parameter, then your environment is so broken that all bets are off no matter what you do, so there's really nothing to be gained by checking for null
.
On the other hand, if you do check for null, then readers and maintainers of the code will have to understand why. Why did the original programmer put in such a useless check? Did he know something we don't? We can't just remove it, because he might have uncovered some weird corner case bug!
In other words, you're adding complexity to your program, and tripping up future readers of the code. Don't do that. That future user might be you. Make your future self happy, and write code that makes sense.
However, in situations where such a null check does make sense, it must be the leftmost condition.
In a test like this: args.Length == 0 || args == null
, args.Length
is evaluated first, and if that fails, args
is compared to null
. In other words, if args
is null, your code will throw an exception. It should be args == null || args.Length == 0
According to this, you only need to check :
if (args.Length == 0)
{
// Do X
}
Though checking for null
doesn't do any harm, there is no real need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With