문제

I was learning about the switch...case statement and i cant find out whats wrong with the following code. Once i debug i goes back to visual studio and gives me a error. An unhandled exception of type 'System.IndexOutOfRangeException' occurred in C sharp.exe

Additional information: Index was outside the bounds of the array.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace C_sharp
{
class Program
{
    //this will demonstrate the switch statement
    static void Main(string[] userInput)
    {
        int input = int.Parse(userInput[0]);

        switch(input)
        {
            case 1:
                Console.WriteLine("you typed 1 (one) as the first command line argument");
                break;
            case 2:
                Console.WriteLine("you typed 2 (two) as the first command line argument");
                break;
            case 3:
                Console.WriteLine("you 3 (three) as the first command line argument");
                break;
        }
    }
}

}

도움이 되었습니까?

해결책 2

Visual Studio should be highlighting a particular line when it hits that exception. Let me guess: this one?

int input = int.Parse(userInput[0]);

That's nothing to do with the switch statement, but to do with the arguments to Main(). Those get there from the command line, for example when you invoke your program by typing

command some-parameter

at the C:\ command prompt, or from your Command line arguments which you can set in the Debug page when you look at the Properties of your project.

다른 팁

userInput[0], you're assuming that array has at least one item in it and the reference isn't null. Neither of those things are guaranteed. Some error checking would be good, you could also just pass a command line argument to the program when you invoke it.

You must call that program with commandline arguments. Otherwise, userInput does not contain any element. Then, userInput[0] will trigger this error.

BTW, it helps to look at the stacktrace of the exception in order to find the culprit more easily. It would have pointed you to the corresponding line.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top