Using C# Return Codes in Batch Files

Its been common in my experience to use batch or command files for automation of simple tasks.  Sometimes you need just a little more flexibility than the batch language has.  One way to deal with this is to write a command line program to handle the extra work.  Since error levels can be used in batch files to control flow it would be nice to be able to communicate the success or failure to of the command line program back to the batch file.  It turns out this is really easy.  Below is the basic command line program you get from visual studio.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args) {
        }
    }
}

The main function has a return type of void.  If we change that to int then we have the opportunity to give some information back to the batch file.  The example below has the return value changed and does a simple comparison to see which number to return to the batch file.

namespace AppExitTest
{
      class Program
      {
            static int Main(string[] args) {
                  int returnVal = 0;
                  if(args[0] == “true”) {
                        returnVal = 23412341;
                  }
                  return returnVal;
            }
      }
}

This returns an int which can be read out of the %ERRORLEVEL% variable in a batch file.  Below is a batch file which demonstrates both paths in the command line program.

echo off
appexittest.exe false
echo %ERRORLEVEL%
appexittest.exe true
echo %ERRORLEVEL%

This batch file gives the result:

echo off
0
23412341