VB.NET Code Examples

Explore a variety of practical code examples demonstrating key features and common scenarios in Visual Basic .NET. These examples are designed to help you understand concepts and implement solutions efficiently.

Basic Console Application

A simple "Hello, World!" console application to get started.

Module HelloWorld
                            Sub Main()
                                Console.WriteLine("Hello, World!")
                                Console.ReadKey() ' Keep console open
                            End Sub
                        End Module

Working with Collections (List(Of T))

Demonstrates how to create, add, remove, and iterate through a List of strings.

Imports System.Collections.Generic

                        Module ListExample
                            Sub Main()
                                Dim names As New List(Of String)()
                                names.Add("Alice")
                                names.Add("Bob")
                                names.Add("Charlie")

                                Console.WriteLine("Names in the list:")
                                For Each name In names
                                    Console.WriteLine(name)
                                Next

                                names.Remove("Bob")
                                Console.WriteLine("Removed Bob. New count: " & names.Count)
                            End Sub
                        End Module

File I/O (Reading a Text File)

Shows how to read content from a simple text file.

Imports System.IO

                        Module FileReadExample
                            Sub Main()
                                Dim filePath As String = "mydata.txt"

                                Try
                                    If File.Exists(filePath) Then
                                        Dim lines As String() = File.ReadAllLines(filePath)
                                        Console.WriteLine("Content of " & filePath & ":")
                                        For Each line In lines
                                            Console.WriteLine(line)
                                        Next
                                    Else
                                        Console.WriteLine("File not found: " & filePath)
                                    End If
                                Catch ex As Exception
                                    Console.WriteLine("An error occurred: " & ex.Message)
                                End Try

                                Console.WriteLine("Press any key to continue...")
                                Console.ReadKey()
                            End Sub
                        End Module

Working with Dates and Times

Basic operations for getting and formatting current date and time.

Module DateTimeExample
                            Sub Main()
                                Dim now As DateTime = DateTime.Now

                                Console.WriteLine("Current Date: " & now.ToShortDateString())
                                Console.WriteLine("Current Time: " & now.ToShortTimeString())
                                Console.WriteLine("Full Date & Time: " & now.ToString("yyyy-MM-dd HH:mm:ss"))
                                Console.WriteLine("Day of the Week: " & now.DayOfWeek.ToString())

                                Dim futureDate As DateTime = now.AddDays(7)
                                Console.WriteLine("Date in 7 days: " & futureDate.ToShortDateString())
                            End Sub
                        End Module

Creating a Simple Class

Defines a basic `Person` class with properties and a method.

Public Class Person
                            Public Property Name As String
                            Public Property Age As Integer

                            Public Sub Greet()
                                Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.")
                            End Sub
                        End Class

                        Module ClassExample
                            Sub Main()
                                Dim person1 As New Person()
                                person1.Name = "Jane Doe"
                                person1.Age = 30
                                person1.Greet()

                                Dim person2 As New Person With { .Name = "John Smith", .Age = 25 }
                                person2.Greet()
                            End Sub
                        End Module

Error Handling (Try...Catch)

Demonstrates robust error handling for potential exceptions.

Module ErrorHandlingExample
                            Sub DivideNumbers(divisor As Integer)
                                Try
                                    Dim result As Integer = 10 / divisor
                                    Console.WriteLine($"10 divided by {divisor} is {result}")
                                Catch ex As DivideByZeroException
                                    Console.WriteLine("Error: Cannot divide by zero!")
                                Catch ex As Exception
                                    Console.WriteLine("An unexpected error occurred: " & ex.Message)
                                Finally
                                    Console.WriteLine("Division operation finished.")
                                End Try
                            End Sub

                            Sub Main()
                                DivideNumbers(2)
                                DivideNumbers(0)
                                DivideNumbers(-5) ' Example of a potential non-standard error if input validation was involved
                            End Sub
                        End Module