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?
14 Answers
Three options:
- You can return it from
Main
if you declare yourMain
method to returnint
. - 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.

- 30,738
- 21
- 105
- 131

- 34,421
- 21
- 109
- 151
-
17For those of you who wonder why this does not work in their case, make sure your project is compiled as a "Console application" and not as a "Windows application". – Marcel Gosselin Apr 07 '12 at 04:11
-
11what if I have a WinForms app that with some args I want it to behave as a console app? – sebagomez Sep 07 '12 at 16:27
-
5You can also just type the maine program as int (replace void by int) and use e.g. "return -1;" to return from the main program. This is more portable than Environment.Exit() (which depends on the environment). – werner Jun 06 '13 at 11:27
-
There's no need to change the return type of `Main` from `void` to `int`; simply use `return;` instead of `return -1;` – Danny Beckett Oct 03 '13 at 03:19
-
15@DannyBeckett By convention, an exit code of `0` means success, and non-zero means failure. `return;` indicates success through exit code `0`, and `return -1;` indicates failure. – allonhadaya Nov 20 '13 at 15:42
-
7You can also set the exit code using properties: Environment.ExitCode = -1; – t3b4n Aug 31 '16 at 19:10
-
1@marcel-gosselin It works even as "Windows Application" but when you wait for process termination. In case of using return code from Windows Application in windows batch script -> change call from "myApp.exe" to "start /wait myApp.exe" and then check %errorlevel%. This did the trick for me :) – badsamaritan Sep 13 '16 at 17:36
-
1Please note @Vern DeHaven's [answer below](http://stackoverflow.com/a/39986501/2822719): simply returning an int will **not** work anymore in `C# 6.0`/`Visual Studio 2015`. (Ran into this myself - very confusing!) – Marcus Mangelsdorf Dec 01 '16 at 14:01
-
The [MSDN documentation](https://msdn.microsoft.com/en-us/library/system.environment.exitcode(v=vs.110).aspx) has a great example including usage of the example within a batch file. – user3613932 Jul 27 '17 at 02:41
-
2) worked in a [.NET Core](https://en.wikipedia.org/wiki/.NET_Core) console application on Linux: Use of `Environment.Exit(42);` in C# and `echo $?` in Bash. The most likely version of .NET Core was 3.1.21-1 (though there is also ".NET Host" 6.0.1)). The Linux system was [Ubuntu MATE 20.04](https://en.wikipedia.org/wiki/Ubuntu_MATE#Releases), but with [Cinnamon](https://en.wikipedia.org/wiki/Cinnamon_(desktop_environment)). The significant date for the build tools was approximately 2021-10 (one update behind). The signature for `Main()` was `static void Main(string[] args)`. It printed `42`. – Peter Mortensen Jan 18 '22 at 20:52
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;
}

- 44,709
- 21
- 151
- 275

- 84,552
- 17
- 108
- 152
-
57You 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 Oct 01 '08 at 05:36
-
2I'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 Aug 07 '09 at 10:47
-
21You say that 0 is the standard value for success, and yet when converting 0/1 to boolean, 0 is false and 1 is true! It may be more accurate to say that an exit code of 0 means "no error", rather than "success", as the exit code is an ErrorResult not simply a Result. – Mark Shapiro Oct 20 '12 at 01:08
-
11For the complete list of microsoft convention, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx. Some guy has made a huge list of consts and used it in a switch case in comments further below. – nawfal Jan 10 '14 at 10:27
-
6@MarkShapiro, I guess `0 = Success` comes from the fact that there is only one success code needed, but many error codes, such that 0, as having no + or - in Computer integers, can be used to uniquely identify success – Sebastian Mar 11 '14 at 12:54
-
-
@MarkShapiro One could look at it as the exit code being an indication of whether the program exited abnormally (and if so, in what manner). In that case, `false` being the standard return value for normal termination makes perfect sense (and more importantly, makes it easier to use an `if (exit code) { handle error; }` paradigm). – Justin Time - Reinstate Monica Aug 22 '18 at 23:44
-
The `glibc` docs about exit status might be of interest here. These values are defined in `stdlib.h`: https://www.gnu.org/software/libc/manual/html_node/Exit-Status.html – Per Lundberg Jan 09 '21 at 11:02
There are three methods that you can use to return an exit code from a console application.
- Modify the
Main
method in your application so that it returns anint
instead ofvoid
(a function that returns anInteger
instead ofSub
in VB.NET) and then return the exit code from that method. - Set the Environment.ExitCode property to the exit code. Note that method 1. takes precedence - if the
Main
method returns anything other thanvoid
(is aSub
in VB.Net) then the value of this property will be ignored. - Pass the exit code to the Environment.Exit method. This will terminate the process immediately as opposed to the other two methods.
An important standard that should be observed is that 0
represents 'Success'.
On a related topic, consider using an enumeration to define the exit codes that your application is going to return. The FlagsAttribute will allow you to return a combination of codes.
Also, ensure that your application is compiled as a 'Console Application'.

