I have this code:
public static void Main(string[] args)
{
if (string.IsNullOrEmpty(args[0])) // Warning : Index was out of the bounds of the a
it's an array and there's two scenarios that might have the meaning NO arguments passed. Depending on your semantics
args == null
or args.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 == null || args.Length == 0){
ComputeNoParam cptern = new ComputeNoParam();
cptern.ComputeWithoutParameters();
}
else
{
ComputeParam cpter = new ComputeParam();
foreach (string s in args){...}
}
This should also work:
if (args.Length < 1)
{
//no args passed
}
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.
if(args.Length==0)
should work, args[0]
requires at least one argument to not crash.
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
}
if(args == null || args.Length == 0)
{
// no arguments
}
else
{
// arguments
}