Skip to main content

.NET VB.NET Basics

Introduction

Visual Basic .NET (VB.NET) is a high-level, object-oriented programming language implemented on the .NET Framework. As part of the .NET family, it offers a user-friendly approach to building Windows applications, web services, and more. Originally designed as a successor to the classic Visual Basic language, VB.NET has evolved into a powerful tool that combines the simplicity of Visual Basic's syntax with the robust features of the .NET platform.

In this guide, we'll explore the fundamental elements of VB.NET programming, from basic syntax to creating simple applications. If you're new to programming or transitioning from another language, VB.NET's readable syntax makes it an excellent starting point for your coding journey.

Setting Up Your Environment

Before diving into VB.NET programming, you'll need to set up your development environment:

  1. Visual Studio: Microsoft's Visual Studio is the recommended IDE (Integrated Development Environment) for VB.NET development. You can download Visual Studio Community Edition for free from Microsoft's website.

  2. .NET Framework/.NET Core: Visual Studio includes the necessary .NET components, but ensure you select the ".NET desktop development" workload during installation.

VB.NET Syntax Fundamentals

Your First VB.NET Program

Let's start with the traditional "Hello World" program to understand the basic structure of a VB.NET application:

vb
Module Program
Sub Main()
Console.WriteLine("Hello, World!")
Console.ReadLine() ' Keeps the console window open
End Sub
End Module

Output:

Hello, World!

Let's break down what's happening here:

  • Module Program declares a new module named "Program"
  • Sub Main() is the entry point of the application
  • Console.WriteLine() writes a line of text to the console
  • End Sub marks the end of the Main subroutine
  • End Module marks the end of the module

Comments

Comments in VB.NET allow you to add explanatory notes to your code:

vb
' This is a single-line comment

' Multi-line comments use the apostrophe on each line
' like this
' and this

REM This is another way to write comments (legacy style)

Variables and Data Types

VB.NET is a strongly-typed language, offering various data types to store different kinds of data:

vb
Module Variables
Sub Main()
' Declaring variables with explicit data types
Dim age As Integer = 25
Dim name As String = "John Doe"
Dim isActive As Boolean = True
Dim salary As Double = 55000.75

' Variable with type inference (compiler determines the type)
Dim temperature = 98.6 ' Inferred as Double

' Output
Console.WriteLine("Name: " & name)
Console.WriteLine("Age: " & age)
Console.WriteLine("Active: " & isActive)
Console.WriteLine("Salary: $" & salary)
Console.WriteLine("Temperature: " & temperature & "°F")

Console.ReadLine()
End Sub
End Module

Output:

Name: John Doe
Age: 25
Active: True
Salary: $55000.75
Temperature: 98.6°F

Common Data Types

Data TypeDescriptionExample
IntegerWhole numbersDim count As Integer = 10
LongLarge whole numbersDim population As Long = 7800000000
SingleSingle-precision floating-pointDim weight As Single = 65.5F
DoubleDouble-precision floating-pointDim pi As Double = 3.14159265359
DecimalHigh-precision decimal valuesDim amount As Decimal = 1234.5678D
StringTextDim message As String = "Hello"
BooleanTrue/False valuesDim isCompleted As Boolean = False
DateDate and timeDim today As Date = Date.Now
CharSingle characterDim grade As Char = "A"c
ObjectGeneric object referenceDim something As Object = 42

Basic Input and Output

VB.NET provides several ways to interact with users through input and output:

vb
Module IOExample
Sub Main()
' Output
Console.WriteLine("What is your name?")

' Input
Dim userName As String = Console.ReadLine()

' Processing and output
Console.WriteLine("Hello, " & userName & "! Welcome to VB.NET programming.")

' Formatting output
Dim currentDate As Date = Date.Now
Console.WriteLine("Today is {0:d} and the time is {0:t}", currentDate)

' Using string interpolation (.NET 6 and later)
Console.WriteLine($"The date is {currentDate:yyyy-MM-dd}")

