Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Environment.Exit(0): terminate the process with exit code 0

`Environment.Exit(0)` ends the current process with a success status. Assigning to `Environment.ExitCode` only sets the status and lets the program continue.

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

Syntax

System.Environment.Exit(0);
// API signature: public static void Exit(int exitCode);

In a C# 12 console app on .NET 8, Environment.Exit(0) immediately ends the current process, even if other threads are still running. Exit(int exitCode) is a static method on System.Environment. It returns void: the code goes to the operating system, not back to the method's caller. By convention, 0 means success and a nonzero code usually indicates an error.

Assigning Environment.ExitCode = 0; sets a property but lets execution continue. To finish normally from an int-returning Main, use return 0;. Returning from a helper method only gives control back to its caller; it does not end the process.

If you call Exit inside a try or catch block, pending finally blocks do not run. If you need to release resources or wait for work to finish, do so before calling Exit or return normally from Main. Library code should leave the decision to end the whole process to the application that uses it.

Examples

using System;

Environment.ExitCode = 0;

try
{
    Console.WriteLine("Report complete.");
    Environment.Exit(0);
    Console.WriteLine("After Exit.");
}
finally
{
    Console.WriteLine("Finally ran.");
}

Result

Report complete.

The program prints `Report complete.` after the property assignment. `Environment.Exit(0)` then ends the process with status `0`, so neither `After Exit.` nor `Finally ran.` appears. The exit status is separate from the text the program prints.

Related lessons

  • C# · Lesson 15 · Advanced · Version: 3
  • C# · Lesson 19 · Advanced · Version: 3
  • C# · Lesson 16 · Basic · Version: 3
  • C# · Lesson 40 · Basic · Version: 3
  • C# · Lesson 35 · Intermediate · Version: 2

Sources