Discussion on parameters of Main method

  • 2021-09-04 23:58:13
  • OfStack

You can send parameters to Main methods by defining methods in one of the following ways.

static int Main(string[] args)

static void Main(string[] args)

[Note] To enable command-line arguments in the Main method in an Windows Forms application, you must manually modify the signature of Main in program. cs. The code generated by the Windows form designer creates an Main without input parameters. You can also use Environment. CommandLine or Environment. GetCommandLineArgs to access command line parameters from anywhere in the console or Windows application.

The arguments to the Main method are an String array that represents command-line arguments. 1 generally tests the Length property to determine whether a parameter exists, such as:


  if (args.Length == 0)
  {
   WriteLine("Hello World.");
   return 1;
  }   

You can also use the Convert class or the Parse method to convert string parameters to numeric types. For example, the following statement converts an string to an long number using the Parse method:

long num = Int64.Parse(args[0]);  

You can also use C # Type long with the alias Int64:

long num = long.Parse(args[0]);  

You can also do the same using the method ToInt64 of the Convert class:

long num = Convert.ToInt64(s);  

Example

The following example demonstrates how to use command line parameters in a console application. The application takes 1 parameter at run time, converts that parameter to an integer, and calculates the factorial of that number. If no parameters are provided, the application sends a message explaining the correct use of the program.


public class Functions
 {
 public static long Factorial(int n)
 {
 if ((n < 0) || (n > 20))
 {
 return -1;
 }
 long tempResult = 1;
 for (int i = 1; i <= n; i++)
 {
 tempResult *= i;
 }
 return tempResult;
 }
 }
 class MainClass
 {
 static int Main(string[] args)
 {
 // Test if input arguments were supplied:
 if (args.Length == 0)
 {
 Console.WriteLine("Please enter a numeric argument.");
 Console.WriteLine("Usage: Factorial <num>");
 return 1;
 }
 int num;
 bool test = int.TryParse(args[0], out num);
 if (test == false)
 {
 Console.WriteLine("Please enter a numeric argument.");
 Console.WriteLine("Usage: Factorial <num>");
 return 1;
 }
 long result = Functions.Factorial(num);
 if (result == -1)
 Console.WriteLine("Input must be >= 0 and <= 20.");
 else
 Console.WriteLine("The Factorial of {0} is {1}.", num, result);

 return 0;
 }
 }

Related articles: