Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C# console application receive null arguments?

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.

like image 784
Evdzhan Mustafa Avatar asked Mar 07 '23 23:03

Evdzhan Mustafa


1 Answers

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.

like image 100
Matthew Watson Avatar answered Mar 10 '23 14:03

Matthew Watson