Generic Property in Visual Basic .NET

Last Updated: March 19, 2020

You can define generic property in a VB.NET class as shown in below code

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

    Public ReadOnly Property Item(index As Integer) As type
        Get
            Return items(index)
        End Get

    End Property

End Class

In Line 16, I have created a read only property as generic type

You can create instance of Integer type using following code

Module Module1

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

End Module