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

Solution 1:

3 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 app, etc) different methods can be used.

Solution 2:

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;
}

Solution 3:

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'.