CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Specifying an Application Error Code
While a vast majority of your Main() methods will return void as the return value, the ability to return an
int from Main() keeps C# consistent with other C-based languages. By convention, returning the value 0
indicates the program has terminated successfully, while another value (such as -1) represents an error
condition (be aware that the value 0 is automatically returned, even if you construct a Main() method
prototyped to return void).
On the Windows operating system, an application’s return value is stored within a system
environment variable named %ERRORLEVEL%. If you were to create an application that programmatically
launches another executable (a topic examined in Chapter 17), you can obtain the value of %ERRORLEVEL%
using the static System.Diagnostics.Process.ExitCode property.
Given that an application’s return value is passed to the system at the time the application
terminates, it is obviously not possible for an application to obtain and display its final error code while
running. However, to illustrate how to view this error level upon program termination, begin by
updating the Main() method, as follows:
// Note we are now returning an int, rather than void.
static int Main(string[] args)
{
// Display a message and wait for Enter key to be pressed.
Console.WriteLine("***** My First C# App *****");
Console.WriteLine("Hello World!");
Console.WriteLine();
Console.ReadLine();
// Return an arbitrary error code.
return -1;
}
Now let’s capture the return value of Main() with the help of a batch file. Using Windows Explorer,
navigate to the folder containing your compiled application (for example,
C:\SimpleCSharpApp\bin\Debug). Add a new text file (named SimpleCSharpApp.bat) to the Debug folder
that contains the following instructions (if you have not authored *.bat files before, don’t concern
yourself with the details; this is a test . . . this is only a test):
@echo off
rem A batch file for SimpleCSharpApp.exe
rem which captures the app's return value.
SimpleCSharpApp
@if "%ERRORLEVEL%" == "0" goto success
:fail
echo This application has failed!
echo return value = %ERRORLEVEL%
goto end
:success
echo This application has succeeded!
echo return value = %ERRORLEVEL%
goto end
:end
76