C# check if you have passed arguments or not

robertpas picture robertpas · Aug 3, 2012 · Viewed 56.1k times · Source

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.

Answer

Albin Sunnanbo picture Albin Sunnanbo · Aug 3, 2012

if(args.Length==0) should work, args[0] requires at least one argument to not crash.