Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

exit-code

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?

like image 701
MrDatabase Avatar asked Sep 30 '08 23:09

MrDatabase


People also ask

How do you exit a console program in C#?

Exit() method to exit a console application in C#. The Environment. Exit() method is used to end the execution of a console application in C#.

How do I exit a .NET program?

Exit(), Application. ExitThread(), Environment. Exit(), etc.

What does environment exit do in C#?

Exit terminates an application immediately, even if other threads are running. If the return statement is called in the application entry point, it causes an application to terminate only after all foreground threads have terminated. Exit requires the caller to have permission to call unmanaged code.


2 Answers

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.

like image 125
TheSoftwareJedi Avatar answered Sep 20 '22 17:09

TheSoftwareJedi


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; } 
like image 37
Mark Brackett Avatar answered Sep 21 '22 17:09

Mark Brackett