Visual Basic
Sub and Function Procedures
Define Sub (no return) and Function (returns value).
By EZ4Code Team
subfunctionprocedure
Code
' Sub: no return value
Sub Greet(ByVal name As String)
Console.WriteLine($"Hello, {name}!")
End Sub
' Function: returns a value
Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
' ByRef (pass by reference)
Sub Increment(ByRef x As Integer)
x += 1
End Sub
' Optional parameters
Function Power(ByVal base As Double, Optional ByVal exp As Double = 2) As Double
Return Math.Pow(base, exp)
End Function
' Usage
Greet("Alice")
Dim sum As Integer = Add(3, 4)
Dim n As Integer = 5
Increment(n) ' n is now 6
Dim sq As Double = Power(5) ' 25
Dim cb As Double = Power(5, 3) ' 125Explanation
Sub performs actions; Function returns a value. ByVal is default (copy); ByRef allows mutation. Optional parameters have defaults. VB supports string interpolation with $ (VS 2015+). Always use ByVal unless you need ByRef — mutable arguments are a common bug source.
More Visual Basic Snippets
Variables and Types
Declare variables with Dim and type inference.
Loops and Iteration
For, For Each, While, and Do loops in VB.
Windows Forms Basics
Create a simple WinForms application.
File I/O
Read/write text files and use My.Computer.FileSystem.
Error Handling (Try/Catch)
Structured exception handling in VB.
Collections (List, Dictionary)
Generic collections in VB.NET.