Fun with Generics in VB

I had so much fun with my little generics experiment that I thought I would try the same code in VB. 


A couple of interesting notes:


  1. Generics are fully supported by VB… I found zero language\compiler issues with this little example!

  2. Notice I didn’t find a way to do type aliasing in VB, but I might just be missing it, so you see the (slightly ugly) nested generics more often in the VB code
    List(Of KeyValuePair(Of String, Integer)) rather than List(Of NameCount)

  3. VB doesn’t yet support the functional members so I used the more traditional interface based callback.  It is good that we offer both on this class.  Using the delegate based one with out the language support would have been really ugly.  Do you like the functional way or the interface way better? 

  4. The Comparer base class was fun to use -- it really made it easy.  I did find out that we are making a change to make Equals not abstract.  It will be a virtual member with the exact same implementation I show below.  I think this is goodness as it allows folks to customize it for performance sensitive scenarios but doesn’t force everyone to do it.




   Sub Main()

        Dim tally As New Dictionary(Of String, Integer)

        Dim entries As List(Of Uri)

        entries = GetEntryUris(DateTime.Parse("2/01/2004"), DateTime.Now)

        For Each entry As Uri In entries

            For Each name As String In GetComments(entry)

                If (tally.ContainsKey(name)) Then

                    tally(name) = tally(name) + 1


                    tally.Add(name, 1)

                End If



        Dim l As New List(Of KeyValuePair(Of String, Integer))(tally)

        l.Sort(New KeyValuePairComparer())

        For Each k As KeyValuePair(Of String, Integer) In l

            Console.WriteLine("{0}={1}", k.Key, k.Value)



    End Sub

End Module


Class KeyValuePairComparer

    Inherits Comparer(Of KeyValuePair(Of String, Integer))


    Public Overrides Function Compare(ByVal x As KeyValuePair(Of String, Integer), ByVal y As KeyValuePair(Of String, Integer)) As Integer

        Return x.Value.CompareTo(y.Value)

    End Function


    Public Overloads Overrides Function Equals(ByVal x As KeyValuePair(Of String, Integer), ByVal y As KeyValuePair(Of String, Integer)) As Boolean

        Return Compare(x, y) = 0

    End Function

End Class

Comments (2)

  1. John Cavnar-Johnson says:

    The VB equivalent syntax would be:

    Imports NameCount = System.Collections.Generic.KeyValuePair(Of String, Integer)

  2. Brad Abrams says:

    So it does — you are right.. thanks

Skip to main content