Console.ReadLine()
End Sub
End Module

Sample Output:

What is your name?
Alice
Hello, Alice! Welcome to VB.NET programming.
Today is 10/12/2023 and the time is 14:30
The date is 2023-10-12

Control Structures

Conditional Statements

If-Then-Else

vb
Module ConditionalExample
Sub Main()
Console.Write("Enter your age: ")
Dim age As Integer = Integer.Parse(Console.ReadLine())

If age < 18 Then
Console.WriteLine("You are a minor.")
ElseIf age >= 18 And age < 65 Then
Console.WriteLine("You are an adult.")
Else
Console.WriteLine("You are a senior citizen.")
End If

Console.ReadLine()
End Sub
End Module

Select Case (Switch)

vb
Module SelectCaseExample
Sub Main()
Console.Write("Enter a day number (1-7): ")
Dim dayNum As Integer = Integer.Parse(Console.ReadLine())

Select Case dayNum
Case 1
Console.WriteLine("Sunday")
Case 2
Console.WriteLine("Monday")
Case 3
Console.WriteLine("Tuesday")
Case 4
Console.WriteLine("Wednesday")
Case 5
Console.WriteLine("Thursday")
Case 6
Console.WriteLine("Friday")
Case 7
Console.WriteLine("Saturday")
Case Else
Console.WriteLine("Invalid day number")
End Select

Console.ReadLine()
End Sub
End Module

Loops

For Loop

vb
Module ForLoopExample
Sub Main()
' Basic For loop
Console.WriteLine("Counting from 1 to 5:")
For i As Integer = 1 To 5
Console.WriteLine(i)
Next

' For loop with Step
Console.WriteLine("Even numbers from 2 to 10:")
For j As Integer = 2 To 10 Step 2
Console.WriteLine(j)
Next

Console.ReadLine()
End Sub
End Module

Output:

Counting from 1 to 5:
1
2
3
4
5
Even numbers from 2 to 10:
2
4
6
8
10

While Loop

vb
Module WhileLoopExample
Sub Main()
Dim count As Integer = 1

While count <= 5
Console.WriteLine("Count is: " & count)
count += 1
End While

Console.ReadLine()
End Sub
End Module

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

Do Loop

vb
Module DoLoopExample
Sub Main()
' Do While - checks condition before execution
Dim i As Integer = 1
Do While i <= 3
Console.WriteLine("Do While: " & i)
i += 1
Loop

' Do Until - loops until condition becomes true
Dim j As Integer = 1
Do Until j > 3
Console.WriteLine("Do Until: " & j)
j += 1
Loop

' Do Loop While - checks condition after execution
Dim k As Integer = 1
Do
Console.WriteLine("Do Loop While: " & k)
k += 1
Loop While k <= 3

Console.ReadLine()
End Sub
End Module

Output:

Do While: 1
Do While: 2
Do While: 3
Do Until: 1
Do Until: 2
Do Until: 3
Do Loop While: 1
Do Loop While: 2
Do Loop While: 3

Working with Arrays and Collections

Arrays

Arrays store multiple values of the same data type:

vb
Module ArrayExample
Sub Main()
' Declare and initialize an array
Dim fruits() As String = {"Apple", "Banana", "Cherry", "Date", "Elderberry"}

' Access array elements
Console.WriteLine("The first fruit is: " & fruits(0))
Console.WriteLine("The third fruit is: " & fruits(2))

' Get array length
Console.WriteLine("Number of fruits: " & fruits.Length)

' Iterate through array
Console.WriteLine("All fruits:")
For Each fruit As String In fruits
Console.WriteLine("- " & fruit)
Next

' Multi-dimensional array
Dim matrix(,) As Integer = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

Console.WriteLine("Element at position (1,2): " & matrix(1, 2)) ' Outputs 6

Console.ReadLine()
End Sub
End Module

Collections

VB.NET provides several collection types for more flexible data management:

vb
Imports System.Collections.Generic

Module CollectionsExample
Sub Main()
' List (dynamic array)
Dim numbers As New List(Of Integer)
numbers.Add(10)
numbers.Add(20)
numbers.Add(30)

Console.WriteLine("List count: " & numbers.Count)
Console.WriteLine("Second number: " & numbers(1))

' Dictionary (key-value pairs)
Dim capitals As New Dictionary(Of String, String)
capitals.Add("USA", "Washington D.C.")
capitals.Add("UK", "London")
capitals.Add("France", "Paris")

Console.WriteLine("Capital of France: " & capitals("France"))

' Checking if key exists
If capitals.ContainsKey("Japan") Then
Console.WriteLine("Capital of Japan: " & capitals("Japan"))
Else
Console.WriteLine("Japan is not in the dictionary.")
End If

Console.ReadLine()
End Sub
End Module

Functions and Subroutines

VB.NET offers two types of procedures: functions (which return values) and subroutines (which don't):

vb
Module ProceduresExample
' Subroutine (does not return a value)
Sub PrintWelcome(name As String)
Console.WriteLine("Welcome, " & name & "!")
End Sub

' Function (returns a value)
Function CalculateArea(length As Double, width As Double) As Double
Return length * width
End Function

' Function with optional parameters
Function FormatName(firstName As String, lastName As String, Optional includeMiddle As Boolean = False, Optional middleName As String = "") As String
If includeMiddle AndAlso middleName <> "" Then
Return firstName & " " & middleName & " " & lastName
Else
Return firstName & " " & lastName
End If
End Function

Sub Main()
' Calling a subroutine
PrintWelcome("Developer")

' Calling a function
Dim area As Double = CalculateArea(5.5, 3.2)
Console.WriteLine("The area is: " & area & " square units")

' Optional parameters
Dim fullName1 As String = FormatName("John", "Doe")
Dim fullName2 As String = FormatName("Jane", "Smith", True, "Elizabeth")

Console.WriteLine(fullName1)
Console.WriteLine(fullName2)

Console.ReadLine()
End Sub
End Module

Output:

Welcome, Developer!
The area is: 17.6 square units
John Doe
Jane Elizabeth Smith

Error Handling

VB.NET provides a robust error-handling system using Try-Catch blocks:

vb
Module ErrorHandlingExample
Sub Main()
' Basic Try-Catch
Try
Console.Write("Enter a number to divide 100 by: ")
Dim divisor As Double = Double.Parse(Console.ReadLine())
Dim result As Double = 100 / divisor
Console.WriteLine("Result: " & result)
Catch ex As DivideByZeroException
Console.WriteLine("Error: Cannot divide by zero.")
Catch ex As FormatException
Console.WriteLine("Error: Please enter a valid number.")
Catch ex As Exception
Console.WriteLine("An unexpected error occurred: " & ex.Message)
Finally
Console.WriteLine("This code always executes, whether there was an error or not.")
End Try

Console.ReadLine()
End Sub
End Module

Practical Example: Simple Calculator Application

Let's combine what we've learned into a simple calculator application:

vb
Module CalculatorApp
Function Add(a As Double, b As Double) As Double
Return a + b
End Function

Function Subtract(a As Double, b As Double) As Double
Return a - b
End Function

Function Multiply(a As Double, b As Double) As Double
Return a * b
End Function

Function Divide(a As Double, b As Double) As Double
If b = 0 Then
Throw New DivideByZeroException("Cannot divide by zero")
End If
Return a / b
End Function

Sub Main()
Console.WriteLine("==== Simple Calculator ====")

Try
' Get first number
Console.Write("Enter first number: ")
Dim num1 As Double = Double.Parse(Console.ReadLine())

' Get second number
Console.Write("Enter second number: ")
Dim num2 As Double = Double.Parse(Console.ReadLine())

' Get operation
Console.WriteLine("Select operation:")
Console.WriteLine("1. Add")
Console.WriteLine("2. Subtract")
Console.WriteLine("3. Multiply")
Console.WriteLine("4. Divide")
Console.Write("Enter choice (1-4): ")
Dim operation As Integer = Integer.Parse(Console.ReadLine())

Dim result As Double

' Perform calculation based on operation
Select Case operation
Case 1
result = Add(num1, num2)
Console.WriteLine($"{num1} + {num2} = {result}")
Case 2
result = Subtract(num1, num2)
Console.WriteLine($"{num1} - {num2} = {result}")
Case 3
result = Multiply(num1, num2)
Console.WriteLine($"{num1} × {num2} = {result}")
Case 4
result = Divide(num1, num2)
Console.WriteLine($"{num1} ÷ {num2} = {result}")
Case Else
Console.WriteLine("Invalid operation selected")
End Select

Catch ex As FormatException
Console.WriteLine("Error: Please enter valid numbers.")
Catch ex As DivideByZeroException
Console.WriteLine("Error: " & ex.Message)
Catch ex As Exception
Console.WriteLine("An unexpected error occurred: " & ex.Message)
End Try

Console.WriteLine("Press Enter to exit.")
Console.ReadLine()
End Sub
End Module

This calculator demonstrates many of the concepts we've covered: functions, input/output, error handling, control structures, and type conversion.

Object-Oriented Programming Basics

VB.NET is a fully object-oriented language. Here's a simple example of a class:

vb
' Class definition
Public Class Person
' Properties
Public Property FirstName As String
Public Property LastName As String
Public Property Age As Integer

' Constructor
Public Sub New(firstName As String, lastName As String, age As Integer)
Me.FirstName = firstName
Me.LastName = lastName
Me.Age = age
End Sub

' Method
Public Function GetFullName() As String
Return FirstName & " " & LastName
End Function

' Function to check if person is adult
Public Function IsAdult() As Boolean
Return Age >= 18
End Function
End Class

Module OOPExample
Sub Main()
' Create an instance of the Person class
Dim person1 As New Person("Jane", "Doe", 25)

' Access properties and methods
Console.WriteLine("Person: " & person1.GetFullName())
Console.WriteLine("Age: " & person1.Age)

If person1.IsAdult() Then
Console.WriteLine(person1.FirstName & " is an adult")
Else
Console.WriteLine(person1.FirstName & " is a minor")
End If

Console.ReadLine()
End Sub
End Module

Output:

Person: Jane Doe
Age: 25
Jane is an adult

Summary

In this guide, we've covered the basic elements of VB.NET programming:

  • Syntax fundamentals including modules, subroutines, and comments
  • Variables and data types for storing different kinds of information
  • Control structures like If-Then-Else, Select Case, and various loops
  • Arrays and collections for managing groups of related data
  • Functions and subroutines for organizing and reusing code
  • Error handling with Try-Catch blocks
  • Object-oriented programming basics with classes and objects

VB.NET combines a readable syntax with the power and flexibility of the .NET platform, making it an excellent choice for building Windows applications, web services, and more.

Additional Resources

To further develop your VB.NET skills:

  1. Microsoft Documentation: Visit Microsoft's official VB.NET documentation for in-depth guides and reference materials.

  2. Books:

    • "Visual Basic .NET Step by Step" by Microsoft Press
    • "Programming in Visual Basic 2010" by Julia Case Bradley and Anita Millspaugh
  3. Online Courses:

    • Microsoft Learn Platform
    • Pluralsight courses on VB.NET
    • Udemy's VB.NET courses for beginners

Practice Exercises

  1. Hello User: Create a program that asks for a user's name and their favorite color, then displays a personalized greeting using that information.

  2. Number Analyzer: Write a program that asks the user for a number, then determines if it's positive, negative, or zero, and if it's even or odd.

  3. Shopping List Manager: Develop an application that lets users add items to a shopping list, view all items, and remove items.

  4. Temperature Converter: Create a program that converts temperatures between Celsius and Fahrenheit based on user input.

  5. Student Grade Calculator: Build an application that calculates the average grade from a collection of student scores and assigns a letter grade based on the average.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)