This is an excess for evaluating Main (string [] args)

I have the following, and I was wondering if the initial test is excessive:

static void Main(string[] args) { if (args.Length == 0 || args == null) { //do X } else { //do Y } } 

In other words, I ask if there are opportunities args.Length equal to zero, or args being zero .... or would one of these conditions be sufficient?

+8
c # main args
source share
5 answers

Well, Main defined to never be called with a null parameter. If it somehow gets a null parameter, then your environment is so broken that all bets don't work no matter what you do, so nothing really works out by checking for null .

On the other hand, if you check the null value, readers and code developers will need to understand why. Why did the original programmer make such a useless check? Did he know something we don’t have? We cannot just delete it, because it may have discovered some strange error in the corners!

In other words, you add complexity to your program and upset future code readers. Do not do this. This future user may be you. Make your future happy and write code that makes sense.

However, in situations where such a null check makes sense, it should be the leftmost condition.

In a test like this: args.Length == 0 || args == null args.Length == 0 || args == null , args.Length is first evaluated, and if that fails, args compared to null . In other words, if args is null, your code throws an exception. It should be args == null || args.Length == 0 args == null || args.Length == 0

+15
source share

According to this , you only need to check:

 if (args.Length == 0) { // Do X } 

Although checking for null does no harm, there is no real need.

+11
source share

It’s a good idea to take extra control if it’s not a high-performance, very often used feature. Therefore, I would say no, it does not go too far.

And one more thing: check null first, after for Length

+3
source share

If there is no input, then args.Length is 0, but not null. If there is any input, then agrs.Length is equal to the number of input arguments. In conclusion, args cannot be zero, but the length can be zero.

PS check the null value first

+3
source share
 if (args == null) { Console.WriteLine("args is null"); // Check for null array } else { if (args.Length == 0) { //do X } else { //do Y } } 
0
source share

All Articles