Step 1 of 5 · Reading · ~2 min
Learn
Subs, Functions, Arrays
VB.NET distinguishes:
- Sub — does work, returns nothing (like
void) - Function — returns a value
Sub — no return
Sub Greet(name As String)
Console.WriteLine("Hello, " & name)
End Sub
Call: Greet("Ada") or Call Greet("Ada") (older style). A Sub cannot carry an As Type clause — that is what makes it a Sub.
Function — returns a value
Function Square(n As Integer) As Integer
Return n * n
End Function
The trailing As Integer declares the return type; Return value exits with that value.
Legacy alternative — assign to the function's own name (still compiles):
Function Square(n As Integer) As Integer
Square = n * n ' sets the return value, does NOT exit
End Function
The difference matters: Return leaves immediately, the assignment form keeps running to End Function. Modern code uses Return.
Optional and named arguments
Function Greet(name As String, Optional greeting As String = "Hello") As String
Return greeting & ", " & name
End Function
Greet("Ada") ' "Hello, Ada"
Greet("Ada", "Hi") ' "Hi, Ada"
Greet("Ada", greeting:="Hi") ' named argument
ByVal vs ByRef
Sub Increment(ByRef n As Integer) ' pass by reference
n += 1
End Sub
Dim x As Integer = 5
Increment(x)
Console.WriteLine(x) ' 6 — the caller's variable was modified
ByVal (the default) passes a copy. ByRef passes the variable itself.
ParamArray — variadic
Function SumAll(ParamArray nums() As Integer) As Integer
Dim total As Integer = 0
For Each n As Integer In nums
total += n
Next
Return total
End Function
SumAll(1, 2, 3, 4, 5) ' 15
Recursion
Function Factorial(n As Integer) As Long
If n <= 1 Then Return 1
Return n * Factorial(n - 1)
End Function
No special syntax — a function may call itself. What it needs is a base case that returns without recursing (here n <= 1) and a recursive step that moves toward it (n - 1). Drop the base case and the program runs until the call stack is exhausted.
Passing a function around
AddressOf turns a method name into a delegate — a value you can store and call later:
Function Square(n As Integer) As Integer
Return n * n
End Function
Sub Main()
Dim f As Func(Of Integer, Integer) = AddressOf Square
Console.WriteLine(f(7)) ' 49
End Sub
Newer VB also writes this inline as a lambda, Function(n As Integer) n * n. Lambdas arrived in VB 10 (2010) and the compiler this course grades on predates them — it answers error VBNC30201: Expected expression — so use AddressOf and a named function here.
Your exercise
Write Factorial recursively: the base case returns 1, and every other n returns n * Factorial(n - 1). Return type is Long, not Integer, because 10! is already 3,628,800 and the tests go there. Note that 0! is 1 — n <= 1 covers both 0 and 1 in one test.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…