Skip to content
Lesson 6 of 7

Step 1 of 5 · Reading · ~2 min

Learn

Modules, Generics, Async

VB.NET supports full .NET generics — same engine as C# generics.

Generic class

Class Box(Of T)
    Private _value As T

    Public Sub New(v As T)
        _value = v
    End Sub

    Public ReadOnly Property Value As T
        Get
            Return _value
        End Get
    End Property
End Class

' Usage:
Dim intBox = New Box(Of Integer)(42)
Dim strBox = New Box(Of String)("hello")
intBox.Value         ' 42
strBox.Value         ' "hello"

The (Of T) is the type parameter list. Multiple: (Of K, V).

Generic function

Function Max(Of T As IComparable)(a As T, b As T) As T
    If a.CompareTo(b) > 0 Then
        Return a
    Else
        Return b
    End If
End Function

Dim m1 = Max(3, 7)              ' inferred — 7
Dim m2 = Max("abc", "xyz")     ' "xyz"

As IComparable is a constraint — T must implement IComparable.

Constraint types

  • As ClassName — must inherit from this class
  • As IName — must implement this interface
  • As Class — must be a reference type
  • As Structure — must be a value type
  • As New — must have a parameterless constructor
Function Create(Of T As New)() As T
    Return New T()
End Function

Generic collections

The whole System.Collections.Generic namespace:

  • List(Of T) — dynamic array
  • Dictionary(Of K, V) — hash map
  • HashSet(Of T) — hash set
  • Queue(Of T), Stack(Of T)
  • LinkedList(Of T)
  • SortedDictionary(Of K, V), SortedSet(Of T)
Dim users As New List(Of String)
users.Add("Ada")
users.Add("Bob")

Dim ages As New Dictionary(Of String, Integer)
ages.Add("Ada", 36)
ages("Bob") = 25

Dim unique As New HashSet(Of Integer)({1, 2, 3, 2, 1})
unique.Count          ' 3

Generic interfaces

Interface IComparable(Of T)
    Function CompareTo(other As T) As Integer
End Interface

Class Person
    Implements IComparable(Of Person)
    Public Age As Integer
    Public Function CompareTo(other As Person) As Integer Implements IComparable(Of Person).CompareTo
        Return Me.Age.CompareTo(other.Age)
    End Function
End Class

Allows type-safe Comparable, Equatable, etc.

Default(Of T)

Retrieve the default value for type T:

Function Empty(Of T)() As T
    Return Nothing       ' or CType(Nothing, T)
End Function

Default(Of Integer)        ' 0
Default(Of String)         ' Nothing

Why generics over Object

  • Type safety: compile-time errors instead of runtime InvalidCastException
  • Performance: no boxing/unboxing for value types
  • IntelliSense: IDE knows the actual type

Backing fields, not auto-properties

The examples above spell out Private _value As T and a Get block. That is not style: this course's grader compiles with vbnc, which has no auto-implemented properties. Write the field and the block.

Up nextAsync/AwaitModules, Generics, Async

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…