Generic classes in VB.NET
To work with a collection of objects you use generic collection.
Whenever you need to work with a collection of objects you use generic collection. .NET framework providing some generic collection such as the ones define by the List(), SortedList(), Stack(), Queue() classes.
So many times you need to use generics to define your own generic collection to add some functionality which is not provided in .NET Framework generic collections. So, this article show you how to do that.
In this example first creates a CustomList() class that can store Product types, add four product object to the list, and display these objects in a dialog box.
Example Code
Imports System.Windows.Forms
Module Module1
Public Class CustomList(Of T)
Private List As New List(Of T)
Public Sub Add(ByVal item As T)
List.Add(item)
End Sub
Default Public Property Item(ByVal indax As Integer) As T
Get
Return List(indax)
End Get
Set(ByVal value As T)
List(indax) = value
End Set
End Property
Public ReadOnly Property Count() As Integer
Get
Return List.Count
End Get
End Property
Public Overrides Function ToString() As String
Dim listString As String = ""
For i As Integer = 0 To List.Count - 1
listString &= List(i).ToString & vbCrLf
Next
Return listString
End Function
End Class
Sub Main()
Dim list As New CustomList(Of Integer)
Dim a1 As Integer = 23
Dim a2 As Integer = 71
Dim a3 As Integer = 10
Dim a4 As Integer = 50
list.Add(a1)
list.Add(a2)
list.Add(a3)
list.Add(a4)
MessageBox.Show(list.ToString, "List of Integers")
End Sub
End Module
OUTPUT