Generics and tuples in Visual Basic
(Of T) type parameters, constraints and named tuple fields.
Console.WriteLine(Largest({3, 141, 59}))
Console.WriteLine(Largest({"fig", "plum", "apricot"}))
Dim pairs As New List(Of (name As String, score As Integer))
pairs.Add(("ada", 99))
pairs.Add(("alan", 87))
Console.WriteLine($"{pairs(0).name} tops {pairs(1).name}")
Function Largest(Of T As IComparable(Of T))(items As IEnumerable(Of T)) As T
Dim best = items.First()
For Each item In items
If item.CompareTo(best) > 0 Then best = item
Next
Return best
End Function
How it works
(Of T As IComparable(Of T))constrains T to things that compare.- One
Largestserves Integers and Strings alike — inference picks T. (name As String, score As Integer)tuples read by field name.
Keywords and builtins used here
DimEachEndForFunctionIfIntegerLargestNewNextOfReturnStringThen
The run, in numbers
- Lines
- 15
- Characters to type
- 464
- Tokens
- 141
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 113 seconds.
Step 3 of 3 in Value types, step 21 of 29 in Language basics.