C# check if you have passed arguments or not

前端 未结 6 922
灰色年华
灰色年华 2020-12-29 02:36

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         


        
6条回答
  •  清酒与你
    2020-12-29 03:24

    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
    }
    

提交回复
热议问题