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.
Another available option if you're already using
System.Linq
is to make use of theAny()
extension, for instance:This could also be written:
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.This should also work:
This should work on your scenario:
Notice how
check args == null
should be executed beforeargs.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)
andargs
becomenull,
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.
it's an array and there's two scenarios that might have the meaning NO arguments passed. Depending on your semantics
args == null
orargs.Length == 0
In this case where the method is called when the program is executed (e.g. not calling the method as part of say a unit test) the args argument will never be null (making the first test redundant) I've included it for completeness because the same situation might easily be encountered in other methods than main
if you test them in that order you don't have to worry about args being null in the latter expression
if(args.Length==0)
should work,args[0]
requires at least one argument to not crash.