Generics In Visual Basic .NET

August 29, 2017

To Explain the Generics in VB.NET I am going to create a class called List which you can add integer 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 the code reusability this is not good approach. SO VB.NET has Generics for this
I am using 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 form 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 used this generic class for any data type which you find in the VB.NET