This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Console Applications and %ERRORLEVEL%

When developing console applications that may be launched from batch files it can be helpful to return an integer to indicate the final status of the program. This value can be interrogated in the batch file using the %ERRORLEVEL% environment variable.


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)
    Console.WriteLine("Type 'Hello'");
    if (string.Compare(Console.ReadLine(), "Hello", true) == 0)
        return 0;
        return 123;

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.

@echo off

IF NOT %ERRORLEVEL% == 0 goto error

echo OK
goto end

echo Failed with error code %ERRORLEVEL%.

1 March 2013