Exit in C#
Here’s an idiomatic C# example that demonstrates the concept of exiting a program with a specific status code:
This C# program demonstrates how to exit a program immediately with a specific status code. Here’s a breakdown of the code:
We import the
System
namespace, which contains theEnvironment
class we’ll use to exit the program.We define a
Program
class with aMain
method, which is the entry point of our C# application.Inside
Main
, we have aConsole.WriteLine
statement that won’t be executed due to the immediate exit.We use
Environment.Exit(3)
to immediately terminate the program with an exit code of 3. This is equivalent to theos.Exit(3)
call in the Go example.The second
Console.WriteLine
statement will never be reached because the program exits before it.
To compile and run this program:
- Save the code in a file named
ExitExample.cs
. - Open a terminal and navigate to the directory containing the file.
- Compile the code using the C# compiler:
This will create an executable file named ExitExample.exe
.
- Run the program:
To check the exit code in Windows PowerShell, you can use:
This should display 3
, which is the exit code we specified.
In C#, unlike languages like C or Go, the Main
method can return an int
to indicate the exit status. However, using Environment.Exit
allows you to exit the program immediately from any point in your code, not just at the end of Main
.
It’s important to note that any pending finally
blocks or finalizers will not be executed when using Environment.Exit
. If you need to ensure cleanup code is run, consider using a try
-finally
block or implementing the IDisposable
interface and properly disposing of resources before calling Environment.Exit
.