tags:

views:

7589

answers:

6

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

Thanks!

+10  A: 
int code = 2;
Environment.Exit( code );
palehorse
Any technical reason you didn't just write "Environment.Exit( 2 );" ?
Blorgbeard
No, not really. Just trying to be clear.
palehorse
+9  A: 
System.Environment.ExitCode

http://msdn.microsoft.com/en-us/library/system.environment.exitcode.aspx

AlbertEin
+2  A: 

Just return the appropiate code from main.

int main(string[] args)
{
      return 0; //or exit code of your choice
}
Esteban Araya
+19  A: 

you can return it from Main if you declare your Main method to return an int, or call Environment.Exit(code)

TheSoftwareJedi
+3  A: 

Use ExitCode if your main has a void return signature, otherwise you need to "set" it by the value you return.

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.

crashmstr
+5  A: 

Not an answer - the return int's have already gotten that...but 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;
}
Mark Brackett
You might want to add, that the value of "0" for "Success" is not by chance, but actually the "standard" value for that situation.
Christian.K
I'm aware that 0 is standard for sucess.Is there a agreed convention for other exit codes or is it just a free for all? (I presume these are the same numbers you get back after running a scheduled task).
AndyM