How do I specify the exit code of a console application in .NET?

If you are going to use the method suggested by David, you should also take a look at the [Flags] Attribute.

This allows you to do bit wise operations on enums.

[Flags]
enum ExitCodes : int
{
  Success = 0,
  SignToolNotInPath = 1,
  AssemblyDirectoryBad = 2,
  PFXFilePathBad = 4,
  PasswordMissing = 8,
  SignFailed = 16,
  UnknownError = 32
}

Then

(ExitCodes.SignFailed | ExitCodes.UnknownError)

would be 16 + 32. :)


There are three methods that you can use to return an exit code from a console application.

  1. Modify the Main method in your application so that it returns an int instead of void (a function that returns an Integer instead of Sub in VB.NET) and then return the exit code from that method.
  2. Set the Environment.ExitCode property to the exit code. Note that method 1. takes precedence - if the Main method returns anything other than void (is a Sub in VB.Net) then the value of this property will be ignored.
  3. Pass the exit code to the Environment.Exit method. This will terminate the process immediately as opposed to the other two methods.

An important standard that should be observed is that 0 represents 'Success'.

On a related topic, consider using an enumeration to define the exit codes that your application is going to return. The FlagsAttribute will allow you to return a combination of codes.

Also, ensure that your application is compiled as a 'Console Application'.


Three options:

  • You can return it from Main if you declare your Main method to return int.
  • You can call Environment.Exit(code).
  • You can set the exit code using properties: Environment.ExitCode = -1;. This will be used if nothing else sets the return code or uses one of the other options above).

Depending on your application (console, service, web application, etc.), different methods can be used.


In addition to the answers covering the return int's... a plea for sanity. Please, please define your exit codes in an enum, with Flags if appropriate. It makes debugging and maintenance so much easier (and, as a bonus, you can easily print out the exit codes on your help screen - you do have one of those, right?).

enum ExitCode : int {
  Success = 0,
  InvalidLogin = 1,
  InvalidFilename = 2,
  UnknownError = 10
}

int Main(string[] args) {
   return (int)ExitCode.Success;
}

Tags:

C#

.Net

Exit Code