Search code examples
c#nullprogram-entry-point

Should I test for nullity of values in the args array of Main


According to this post :

is this overkill for assessing Main(string[] args)

It seems that args can never be null in

static void Main(string[] args)

Ok good to know, however, supposing args.Length == 1 is true is it possible to have args[0] == null ? First observation : A string array can have null elements

Second observation : If the main is invoked with the command line I wouldn't know how to pass null and I don't think it is possible,

Third observation : on the other hand (this is a bit far-fetched) it is possible that some code calls

Program.Main(new string[]{null}) 

Thus, it is possible to produce a case where one gets null values in the args array.

So the question is :

Is it overkill or good practice to make tests for nullity in the main's arguments ? (Especially considering that the main called like in the third observation is an unlikely case)

For example : is the following correct ?

 static void Main(string[] args)
 {
     if(args.Length == 1)
     {
          var v = args[0].Replace("Foo", "Bar");//hope args[0] is not null

or should I rather do

 static void Main(string[] args)
 {
     if(args.Length == 1 && args[0] != null)
     {
         //...

Note: I tagged it C# but I guess this applies to other languages as well


Solution

  • As written in your question, the static void Main() is private (because private is implicit if missing). Whoever calls it must use reflection and must know he is walking on tiny ice. He has the duty/obligation of passing correct parameters (where "correct" in this case is "no null values" anywhere). If he doesn't do it, and he receives a NullReferenceException, the fault is only his. So the answer is "you have no duty to check for null values" (and I wouldn't do it. It is overkill)

    As you wrote (and as written in the referenced answer), you can't pass null from the command line, so this removes the other possibility.