1. Generics - (New in VB2005)






    Example
    System.Collections.Generics. This allows us to use Dictionary, List, Queue, SortedDictionary and Stack classes.

    Dim employees As New Dictionary(Of String, Employee)
    Dim emp As Employee emp = New Employee
    emp.SSN = “111-11-1111"
    emp.FirstName = “Scott"
    emp.LastName = “Swigart"
    emp.Salary = 50000

    employees.Add(emp.SSN, emp)
    txtOutput.Text = “Consuming generics” & vbCrLf & vbCrLf

    Dim emp2 As Employee
    emp2 = employees.Item(“111-11-1111”)

    Dim s As String
    s = employees.Item(“111-11-1111”) ‘ This is now a syntax error

    employees.Item(“111-11-1111”).LastName = “SomeoneElse"

    txtOutput.Text &= “Employee last name:” & vbCrLf & _
    employees.Item(“111-11-1111”).LastName

    So the generic types are instantiated as

    Dim employees As New Dictionary (Of String, Employee)

    Here the use of word OF specifies the desired data type of the keys. Any attempt to save any value other than Employee will result in the compile time error. With generics using incorrect data type will result in compiler error.

    One of the reasons of using Generics in the .NET framework is performance. Simply put, they are faster than the previous collection classes because the compiler optimizes them specifically for the types they store.
    0

    Add a comment

Blog Archive
Topics
Topics
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.