Partager via


Main() Return Values (C# Programming Guide) 

The Main method can be of the type void:

static void Main()
{
    //...
}

It can also return an int:

static int Main()
{
    //...
    return 0;
}

If the return value from Main is not to be used, then returning void allows slightly simpler code. However, returning an integer enables the program to relate status information to other programs or scripts that invoke the executable. An example of using the return value from Main is shown in the following example.

Example

In this example a batch file is used to execute a program and test the return value of the Main function. When a program is executed in Windows, any value returned from the Main function is stored in an environment variable called ERRORLEVEL. By inspecting the ERRORLEVEL variable, batch files can therefore determine the outcome of execution. Traditionally, a return value of zero indicates successful execution. Below is a very simple program that returns zero from the Main function.

class MainReturnValTest
{
    static int Main()
    {
        //...
        return 0;
    }
}

Because this example uses a batch file, it is best to compile this code from the command line, as demonstrated in How to: Build from the Command Line.

Next, a batch file is used to invoke the executable resulting from the previous code example. Because the code returns zero, the batch file will report success, but if the previous code is changed to return a non-zero value, and is then re-compiled, subsequent execution of the batch file will indicate failure.

rem test.bat
@echo off
MainReturnValueTest
@if "%ERRORLEVEL%" == "0" goto good

:fail
    echo Execution Failed
    echo return value = %ERRORLEVEL%
    goto end

:good
    echo Execution Succeded
    echo return value = %ERRORLEVEL%
    goto end

:end

Sample Output

Execution Succeded

return value = 0

See Also

Tasks

How to: Display Command Line Arguments (C# Programming Guide)
How to: Access Command-Line Arguments Using foreach (C# Programming Guide)

Reference

Main() and Command Line Arguments (C# Programming Guide)

Concepts

C# Programming Guide

Other Resources

C# Reference