- 30,738
- 21
- 105
- 131

- 13,369
- 3
- 74
- 80
-
2This brings up an interesting point. Setting `Environment.ExitCode` doesn't close the program immediately but `Environment.Exit` method closes the program immediately – PsychoData Apr 18 '14 at 16:41
-
2Exit code also works on windows applications. If the app would be started from c#, through a `Process` object, you can ask the object to `WaitForExit()`, and then request the exit code from it. – Nyerguds Apr 29 '14 at 10:56
If you are going to use the method suggested by David, you should also take a look at the [Flags] Attribute.
This allows you to do bit wise operations on enums.
[Flags]
enum ExitCodes : int
{
Success = 0,
SignToolNotInPath = 1,
AssemblyDirectoryBad = 2,
PFXFilePathBad = 4,
PasswordMissing = 8,
SignFailed = 16,
UnknownError = 32
}
Then
(ExitCodes.SignFailed | ExitCodes.UnknownError)
would be 16 + 32. :)

- 30,738
- 21
- 105
- 131

- 473
- 4
- 2
-
4This implies that a program would say 'your password is wrong' then go on to try and sign whatever it's signing, and only stop if it then fails. You should return once you have failed; anything else is a warning and the program should still return 0. – Pete Kirkham Sep 02 '15 at 07:47
-
3Little known fact is that [Flags] does nothing to enable or disable bitwise operations. All it does is override the ToString method so that the output represents the bitwise flags. With or without it, you can still do bitwise operations. – Steven Berkovitz Aug 03 '16 at 18:26
-
4@Steven that's nice to know but I'd still recommend decorating enums intended for "flag usage" with that attribute, if nothing else it conveys intention. – MarioDS Nov 07 '17 at 10:29
int code = 2;
Environment.Exit( code );

- 26,407
- 4
- 40
- 48
-
19Any technical reason you didn't just write "Environment.Exit( 2 );" ? – Blorgbeard Sep 30 '08 at 23:57
-
64Assigning a magic number to a variable with a meaningless name does not make it any less magic. – Blorgbeard Oct 13 '15 at 20:37
-
3@Blorgbeard - Seven years has elapsed between your two comments. That's kinda epic. :-D – Tornseglare Mar 21 '22 at 10:53
-
3@Tornseglare I'm looking forward to update on this. Should be coming in a few months :) – El Ronnoco Jun 17 '22 at 13:48
-
Just return the appropiate code from main.
int Main(string[] args)
{
return 0; // Or exit code of your choice
}

- 30,738
- 21
- 105
- 131

- 29,284
- 24
- 107
- 141
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.

- 30,738
- 21
- 105
- 131

- 28,043
- 9
- 61
- 79
As an update to Scott Munro's answer:
- In C# 6.0 and VB.NET 14.0 (Visual Studio 2015), either Environment.ExitCode or Environment.Exit(exitCode) is required to return an non-zero code from a console application. Changing the return type of
Main
has no effect. - In F# 4.0 (Visual Studio 2015), the return value of the
main
entry point is respected.

