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?
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?
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;
}
Just return the appropiate code from main.
int Main(string[] args)
{
return 0; // Or exit code of your choice
}
Use ExitCode if your main has a void return signature. Otherwise, you need to "set" it by the value you return.
From Environment.ExitCode Property:
If the Main method returns void, you can use this property to set the exit code that will be returned to the calling environment. If Main does not return void, this property is ignored. The initial value of this property is zero.
As an update to Scott Munro's answer:
Main has no effect.main entry point is respected.Use this code
Environment.Exit(0);
use 0 as the int if you don't want to return anything.
I'm doing it like this:
int exitCode = 0;
Environment.Exit(exitCode);
Or you can throw an error (personal preference):
throw new ArgumentException("Code 0, Environment Exit");
I've choose ArgumentException, but you can type other. It will work fine.
Just another way:
public static class ApplicationExitCodes
{
public static readonly int Failure = 1;
public static readonly int Success = 0;
}