Making VB.NET as Strict & Robust as C# – Best Practices





🔥 Making VB.NET as Strict & Robust as C# – Best Practices 🚀

Do you want VB.NET to behave more like C# in terms of strictness, type safety, and reliability? 🤔 By default, VB.NET allows some loose coding practices that can lead to hidden bugs. But don’t worry—I’ll show you how to enforce strict rules and improve code quality with just a few changes! 💡

โปรเจกต์นี้พัฒนาด้วย Visual Studio 2022
🖥️✨ อาจารย์แนะนำให้ติดตั้งพร้อมกับ .NET 8
🚀 หรือเวอร์ชันใหม่ล่าสุด
🔄 ตามวิดีโอสอนฟรีด้านล่างนี้เลยครับ 🎬👇

This project was developed using Visual Studio 2022.
I recommend installing it along with .NET 8
or the latest version.
Check out the free tutorial video below! 🎥👇


Here’s an example of Visual Basic .NET source code in the Main module of the project:

' File-level VB.NET compiler options:
Option Strict On     ' Enforces strict type checking, prevents implicit type conversions
Option Explicit On   ' Requires all variables to be declared before use
Option Infer On      ' Enables type inference (like C# var), lets compiler determine types
Option Compare Binary ' Uses binary (case-sensitive) string comparisons instead of text

' Main module for the Enterprise Grade Inventory Management System
Module Program
    ' Entry point of the application
    Sub Main(args As String())
        Try
            ' Display application title and header
            Console.WriteLine("Enterprise Grade Inventory Management System")
            Console.WriteLine("----------------------------------------")
            Console.WriteLine()

            ' Synchronously execute the asynchronous application initialization
            InitializeApplicationAsync().Wait()

            ' Handle user-initiated cancellation of the initialization process
        Catch ex As OperationCanceledException
            Console.WriteLine(ex.Message)
            Console.WriteLine(Environment.NewLine & "Program terminated by user.")
            Environment.Exit(1)

            ' Environment.Exit(1) is a method in .NET that immediately terminates
            ' the current running application with a specific exit code.
            ' In this context: 1 indicates an abnormal termination or error condition
            ' It forcefully stops the application
        Catch ex As Exception
            Console.WriteLine(Environment.NewLine & "Critical Error")
            Console.WriteLine("--------------")
            Console.WriteLine("An unexpected error has occurred:")
            Console.WriteLine(ex.Message)
            Console.WriteLine(Environment.NewLine & "The application needs to close.")
            Console.WriteLine("Please contact system administrator if this persists.")
            Environment.Exit(1)
        End Try

        ' Prompt user to press any key before application closes
        Console.WriteLine(Environment.NewLine & "Press any key to exit...")
        Console.ReadKey()
    End Sub

    ' Asynchronous method to initialize the entire application
    Private Async Function InitializeApplicationAsync() As Task
        ' Attempt system initialization with retry mechanism
        Await InitializeWithRetryAsync()

        ' Start the main program loop (menu system)
        Await MainProgramLoopAsync()
    End Function

    ' Implements a retry mechanism for system initialization
    Private Async Function InitializeWithRetryAsync() As Task
        ' Maximum number of initialization attempts
        Const MaxRetries As Integer = 3
        Dim retryCount As Integer = 0

        Do
            Try
                ' Attempt to initialize the system
                Await SystemInitialization.InitializeSystemAsync()

                ' Verify the system's integrity
                If Await SystemInitialization.VerifySystemIntegrityAsync() Then
                    ' System initialization successful
                    Console.WriteLine("System verification passed. Ready to start.")
                    Console.WriteLine(Environment.NewLine & "Press any key to continue...")
                    Console.ReadKey(True)  ' Pause for user acknowledgment
                    Exit Do  ' Exit retry loop if successful
                Else
                    ' Throw exception if system verification fails
                    Throw New Exception("System verification failed.")
                End If

            Catch ex As Exception
                ' Increment retry counter
                retryCount += 1

                ' Check if maximum retry attempts have been reached
                If retryCount >= MaxRetries Then
                    Console.WriteLine(Environment.NewLine & "Initialization Failed")
                    Console.WriteLine("---------------------")
                    Console.WriteLine($"Failed to initialize after {MaxRetries} attempts.")
                    Console.WriteLine("Error: " & ex.Message)
                    Throw  ' Throw final error if all attempts fail
                End If

                ' Inform user about retry attempt
                Console.WriteLine(Environment.NewLine & $"Initialization attempt {retryCount} of {MaxRetries} failed.")
                Console.WriteLine("Press any key to retry or Esc to cancel...")

                ' Get user input for retry or cancel
                Dim key = Console.ReadKey(True)
                If key.Key = ConsoleKey.Escape Then
                    ' Allow user to cancel initialization
                    Throw New OperationCanceledException("Initialization cancelled by user.")
                End If
            End Try
        Loop
    End Function

    ' Main program loop to display and handle the menu system
    Private Async Function MainProgramLoopAsync() As Task
        ' Call the main menu display method from MenuSystem module
        ' Await MenuSystem.DisplayMainMenuAsync()
        Await Task.CompletedTask
    End Function

