[c#] How do I specify the exit code of a console application in .NET?

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?

This question is related to c# .net exit-code

The answer is


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.


There are three methods that you can use to return an exit code from a console application.

  1. Modify the Main method in your application so that it returns an int instead of void (a function that returns an Integer instead of Sub in VB.Net) and then return the exit code from that method.
  2. Set the Environment.ExitCode property to the exit code. Note that method 1. takes precedence - if the Main method returns anything other than void (is a Sub in VB.Net) then the value of this property will be ignored.
  3. 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'.



Just return the appropiate code from main.

int Main(string[] args)
{
      return 0; //or exit code of your choice
}

Use this code

Environment.Exit(0);

use 0 as the int if you don't want to return anything.


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. :)


My 2 cents:

You can find the system error codes here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx

You will find the typical codes like 2 for "file not found" or 5 for "access denied".

And when you stumble on an unknown code, you can use this command to find out what it means:

net helpmsg decimal_code

e.g.

net helpmsg 1

returns

Incorrect function


int code = 2;
Environment.Exit( code );

Just an another way:

public static class ApplicationExitCodes
{
    public static readonly int Failure = 1;
    public static readonly int Success = 0;
}

As an update to Scott Munro's answer:

  • In C# 6.0 and VB.NET 14.0 (VS 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 (VS 2015), the return value of the main entry point is respected.

The enumeration option is excellent however 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.


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;
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to exit-code

What is a thread exit code? check if command was successful in a batch file Difference between exit(0) and exit(1) in Python Check if process returns 0 with batch file Command /usr/bin/codesign failed with exit code 1 In a Bash script, how can I exit the entire script if a certain condition occurs? Are there any standard exit status codes in Linux? How do I get the application exit code from a Windows command line? Exit codes in Python How do I specify the exit code of a console application in .NET?