C# | Command Line Arguments
The arguments which are passed by the user or programmer to the Main() method is termed as Command-Line Arguments. Main() method is the entry point of execution of a program. Main() method accepts array of strings. But it never accepts parameters from any other method in the program. In C# the command line arguments are passed to the Main() methods by stating as follows:
static void Main(string[] args) or static int Main(string[] args)
Note : To enable command-line arguments in the Main method in a Windows Forms Application, one must manually modify the signature of Main in program.cs. Windows Forms designer generates code and creates Main without an input parameter. One can also use Environment.CommandLine or Environment.GetCommandLineArgs to access the command-line arguments from any point in a console or Windows application.
Example:
// C# program to illustrate the // Command Line Arguments using System; namespace ComLineArg { class Beginner { // Main Method which accepts the // command line arguments as // string type parameters static void Main( string [] args) { // To check the length of // Command line arguments if (args.Length > 0) { Console.WriteLine( "Arguments Passed by the Programmer:" ); // To print the command line // arguments using foreach loop foreach (Object obj in args) { Console.WriteLine(obj); } } else { Console.WriteLine( "No command line arguments found." ); } } } } |
To Compile and execute the above program follow below commands :
Compile: csc Beginner.cs Execute: Beginner.exe Welcome To w3wiki!
Output :
Arguments Passed by the Programmer: Welcome To w3wiki!
In above program Length is used to find the number of command line arguments and command line arguments will store in args[] array. With the help of Convert class and parse methods, one can also convert string argument to numeric types. For examples:
long num = Int64.Parse(args[0]); or long num = long.Parse(args[0]);
This will changes the string to a long type by using the Parse method. It is also possible to use the C# type long, which aliases Int64. Similarly one can parse using predefined parsing methods in C#.
Reference:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/command-line-arguments