Overview
Visual Basic (VB) is a modern, object‑oriented programming language that makes it easy to write clear, concise, and maintainable code for .NET applications. This guide covers the core fundamentals you need to start building robust VB solutions.
Hello World
Every new language tutorial starts with a simple program that prints “Hello, World!” to the console.
Module HelloWorld
Sub Main()
Console.WriteLine("Hello, World!")
End Sub
End Module
Compile and run with dotnet run
inside a console project.
Variables & Data Types
VB provides strong typing with a range of built‑in types. Use Dim
to declare a variable.
Dim name As String = "Alice"
Dim age As Integer = 30
Dim salary As Double = 5432.75
Dim isActive As Boolean = True
Optionally enable Option Strict On
for compile‑time type checking.
Control Structures
VB supports the familiar If…Then…Else
, Select Case
, For
, While
, and Do…Loop
constructs.
If age >= 18 Then
Console.WriteLine("Adult")
Else
Console.WriteLine("Minor")
End If
For i As Integer = 1 To 5
Console.WriteLine(i)
Next
Select Case day
Case "Saturday", "Sunday"
Console.WriteLine("Weekend")
Case Else
Console.WriteLine("Weekday")
End Select
Functions & Subroutines
Encapsulate logic in Function
(returns a value) or Sub
(no return).
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
Sub PrintGreeting(name As String)
Console.WriteLine($"Hello, {name}!")
End Sub
' Usage
Dim sum = Add(3, 4)
PrintGreeting("Bob")
Error Handling
Use Try…Catch…Finally
to handle runtime exceptions.
Try
Dim result = 10 / Convert.ToInt32(userInput)
Console.WriteLine($"Result: {result}")
Catch ex As DivideByZeroException
Console.WriteLine("Cannot divide by zero.")
Catch ex As FormatException
Console.WriteLine("Invalid number format.")
Finally
Console.WriteLine("Operation completed.")
End Try
Classes & Objects
Define classes to model real‑world entities.
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Sub New(name As String, age As Integer)
Me.Name = name
Me.Age = age
End Sub
Public Sub Greet()
Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.")
End Sub
End Class
' Instantiate and use
Dim alice As New Person("Alice", 28)
alice.Greet()