1

I have a program that is going to run through the "Open with ..." menu and give the path file as input to the program. My code is as follows:

 static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        if (args[0] != null)
        {
            Application.Run(new Form1(args[0]));
        }
        else
        {
            Application.Run(new Form1(""));
        }
    }

It will run correctly when given to the input program, but when I enter the program without input and normally, I get the following error:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

Is there a way to solve this problem?

A.Farahmand
  • 23
  • 1
  • 4
  • 3
    When looking at the answers, be aware that `args` *cannot* be null and nor can any of its elements. – Matthew Watson May 21 '21 at 15:17
  • 1
    Here's a good chance for you to get used to debugging your programs. Put a breakpoint on the start of the main function (it will show up on the `{`). Now step once. Hover over `args`. You can see it's an array. If you click around in the pop up, you can see how many elements it has (likely 0). Remember that `args[0]` is the first element, so that's where you are getting your error. By the way, when reporting an error like you did, please include the line where it occurred. – Flydog57 May 21 '21 at 15:25
  • 1
    Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Charlieface May 21 '21 at 16:00

3 Answers3

2

Check args to be not empty:

if(args.Any()) 
{
  // use args[0] here
  ....
}
else
{
  ....
}

The error you have means that args is empty, so accessing first element(at 0 index) is illegal.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • @Charlieface this was my original code, but ["The `args` array can't be null. So, it's safe to access the Length property without null checking."](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line) – Guru Stron May 21 '21 at 16:02
1

If args cannot be null, that doesn't mean we cannot check if it is not empty.

Try This:

if(args.Length > 0)
{
    Application.Run(new Form1(args[0]));
}
else
{
    Application.Run(new Form1("");
}
Gunnarhawk
  • 437
  • 3
  • 12
  • This should be the accepted answer as it's proper. `args` will never be null, so there is no reason to check if it's null like all the other answers are doing. – Andy May 21 '21 at 15:40
0

The problem is, you are trying to check whether the first element is null, even if your args array does not contain any elements. Since your array is empty, you cannot access index 0.

Zokka
  • 147
  • 6