- 30,738
- 21
- 105
- 131

- 136
- 1
- 6
-
2Can your 1st point regarding C# 6 be verified? I can't seem to find anything online. The return value from the Main function is attached to the exit code of the process (at least in all the previous compilers), why they should have changed that? – Arman Oct 27 '16 at 12:02
-
Pure anecdotal evidence, but I just ran into this in my own library, where simply returning my result/error code from `Main()` didn't set the `Process.ExitCode` as seen by the calling application. – Marcus Mangelsdorf Dec 01 '16 at 13:59
-
1MSDN contends `int Main` is still can be used as an alternative to Environment.ExitCode. [link](https://msdn.microsoft.com/en-us/library/system.environment.exitcode.aspx) – Arman Dec 02 '16 at 16:28
-
1I have an application that runs multiple threads. In certain circumstances, I need to clobber some threads via Thread.Abort(), prior to exiting the application. In these circumstances, int Main(){...thread.Abort(); ... return 0;} does NOT result in a process exit code of 0: the process exit code is -1. It seems in certain circumstances, MS has decided that the convention of using the return value of the main thread to set the exit code of the process, is not good enough for them. In fairness, it might be a timing issue: the thread abort might be setting the exit code very late in the game. – David I. McIntosh Dec 13 '16 at 17:25
The enumeration option is excellent. However, it can be improved upon by multiplying the numbers as in:
enum ExitCodes : int
{
Success = 0,
SignToolNotInPath = 1,
AssemblyDirectoryBad = 2,
PFXFilePathBad = 4,
PasswordMissing = 8,
SignFailed = 16,
UnknownError = 32
}
In the case of multiple errors, adding the specific error numbers together will give you a unique number that will represent the combination of detected errors.
For example, an errorlevel of 6 can only consist of errors 4 and 2, 12 can only consist of errors 4 and 8, 14 can only consist of 2, 4 and 8 etc.

- 30,738
- 21
- 105
- 131

- 958
- 2
- 12
- 29
-
3That is if you bother to check for further errors after encountering one, though. Most apps don't. – Nyerguds Apr 29 '14 at 10:59
You can find the system error codes on System Error Codes (0-499).
You will find the typical codes, like 2 for "file not found" or 5 for "access denied".
And when you stumble upon an unknown code, you can use this command to find out what it means:
net helpmsg decimal_code
For example,
net helpmsg 1
returns
Incorrect function

- 30,738
- 21
- 105
- 131

- 1,219
- 1
- 11
- 10
Use this code
Environment.Exit(0);
use 0 as the int if you don't want to return anything.

- 97
- 2
- 2
- 9
-
1This isn't answering OP's question and returning 0 is returning something... – P-L Jan 09 '20 at 13:30
-
1it's returning what an app normally returns. If you don't specify it, an app return 0 – John Lord Aug 03 '20 at 14:58
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.

- 30,738
- 21
- 105
- 131

- 1
- 2
-
That didn't even compile - *[Environment](https://learn.microsoft.com/en-us/dotnet/api/system.environment.exit?view=net-6.0)* misspelled as *Enviroment*. – Peter Mortensen Jan 17 '22 at 21:19
-
What will happen when the exception is thrown (presumably not caught anywhere in the console application)? What is ***the resulting exit code*** (the question was *"How do I specify the exit code of a console application in .NET?"*)? Can you provide a working example (that actually compiles)? Can you back it up with references to documentation? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/68150110/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Jan 17 '22 at 21:23
Just another way:
public static class ApplicationExitCodes
{
public static readonly int Failure = 1;
public static readonly int Success = 0;
}

- 30,738
- 21
- 105
- 131

- 8,446
- 12
- 60
- 87
-
How does that answer the question? Is it a response to another answer, like [Mark Brackett's answer](https://stackoverflow.com/questions/155610/how-do-i-specify-the-exit-code-of-a-console-application-in-net/156134#156134)? – Peter Mortensen Jan 17 '22 at 21:16