Code lives in procedures: a Sub does something and returns nothing, a Function returns a value, a Property is a pair of accessors, an Operator overloads a symbol, and an Event is a notification other code can subscribe to. They are members of classes, structures and modules.
Subs, functions and parameters
Public Sub Greet(name As String, Optional greeting As String = "Hello")
Console.WriteLine(greeting & ", " & name)
End Sub
Public Function Sum(ParamArray numbers() As Integer) As Integer
Dim total = 0
For Each n In numbers
total += n
Next
Return total
End Function
Public Sub Swap(ByRef a As Integer, ByRef b As Integer)
Dim t = a
a = b
b = t
End Sub
Public Function Max(a As Integer, b As Integer) As Integer
Max = If(a > b, a, b) ' assigning to the function's name sets the result
End Function
Public Function Max(a As Double, b As Double) As Double ' an overload
Return If(a > b, a, b)
End Function
Greet("Ada")
Greet(greeting:="Hi", name:="Bob") ' named arguments, in any order
Dim s = Sum(1, 2, 3)
- Parameters are
ByValby default (a copy;ByValmay be left out, and a modifier-free parameter is by value) orByRef(the caller’s variable).Optionalparameters need a default and come last;ParamArraytakes any number of trailing arguments as an array. - Overloading: procedures of one name with different parameter lists; the compiler picks the best match. The
Overloads,OverridesandShadowsmodifiers are described under classes. - Returning:
Return value, or assign to the function’s own name and reachEnd FunctionorExit Function. - Declare imports a function of a native library:
Declare Auto Function MessageBox Lib "user32.dll" Alias "MessageBoxW" (hWnd As IntPtr, text As String, caption As String, type As UInteger) As Integer.Ansi,UnicodeorAutochoose the character set;Aliasnames the entry point. (<DllImport>does the same with an attribute.) - Extension methods (version 9): a
<Extension()>method (fromSystem.Runtime.CompilerServices) in a module whose first parameter is the type being extended can be called as if it were a member of that type.
Async and iterator methods
Public Async Function FetchLengthAsync(delayMs As Integer) As Task(Of Integer)
Await Task.Delay(delayMs)
Return delayMs * 2
End Function
Public Iterator Function Squares(count As Integer) As IEnumerable(Of Integer)
For i = 1 To count
Yield i * i
Next
End Function
Async function and an Iterator function (both version 11).An Async method returns a Task, a Task(Of T) (the Return then gives the T), or, for a Sub that fires and forgets, nothing; Await suspends it until the awaited task completes without blocking the thread. An Iterator function returns IEnumerable, IEnumerator or their generic forms, and each Yield produces the next element lazily. Lambdas can be Async or Iterator too. Main cannot be Async.
Properties
Private _value As Integer
Public Property Value As Integer
Get
Return _value
End Get
Set(newValue As Integer)
_value = newValue
RaiseEvent Changed(Me, newValue)
End Set
End Property
Public ReadOnly Property Double1 As Integer
Get
Return _value * 2
End Get
End Property
Public Property Label As String = "counter" ' automatic property with an initialiser
Public Property Tag As Object
Default Public ReadOnly Property Item(i As Integer) As Integer
Get
Return _value + i
End Get
End Property
A property has a Get and/or a Set accessor (ReadOnly and WriteOnly properties have one); an accessor may be less accessible than the property (Private Set). A property with no accessors written is an automatic property (version 10) with a hidden backing field, and may have an initialiser (= "counter") and be ReadOnly (version 14). A Default property has parameters and is used as obj(i).
Events
Public Event Changed(sender As Object, newValue As Integer)
Public Event Reset As EventHandler
Public Sub Clear()
RaiseEvent Reset(Me, EventArgs.Empty)
End Sub
Public Custom Event Custom As EventHandler
AddHandler(value As EventHandler)
End AddHandler
RemoveHandler(value As EventHandler)
End RemoveHandler
RaiseEvent(sender As Object, e As EventArgs)
End RaiseEvent
End Event
' a subscriber
Private WithEvents source As New Counter
Private Sub OnChanged(sender As Object, newValue As Integer) Handles source.Changed
Console.WriteLine(newValue)
End Sub
Public Sub Hook()
AddHandler source.Reset, AddressOf OnReset
RemoveHandler source.Reset, AddressOf OnReset
End Sub
- An
Eventis declared with a parameter list or with a delegate type (As EventHandler);RaiseEventcalls its subscribers. - A
Custom Eventwrites its ownAddHandler,RemoveHandlerandRaiseEventblocks. Handles: a procedure withHandles variable.Eventsubscribes for as long as theWithEventsvariable holds an object (Windows Forms designers use this for controls).AddHandlerandRemoveHandlersubscribe and unsubscribe at run time, with a method (AddressOf) or a lambda.
Operators
Public Shared Operator +(a As Counter, b As Counter) As Counter
Dim c As New Counter
c.Value = a.Value + b.Value
Return c
End Operator
Public Shared Widening Operator CType(c As Counter) As Integer
Return c.Value
End Operator
An operator is a Public Shared Operator member. Unary: + - Not IsTrue IsFalse; binary: + - * / \ Mod ^ & << >> = <> < > <= >= Like And Or Xor (comparison operators come in pairs). CType operators are Widening (implicit) or Narrowing (explicit) conversions. AndAlso and OrElse are formed from And, Or, IsTrue and IsFalse.
Not described
Known, not yet covered
- Reference: overload resolution (the rules for choosing among overloads, optional and
ParamArrayarguments,OverloadResolutionPriorityof version 17.13), partial methods, interface implementation clauses (Implementson a method) andHandles MyBase/Handles Meare not described in full. - Reference: the marshalling attributes of
DeclareandDllImport, COM events and the application-framework events are not described.
See also
- Classes, modules and interfaces – where procedures live
- Generics, lambdas and delegates – generic procedures and anonymous procedures