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:
Imports System
Module ExitExample
Sub Main()
' This Console.WriteLine will be executed
Console.WriteLine("Starting the program...")
' AddHandler to catch the AppDomain.ProcessExit event
AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf OnProcessExit
' 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)
End Sub
Sub OnProcessExit(sender As Object, e As EventArgs)
' This will be called when the process exits
Console.WriteLine("Exiting the program...")
End Sub
End ModuleThis 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
Systemnamespace to useConsoleandEnvironmentclasses.The
Mainsubroutine is the entry point of our program.We use
Console.WriteLineto print a message at the start of the program.We add an event handler for
AppDomain.CurrentDomain.ProcessExitto 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
OnProcessExitsubroutine 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:
vbc ExitExample.vb- Run the compiled executable:
ExitExample.exeYou should see output similar to:
Starting the program...
Exiting the program...To check the exit code in Windows PowerShell, you can use:
$LastExitCodeThis 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.