none
Avoid the System.IndexOutOfRangeException - with main method args RRS feed

  • Question

  • Hi All,

    So I'm fairly new to C# and what I'm trying to do is to build out an app that takes 2 args when the exe is executed.

    However, if the user does not supply one or both of those arguments, that I call a method to ask for the data.

    Her's the code that I'm thinking about, but of course when I run it, I get the expected out of range exception.

    I'm wondering if something like this is possible:

    static void Main(string[] args)
    {
    	if (args.Length < 1)
    	{
    		GetAndSetVueValues();
    	}
    	else
    	{
    		if (!string.IsNullOrEmpty(args[0]))
    	{
    
    		//call the method to ask the user for the missing args
    	}
    
    ... rest of the code
    Thanks!
    Thursday, January 24, 2019 3:42 PM

All replies

  • Maybe start with this:

    string arg1, arg2;
    
    switch( args.Length )
    {
    case 0:
        Console.WriteLine( "Please enter two arguments." );
        Console.Write( "Argument 1: " );
        arg1 = Console.ReadLine();
        Console.Write( "Argument 2: " );
        arg2 = Console.ReadLine();
        break;
    case 1:
        arg1 = args[0];
        Console.WriteLine( "Argument 1: {0}", arg1 );
        Console.WriteLine( "Please enter the second argument." );
        Console.Write( "Argument 2: " );
        arg2 = Console.ReadLine();
        break;
    case 2:
        arg1 = args[0];
        arg2 = args[1];
        Console.WriteLine( "Argument 1: {0}", arg1 );
        Console.WriteLine( "Argument 2: {0}", arg2 );
        break;
    default:
        Console.WriteLine( "Too many arguments." );
        Console.WriteLine( "Please supply no more than two arguments." );
        return;
    }
    
    // process 'arg1' and 'arg2'
    // . . .



    • Edited by Viorel_MVP Thursday, January 24, 2019 7:42 PM
    Thursday, January 24, 2019 7:40 PM
  • Where do you get the OOR exception at? Based upon your logic it seems correct. If args is empty then Length < 1. That means you won't do anything with the args. However if it is >= 1 then you check for null or empty args[0] which will be there. Note that you don't actually need this check because each arg won't be null or empty.

    Most people use a command line parser to handle this kind of thing. There are several versions floating around.

    Also note you said you are accepting 2 args but the code you provided is only looking for 0 or 1. Maybe post the rest of the code that uses args. Personally, for that few of arguments, I tend to just use LINQ to get the values from the command line, if any, and then prompt for what is missing separately (using a CommandLineOptions type to store the options that I will be using).


    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, January 24, 2019 8:50 PM
    Moderator