C# check if you have passed arguments or not

Viewed 66307

I have this code:

public static void Main(string[] args)
{         
    if (string.IsNullOrEmpty(args[0]))  // Warning : Index was out of the bounds of the array
    {
        ComputeNoParam cptern = new ComputeNoParam();
        cptern.ComputeWithoutParameters();
    }
    else
    {
        ComputeParam cpter = new ComputeParam();
        foreach (string s in args){...}
    }
}

Also tried if(args.Length==0), but it still doesn't work.

Basically I want to find out if the user called the program with arguments. If not the program will ask for input.

How can I do this? Thanks in advance.

6 Answers

This should work on your scenario:

if (args == null || args.Length == 0)
{
    //Code when no arguments are supplied
}
else
{
    //Code when arguments are supplied
}

Notice how check args == null should be executed before args.Length == 0 when using || or &&. This is called "Condition Short-Circuiting" where C# will start evaluating the first condition and if it's true, will not look at the second condition. In this scenario, C# will evaluate the second condition only if the first condition is false.

Suppose if your conditions are aligned as if(args.Length == 0 || args == null) and args become null, it will throw an exception on the first condition, although the second condition is true.

This is something we need to keep in mind when placing conditions.

Another available option if you're already using System.Linq is to make use of the Any() extension, for instance:

public static void Main(string[] args)
{
    if (args == null && !args.Any())
    {
        // No parameters passed.
        ComputeNoParam cptern = new ComputeNoParam();
        cptern.ComputeWithoutParameters();

        return;
    }

    // process parameters
    ComputeParam cpter = new ComputeParam();
    foreach (string s in args){...}
}

This could also be written:

public static void Main(string[] args)
{
    if (!args?.Any() ?? true)
    {
        // No parameters passed.
        ComputeNoParam cptern = new ComputeNoParam();
        cptern.ComputeWithoutParameters();

        return;
    }

    // process parameters
    ComputeParam cpter = new ComputeParam();
    foreach (string s in args){...}
}

This just shows another option available to you, I'd agree with going with .Length, although I would drop the null check and use conditional access instead, so.

if (args?.Length == 0) {
    // Code hit if args is null or zero
}
Related