End Module

🛠️ Step 1: Configure Your Project Settings 

To make your VB.NET project as strict and robust as C#, modify your .vbproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>

    <OutputType>Exe</OutputType>

    <RootNamespace>EnterpriseInventory</RootNamespace>

    <TargetFramework>net8.0</TargetFramework>


    <OptionStrict>On</OptionStrict>

    <OptionExplicit>On</OptionExplicit>

    <OptionCompare>Binary</OptionCompare>

    <OptionInfer>On</OptionInfer>

  

    <!-- Enable null reference checking -->

    <Nullable>enable</Nullable>

    <!-- Helps prevent null reference exceptions, like in C# -->

  </PropertyGroup>

</Project>

This ensures: ✅ Option Strict On – Prevents implicit data type conversions
Option Explicit On – Forces explicit variable declarations
Option Compare Binary – Uses binary comparison for better performance
Option Infer On – Allows type inference
Nullable enable – Helps prevent null reference exceptions like in C#

🛠️ Step 2: Configure in Visual Studio

If you prefer Visual Studio settings, follow these steps:

1️⃣ Right-click on your project → Select Properties
2️⃣ Go to the Compile tab
3️⃣ Set these options:

  • Option Strict = On
  • Option Explicit = On
  • Option Compare = Binary
  • Option Infer = On

🛠️ Step 3: Set at the File Level

For individual files, add these directives at the top:

Option Strict On

Option Explicit On

Option Infer On

Option Compare Binary


This is useful when you only want strict settings for specific files instead of the whole project.

🚀 Bonus: Why Enable Null Reference Checking?

In VB.NET, Nothing can sometimes lead to unexpected null reference errors. Enabling <Nullable>enable</Nullable> in the project settings helps:
✔️ Catch potential null references at compile time
✔️ Reduce runtime exceptions
✔️ Make VB.NET behave more like C# in handling nullability


💬 What do you think?

Have you used these settings before? Let me know in the comments! Or if you have any VB.NET coding challenges, feel free to ask! 👇

📌 Follow for more VB.NET & C# best practices!

💬 พูดคุยกับผมที่...
► LINE OA : https://lin.ee/ApE56xD
► Facebook : https://www.facebook.com/CodeAMinute

📺 ติดตามช่อง YouTube
https://www.youtube.com/@iBasskung
https://www.youtube.com/@iBasskungAcademy
► TikTok : https://www.tiktok.com/@codeaminute

📖 ดูหลักสูตรทั้งหมด: https://bit.ly/3lXWoj2

Udemy profile : https://www.udemy.com/user/tanin-sangngam


#VBNet #CSharp #DotNet #CleanCode #SoftwareEngineering #ProgrammingTips #CodingBestPractices #StrictMode #VisualBasic #DevTips #เขียนโปรแกรม #DotNetไทย #พัฒนาSoftware #โปรแกรมมิ่ง #Codeคุณภาพ #เทคนิคการเขียนโค้ด #DotNetDevelopment #Programming #CodeQuality #TechTips #BestPractices #CodeAMinute #iBasskung #อาจารย์เบส #ไอเบสคุง

Comments