Here is the full source code listing for our sample string component in VB:
Listing 6. Component in VB (CompVB.vb)
Imports System Option Explicit Namespace CompVB Public Class StringComponent Private StringSet(4) As String Public Sub New() MyBase.New StringSet(0) = "VB String 0" StringSet(1) = "VB String 1" StringSet(2) = "VB String 2" StringSet(3) = "VB String 3" End Sub Public Function GetString(ByVal index as Integer) As String If ((index < 0) or (index >= Count)) then throw new IndexOutOfRangeException End If GetString = StringSet(index) End Function ReadOnly Property Count() As Long Get Count = StringSet.Length End Get End Property End Class End Namespace
Like with C++ and C#, both the namespace and the class name are specified in code (previous versions of VB used filenames to indicate class names).
In VB, class constructors are given the name New
rather than the name of the class, as is done for the other languages. Since constructors don't return a value, using VB it is implemented as a Sub
rather than a Function
:
Public Sub New() … End Sub
Also note the statement:
MyBase.New
This statement, which is required, calls the constructor on the base class. In C++ and C#, the call to the base class constructor is generated automatically by the compiler.
Here's the GetString
method (in VB, subroutines which return values are called functions), which takes an integer and returns a string:
Public Function GetString(ByVal index as Integer) As String If ((index < 0) or (index >= Count)) then throw new IndexOutOfRangeException End If GetString = StringSet(index) End Function
Note the throw
statement in the GetString
method, which highlights the new runtime-based exception handling:
throw new IndexOutOfRangeException
This statement creates – and throws – a new object of type IndexOutOfRangeException
. Previous versions of the VB runtime implemented an Err
object.
Finally, we create the read-only property Count
:
ReadOnly Property Count() As Long Get Count = StringSet.Length End Get End Property
The command-line build is quite simple, the only change being to output the component to the relative "..\Bin" subdirectory for convenience:
vbc CompVB.vb /out:..\Bin\CompVB.dll /t:library