4

I'm a beginner in learning programming. I ask about using the string array in main method as a parameter. Why not writing the Main() method without the string array? What is the point of having this array in Main method?

For example:

public static void Main(string[] args) 
{
Console.WriteLine(args.Length);
Console.WriteLine(args[1]);
}
gnat
  • 20,543
  • 29
  • 115
  • 306
Makeed
  • 49
  • 1
  • 1
  • 2

3 Answers3

19

Console applications predate GUI applications, and these take command-line parameters for very long time (at least from CP/M time, which preceded MS-DOS, which preceded Windows, which preceded Windows NT — all preserving more or less the same logic).

You can pass command-line parameters to Windows GUI apps, too.

These are the args.

9000
  • 24,342
7

This is not the sole province of "old" console (command line) applications. Every running program has a "command line" that points at the executable image and includes any command line parameters. Plenty of GUI apps take arguments that alter either their initialization behavior or runtime behavior or both.

Most languages do let you specify an entry-point function that takes no arguments. But virtually all of them also allow you to pass arguments. This args array is simply an ordered collection of whatever is passed on the command line after the name of the executable file when the program is executed. EDIT: And of course in the case of the C language (as one example), the first argument (index 0) is actually the name of the program.

For example, imagine a pointless little program that displays a message in a message box, and lets you specify the message and the title for the window on the command line, like this:

myprogram.exe -title Foo -message Bar

Your args array in this case will look like this, presuming a language like C# which does not include the program name in the args array:

args[ 0 ] = "-title"
args[ 1 ] = "Foo"
args[ 2 ] = "-message"
args[ 3 ] = "Bar"

Making sense of the order of the arguments, and which ones are valid or not, is totally up to your own application code.

Craig Tullis
  • 1,985
1

Have you ever listed items in a directory using

ls -a ~/Downloads

or

dir C:\Users\user1\Downloads\ /P

Now those "ls" and "dir" are commands/programs and the latter arguments are passed to the programs as string[] argv or sometimes int argc, char** argv. They provide arguments to the programs so they can behave accordingly.

When you start a program the OS loads the program to the memory and pushes the arguments to the stack. Now they are available to the program to be used.

High-level languages give you an easy way to access those arguments on the stack (as string arrays or an array of pointers to null terminated strings). If you used assembly, you would need to do some pointer arithmetic and load the arguments from stack to registers when you needed them.

For more details checkout following link, good explanation: FreeBSD Command Line Arguments