Exit in C#
Here’s an idiomatic C# example that demonstrates the concept of exiting a program with a specific status code:
using System;
class Program
{
static void Main()
{
// This line will not be executed due to the immediate exit
Console.WriteLine("This line will not be printed.");
// Exit the program with status code 3
Environment.Exit(3);
// This line will never be reached
Console.WriteLine("This line will also not be printed.");
}
}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
Systemnamespace, which contains theEnvironmentclass we’ll use to exit the program.We define a
Programclass with aMainmethod, which is the entry point of our C# application.Inside
Main, we have aConsole.WriteLinestatement 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.WriteLinestatement 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:
csc ExitExample.csThis will create an executable file named ExitExample.exe.
- Run the program:
ExitExample.exeTo check the exit code in Windows PowerShell, you can use:
$LastExitCodeThis 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.