4

I am doing sanitaion on my command line application written in C#. I was wondering if I need to perform a null check against the passed in string[] args array? E.g.:

static int Main(string[] args)
{         
    if(args != null) { // is this needed?

    }
}

Please note I have found similar question concerning Java, but was unable to find anything concerning the command line arguments in C# (& .NET in general).

Also note that I have indeed tried to pass no arguments to my command line application and have never managed to make the args array object to be null. I have also tried accessing the command line arguments using the Environment.GetCommandLineArgs() utility function, and that was also never null.

I have also read this guide written by MS, and couldn't see any explicit guarantee that the args array will never be null.

Edit: Simplified my example.

13
  • As a best practice (and even for unit testing), it's best to check for null anyway Commented Sep 26, 2017 at 9:58
  • This is fairly opinion-based. In my honest opinion you should allways check arguments within a public API. Commented Sep 26, 2017 at 10:03
  • If you have to pass arguments, then you can pass null. That makes null check reasonable and tbh vital. Commented Sep 26, 2017 at 10:05
  • 1
    Calling the entrypoint using reflection would be a possiblity for args to be null see: dotnetfiddle.net/70zCd1. Commented Sep 26, 2017 at 11:12
  • 1
    @mihail I did not say that you should do that. But as you can see at the provided fiddle, sometimes you are not the first one in the callstack and therefore nothing is wrong in being prepared for all types of possible input. Commented Sep 26, 2017 at 12:03

1 Answer 1

7

The C# standard addresses this in section 3.1 Application Startup:

The entry point may optionally have one formal parameter. The parameter may have any name, but the type of the parameter must be string[]. If the formal parameter is present, the execution environment creates and passes a string[] argument containing the command-line arguments that were specified when the application was started. The string[] argument is never null, but it may have a length of zero if no command-line arguments were specified.

(My bolding)

So the answer is: No, a console application's Main() can never receive a null args[] parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.