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?
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#.
Exit(), Application. ExitThread(), Environment. Exit(), etc.
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.
Three options:
Main
if you declare your Main
method to return int
.Environment.Exit(code)
.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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With