Home >Backend Development >C++ >How Do I Set the Exit Code of a .NET Console Application?

How Do I Set the Exit Code of a .NET Console Application?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-05 17:34:42837browse

How Do I Set the Exit Code of a .NET Console Application?

Setting the Exit Code of a .NET Console Application

In .NET, determining the exit code of a console application allows you to specify the status of your program when it terminates. There are several ways to accomplish this:

1. Return Value from Main

If the Main method is declared to return an integer, the value returned will be the exit code. For example:

public static int Main()
{
    // ... application logic ...

    return 0; // Success
}

2. Environment.Exit Method

Alternatively, you can call the Environment.Exit method with the desired exit code as an argument. This will immediately terminate the application. For instance:

public static void Main()
{
    // ... application logic ...

    Environment.Exit(1); // Failure
}

3. Environment.ExitCode Property

You can also set the exit code using the Environment.ExitCode property. This property will be used if no other method explicitly sets the exit code. For example:

public static void Main()
{
    // ... application logic ...

    Environment.ExitCode = -1; // Error
}

Considerations

The specific method to use depends on the type of application you are creating. For instance, console applications utilize the Main method, while services may use Environment.Exit. Additionally, different operating systems may interpret exit codes differently. It is recommended to consult the documentation for specific platforms for guidance.

The above is the detailed content of How Do I Set the Exit Code of a .NET Console Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn