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 Module

This Visual Basic .NET example demonstrates how to exit a program with a specific status code. Let’s break down the key elements:

  1. We import the System namespace to use Console and Environment classes.

  2. The Main subroutine is the entry point of our program.

  3. We use Console.WriteLine to print a message at the start of the program.

  4. We add an event handler for AppDomain.CurrentDomain.ProcessExit to demonstrate a cleanup or finalization concept similar to Go’s defer.

  5. The Environment.Exit(3) method is used to immediately terminate the program with a status code of 3. This is equivalent to Go’s os.Exit(3).

  6. The OnProcessExit subroutine is our event handler that will be called when the process exits.

To compile and run this program:

  1. Save the code in a file named ExitExample.vb.
  2. Open a command prompt and navigate to the directory containing the file.
  3. Compile the code using the VB.NET compiler:
vbc ExitExample.vb
  1. Run the compiled executable:
ExitExample.exe

You should see output similar to:

Starting the program...
Exiting the program...

To check the exit code in Windows PowerShell, you can use:

$LastExitCode

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.