Hashtable in Visual Basic .NET

Last Updated: March 19, 2020

Hashtable is a collection of key-value pair
Key should be unique. If you try to add same key twice you will get error message “Item has already been added. Key in dictionary:”

Look the following example

Module Module1

    Sub Main()
        Dim grad_student1 As Student
        grad_student1.FirstName = "John"
        grad_student1.LastName = "Doe"
        grad_student1.DateOfBirth = "01-03-1980"

        Dim grad_student2 As Student
        grad_student2.FirstName = "Mark"
        grad_student2.LastName = "Anthony"
        grad_student2.DateOfBirth = "21-06-1982"

        Dim ht As New Hashtable
        ht.Add("S001", grad_student1)
        ht.Add("S002", grad_student1)

       

    End Sub

    Public Structure Student
        Public FirstName As String
        Public LastName As String
        Public DateOfBirth As Date

        Public ReadOnly Property GetName() As String
            Get
                Return FirstName + " " + LastName
            End Get
        End Property
    End Structure

End Module

Code explanation:

Line 14: Hashtable object has been created
Line 15: You can add the grad_student1 object to Hashtable. Key is “S001”

Iterate the Hashtable

For Each element As DictionaryEntry In ht
   Dim stu As Student = CType(element.Value, Student)
   Console.WriteLine("Key is " + element.Key + "Student Name is " + stu.GetName)
Next

Code explanation:

Line 1: We are using Type as DictionaryEntry
Line 2: Casting the element.value to Student

Removing element in Hashtable
You can use remove() by passing the Key as parameter

ht.Remove("S001")