What is the C# equivalent for the Java System.exit(0)?

The C# equivalent for Java's System.exit(0) is the Environment.Exit() method. This method terminates the current process and returns an exit code to the operating system, just like its Java counterpart.

Syntax

Following is the syntax for using Environment.Exit()

Environment.Exit(exitCode);

Parameters

  • exitCode − An integer value returned to the operating system. Use 0 to indicate successful termination, and non-zero values to indicate different error conditions.

Exit Code Conventions

Exit Code Meaning
0 Process completed successfully
1 General error (e.g., file not found)
2 Incorrect file format or invalid arguments
Other non-zero Application-specific error codes

Example

using System;

class Program {
   static void Main(string[] args) {
      Console.WriteLine("Starting application...");
      
      // Simulate some processing
      bool processSuccessful = true;
      
      if (processSuccessful) {
         Console.WriteLine("Process completed successfully!");
         Environment.Exit(0);  // Success
      } else {
         Console.WriteLine("Process failed!");
         Environment.Exit(1);  // Error
      }
      
      // This line will never execute
      Console.WriteLine("This won't be printed");
   }
}

The output of the above code is −

Starting application...
Process completed successfully!

Using Different Exit Codes

using System;
using System.IO;

class FileProcessor {
   static void Main(string[] args) {
      string fileName = "data.txt";
      
      Console.WriteLine("Checking file: " + fileName);
      
      if (!File.Exists(fileName)) {
         Console.WriteLine("Error: File not found!");
         Environment.Exit(1);  // File not found
      }
      
      // Simulate file format check
      bool isValidFormat = false;
      
      if (!isValidFormat) {
         Console.WriteLine("Error: Invalid file format!");
         Environment.Exit(2);  // Invalid format
      }
      
      Console.WriteLine("File processed successfully!");
      Environment.Exit(0);  // Success
   }
}

The output of the above code is −

Checking file: data.txt
Error: File not found!

Comparison with Java

Java C#
System.exit(0) Environment.Exit(0)
Static method in System class Static method in Environment class
Terminates JVM Terminates current process

Conclusion

The Environment.Exit() method is the C# equivalent of Java's System.exit(). It immediately terminates the current process and returns an exit code to the operating system. Use exit code 0 for success and non-zero values for different error conditions.

Updated on: 2026-03-17T07:04:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements