Exit in Visual Basic .NET
Here’s an idiomatic Visual Basic .NET example demonstrating the concept of exiting a program with a specific status code:
This Visual Basic .NET example demonstrates how to exit a program with a specific status code. Let’s break down the key elements:
We import the
System
namespace to useConsole
andEnvironment
classes.The
Main
subroutine is the entry point of our program.We use
Console.WriteLine
to print a message at the start of the program.We add an event handler for
AppDomain.CurrentDomain.ProcessExit
to demonstrate a cleanup or finalization concept similar to Go’sdefer
.The
Environment.Exit(3)
method is used to immediately terminate the program with a status code of 3. This is equivalent to Go’sos.Exit(3)
.The
OnProcessExit
subroutine is our event handler that will be called when the process exits.
To compile and run this program:
- Save the code in a file named
ExitExample.vb
. - Open a command prompt and navigate to the directory containing the file.
- Compile the code using the VB.NET compiler:
- Run the compiled executable:
You should see output similar to:
To check the exit code in Windows PowerShell, you can use:
This should display 3, confirming our custom exit code.
Note that unlike Go, Visual Basic .NET doesn’t have a direct equivalent to Go’s defer
keyword. Instead, we use event handlers or Try
/Finally
blocks for cleanup operations. In this example, we used the ProcessExit
event to simulate a similar behavior.
Also, Visual Basic .NET, being part of the .NET framework, doesn’t require explicit compilation before running. You can use the dotnet run
command with the .NET Core SDK for a more streamlined development experience.