Hi all, i'm new to C#, and as i try to debug the following code, i take the error : "Index was outside the bounds of the array. " in line : Console.WriteLine(args[0]); . The source code is the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Password
{
class Password
{
static void Main(String[] args)
{
Console.Write("Type your password");
Console.WriteLine(" ");
Console.WriteLine(args[0]);
if (args[0].StartsWith("JAVA"))
Console.WriteLine ("Ok, You have typed the correct" + "Password");
else
Console.WriteLine("ERROR!");
Console.ReadLine();
}
}
}
I cannot fix this. Since i declare [0] size of args, what is the problem ?? Thanks in advance guys

2 answers
If you pass any arguments to your program when you run it from the command line, then these arguments are stored in the 'args' array. I'd imagine you're not doing this and so 'args' will be empty.
If you want the user to input a password which you then check for correctness, I'd store it in a string variable. Something like this:
answered one year ago by:
17279
3
Thanks a lot! This is what i was trying to do in order to fix this error, but the source code i published is an example for amateurs from a book chapter and i tried to run it. Probably he is wrong.. If i declare an array "args[]" and declare its size, would it run ?
17279
Well, the compiler wouldn't let you declare another array called 'args' in the Main() method because it would conflict with the parameter of the same name. If the user were passing the password when invoking the program (rather than being asked for it when the program starts), then args[0] would automatically contain the password. Perhaps this is where the confusion lies?
The args[] array contains command line parameters as vulpes said. If none are passed, that array has a size of 0 entries. Since arrays start with indexes at 0, 0 is actually the first item. There is no first item in a list of 0 items, hence your error message.
Once you get more advanced, you can do something like this to actually check for command line arguments:
if (args.Length == 0) { Console.WriteLine("No command line arguments were passed!"); }fm
answered one year ago by:
490