|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
Main() Return Values (C# Programming Guide)
Main method can be of the type void:
It can also return an int:
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.
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
Because this example uses a batch file, it is best to compile this code from the command line, as demonstrated in.
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