Many commands and programs that can be executed from a command line return an integer value. By convention, the returned value is zero if the program completed without error. If there was a problem running the code, the return value is often an error code that you can examine in order to take an appropriate action.
Returning a Value from a Console Application
If you are developing a console application that might be called from a batch file, you may wish to follow the above pattern and return an error value. This is actually very simple. All that you need to do is modify the signature of the Main method of your project so that it returns an integer.
The following simple program shows this. This code asks for user input. If you type "Hello", the return value is zero. If not, an error code of 123 is returned.
static int Main(string args)
if (string.Compare(Console.ReadLine(), "Hello", true) == 0)
To access the return value in your batch file you need to check the %ERRORLEVEL% environment variable immediately after your console application terminates. For example, the batch file below calls the compiled executable, which in this sample is named EnterHello.exe. On completion, the %ERRORLEVEL% variable is checked and a message displayed according to its value.
IF NOT %ERRORLEVEL% == 0 goto error
echo Failed with error code %ERRORLEVEL%.
1 March 2013