Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

`Environment.Exit(0)` after printing a report

End the entire process after printing a report and signal success with exit code `0`. Learn when returning from `Main` is the better choice.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

System.Environment.Exit(0);

The lesson phrase “Environment.Exit(0) after the report” means calling Environment.Exit(0) after printing the report. Exit(int exitCode) is a static method on System.Environment. It has a void return type and does not return control to its caller. By convention, 0 indicates success. The application and its caller define what the codes mean: a nonzero code can indicate an error or another outcome. The exit code goes to the operating system, not into the report text.

Call it only after printing the report, flushing any buffers that need it, and finishing necessary cleanup. Exit does not wait for other threads. If you call it from a try or catch block, pending finally blocks do not run.

If you only need to signal success on normal shutdown, prefer return 0; from static int Main(). Returning runs the applicable finally blocks, and the process can stay alive until foreground threads finish. Assigning Environment.ExitCode = 0; sets the exit status but does not itself terminate the process.

Examples

using System;

internal static class Program
{
    private static void Main()
    {
        try
        {
            Console.WriteLine("Report: 3 items processed.");
            Console.Out.Flush();
            Environment.Exit(0);
        }
        finally
        {
            Console.WriteLine("Cleanup");
        }
    }
}

Result

Report: 3 items processed.

The example prints the report and flushes standard output with `Console.Out.Flush()` before exiting. The `Cleanup` line in `finally` does not appear. Check status `0` separately in the shell.

Related lessons

  • C# · Lesson 43 · Basic · Version: 3

Sources