Generics In Visual Basic .NET

Last Updated: March 20, 2022

To Explain the Generics in VB.NET I am going to create a class called List which you can add integers to the list

Public Class List
    Private items() As Integer
    Private index As Integer

    Public Sub New(ByVal size As Integer)
        ReDim items(size - 1)
        index = 0
    End Sub

    Public Sub Add(ByVal number As Integer)
        items(index) = number
        index += 1

    End Sub

End Class

Inside the Sub Main() I will add two integers

Module Module1

    Sub Main()
        Dim myList As New List(2)
        myList.Add(1)
        myList.Add(2)
    End Sub

End Module

How do you change the class to add String values
You create a new class then copy the code and change Integer to String
Like the code below

Public Class StringList
    Private items() As String
    Private index As Integer

    Public Sub New(ByVal size As Integer)
        ReDim items(size - 1)
        index = 0
    End Sub

    Public Sub Add(ByVal str As String)
        items(index) = str
        index += 1

    End Sub

End Class

Although you have used code reusability this is not a good approach. SO VB.NET has Generics for this
I am using a new keyword Of with type

Public Class List(Of type)
    Private items() As type
    Private index As Integer

    Public Sub New(ByVal size As Integer)
        ReDim items(size - 1)
        index = 0
    End Sub

    Public Sub Add(ByVal item As type)
        items(index) = item
        index += 1

    End Sub

End Class

When you create the instance from this class you have to use Of Integer as shown below

   Sub Main()
        Dim myList As New List(Of Integer)(2)
        myList.Add(1)
        myList.Add(2)
    End Sub

Now you can use this generic class for any data type that you find in the VB.NET

Test