C#. The main() function. Ways of declaration.

The Main() function. Ways of declaration. Passing arguments to the Main() function. The GetCommandLineArgs() method of the Environment class


Contents


1. The purpose of the Main() method. Features of use

The Main() function is a special function that is designed to start execution of any program and has the following features of use:

  • the Main() function is the entry point to any C# program. The term “entry point” means that program execution begins from the Main() function;
  • the Main() function is considered the main function in the program, which can call other functions implemented in the program;
  • the Main() function can receive parameters. Using these parameters, another program can pass some information (data) to the current program;
  • the Main() function can return an integer value that will signal the result of program execution. This is necessary in cases where the program is called from another program (process). Most often, the process that calls the Main() function is the operating system;
  • there can only be one function in the program named Main(). In other words, the Main() function cannot be overloaded;
  • the Main() function is static, that is, at the beginning of the declaration contains a static modifier. This means that the function is called without creating an instance of the class. Static function is necessary, because at the first start no class instances are created yet. There are only static methods and variables. These methods and variables are initialized automatically the first time they are accessed.

 

2. Ways to declare a Main() function

The Main() function can be declared in one of four possible ways, listed below.

Way 1. The function does not return values and does not receive parameters. The general form of the Main() function in this case is as follows:

static void Main()
{
  // actions, operators
  // ...
}

Way 2. The function returns an integer value and does not receive parameters. In this case, the general form of the function is as follows

static int Main()
{
  // actions, operators
  // ...
  return value;
}

Here value is some integer value, which is the result of returning from the program. Other processes running the current program may use this result. For example, if the Main() function returns -1, then this may indicate an internal error. And conversely, if the function returns 0, then this may mean the correct execution of the program.

Way 3. The function does not return a value, but receives parameters. The parameters of the Main() function can be an array of strings. In this case, the general form of the function is as follows:

static void Main(string[] args)
{
  // actions, operators
  // ...
}

here args – an array of strings that is passed to the Main() function from other processes.

Way 4. The function returns an integer value and receives parameters. The general form of function declaration is as follows

static void Main(string[] args)
{
  // actions, operators
  // ...
  return value;
}

here

  • args – an array of strings that is passed to the Main() function from other processes;
  • value – an int value that is passed to the process that called the current program.

 

3. Access modifiers that can be used with the Main() function

The Main() function can be declared with two access modifiers:

  • private – in this case, the Main() function cannot be called directly from other assemblies;
  • public – the Main() function is public from other assemblies.


 

4. Why is an array of strings passed as parameters to the Main() function?

As parameters to any program (Main() function), the calling process (operating system) can pass only a string of characters. If this string contains words that are separated by a space character, then this string is split into an array of strings.

For example. Let the program named Project1.exe be called as follows:

Project1.exe param1 param2 file1.txt

then the Main() function of Project1.exe will receive the following array of input parameters

param1
param2
file1.txt

that is, for the next function declaration

void Main(string[] args)
{
  // ...
}

the values of the args variable will be as follows:

args.Length = 3
args[0] = "param1"
args[1] = "param2"
args[2] = "file1.txt"

 

5. An example that demonstrates the use of parameters in the Main() function

The example shows the output of an array of parameters to the screen. The program was created using the Console Application template.

using System;

namespace ConsoleApp1
{
  class Program
  {
    static void Main(string[] args)
    {
      // An example of displaying an array of args parameters on the screen
      Console.WriteLine("args.Length = {0}", args.Length);

      for (int i = 0; i < args.Length; i++)
      {
        Console.WriteLine("args[{0}] = {1}", i, args[i]);
      }
    }
  }
}

The result of the program named ConsoleApp1.exe for the string

ConsoleApp1 param1 param2 file1.txt

is as follows

args.Length = 3
args[0] = param1
args[1] = param2
args[2] = file1.txt

 

6. Setting parameters that are passed to the Main() function using Microsoft Visual Studio 2019

In Microsoft Visual Studio any version, you can set parameters that are passed to the Main() function. These parameters are also called command-line arguments.

To set command line arguments, use the Properties… command from the Project menu.

For example, if you created a console application with the solution name ConsoleApp1, then you can call the settings window using the command

Project -> ConsoleApp1 Properties...

as shown in the Figure 1.

MS Visual Studio. The command calling the project properties

Figure 1. The command calling the project properties

As a result, the “ConsoleApp1” window opens, in which you need to activate the Debug element (Figure 2). In the left part of the window, in the “Application arguments” field, enter command line arguments. These arguments will be passed to the Main() function. Thus, you can test the call of the current program from other processes by passing the program various options for the arguments.

MS Visual Studio - C#. Main() function. Setting command line arguments

Figure 2. Setting command line arguments

 

7. How do I pass a string that contains spaces to the Main() function?

There are cases where in the Main() function, you need to pass a string as a parameter. But this line may contain spaces. In this case, the string must be enclosed in double quotation marks. Everything that is placed between double quotes is not broken by parameters.

For example. Suppose that you need to pass two string parameters to the Main() function for an application named ConsoleApp1.exe:

  • “This is a parameter”;
  • “Second parameter”.

In this case, calling ConsoleApp1.exe from another process (for example, from the command line) will be as follows:

ConsoleApp1.exe "This is a parameter" "Second parameter"

In this case, the following values of the args array will be passed to the Main() function:

args.Length = 2
args[0] = "This is a parameter"
args[1] = "Second parameter"

 

8. Receiving parameters using the GetCommandLineArgs() method of the Environment class. Example

You can get command line parameters using the GetCommandLineArgs() method of the Environment class. This method is static, and therefore you do not need to create an instance of the Environment class. The method returns an array of arguments of type string[].

It is important to remember that the GetCommandLineArgs() method returns an array of parameters one more. The first parameter that the method returns (under index 0) is the fully qualified name of the current executable file.

Example. Displays a list of parameters passed to the Main() function.

using System;

namespace ConsoleApp1
{
  class Program
  {
    static void Main(string[] args)
    {
      // Display the parameters list using the GetCommandLineArgs () method
      // of Environment class
      string[] parameters = Environment.GetCommandLineArgs();

      Console.WriteLine("Parameters:");

      foreach (string s in parameters)
      {
        Console.WriteLine(s);
      }

      Console.ReadKey();
    }
  }
}

 

9. Determining the full file name of an executable program

The full file name of the executable program can be determined using the static GetCommandLineArgs() method of the Environment class. As you know, the method is used to determine the parameters of the current program in the form of an array of strings of type string[]. When the method is called, the parameter that is returned, with index 0, contains the full file name of the current program.

The following code snippet shows the full file name of the current program

// Print the full path to the file of the current program
string path = Environment.GetCommandLineArgs()[0];
Console.WriteLine("Full path = {0}", path);

 


Related topics