-2

I made a program for parsing command line arguments... My code:

for (var x = 0; x < args.Length; x++)
        {
            switch (args[x].Trim())
            {
                case "--message":
                    if (args[x + 1] == null) // <= the problem
                    {
                        Console.WriteLine("Option {0} requires an argument.", args[x]);
                        Environment.Exit(1);
                    }
                    else
                    {
                        Console.WriteLine("Your message: " + args[x + 1]);
                        Environment.Exit(0);
                    }
                    break;
            }
        }

So when I type: 'myprogram.exe --message mymessage', the program prints my message without any errors. But my problem is: If no message is specified: 'myprogram.exe --message', it crashes because args[x + 1] doesn't exists. How can I check if args[x + 1] exists?

PS: Thanks for downvote!

Thank you for your answers! -AppPrinter

1 Answers1

0

Replace

if (args[x + 1] == null)

with

if (args.Length <= x + 1 && args[x + 1] == null)

to check if you have at least x + 1 items in your args. #

Just an idea: there are several frameworks for parsing command line parameters. You don't have to write your own logic ;)

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51