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


I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this?

11/20/2013 3:31:41 PM

Accepted Answer

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.

8/23/2018 2:50:56 PM

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;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow