Lessons in this course (12)

4. Sub vs Function, ByVal/ByRef, Optional and ParamArray

Basic★ Must knowLesson 4 of 12
vb
' Sub = method returning nothing (C# void)
Public Sub Log(message As String)
    Console.WriteLine($"{Date.Now:HH:mm} {message}")
End Sub

' Function = method returning a value
Public Function Add(a As Integer, b As Integer) As Integer
    Return a + b
End Function

' ByVal (default) copies the value/reference; ByRef passes the variable itself (C# ref)
Public Sub Swap(ByRef a As Integer, ByRef b As Integer)
    Dim t = a : a = b : b = t
End Sub

' Optional parameters and named arguments
Public Sub SendMail(toAddr As String, Optional subject As String = "Hi", Optional urgent As Boolean = False)
End Sub
SendMail("a@b.com", urgent:=True)

' ParamArray = C# params
Public Function Sum(ParamArray values As Integer()) As Integer
    Return values.Sum()
End Function

' Lambdas
Dim square = Function(x As Integer) x * x
Dim show = Sub(msg As String) Console.WriteLine(msg)
Dim isAdult As Func(Of Integer, Boolean) = Function(age) age >= 18

Overloading uses the same name with different parameters (Overloads keyword is optional except when overloading inherited members).