Generics in VB 2005
So, generics in .NET 2.0 let you make functions and classes generic over types.
They also let you maintain type safety by constraining the type, e.g. making it implements a certain interface.
For example, you could define a general function to find the minimum element in a list. In VB, the data structure of interest is System.Collections.Generic.List(Of T). Now, we have to be able to compare on these objects, and the .NET interface for this is IComparable. So, we can define the function as follows:
Imports System.Collections.Generic
Public Function FindMin(Of T As IComparable(Of T))(ByVal data As List(Of T)) As T
Dim minval As T = data(0)
For Each value As T In data
If value.CompareTo(minval) < 0 Then
minval = value
End If
Next
Return minval
End Function
The As IComparable(Of T) bit constraints T to implement IComparable. Visual Studio complains with highlighted source code until we add this constraint about the call to CompareTo; it statically determines the type safety of what we’ve produced with respect to constraints and interfaces and tells us promptly, which is nice.
Then you can test this out as follows:
Dim numdata As New List(Of Integer)
numdata.Add(1) : numdata.Add(3) : numdata.Add(-5) : numdata.Add(4)
Console.WriteLine(FindMin(numdata))
Dim stringdata As New List(Of String)
stringdata.Add("first") : stringdata.Add("second") : stringdata.Add("last")
Console.WriteLine(FindMin(stringdata))
This outputs -5 and “first”, respectively, as you’d expect.
Pretty straightforward, really.
Whoda thought a BASIC dialect could be a respectable albeit underwhelming programming language?