Generics in Depth
As Class, As Structure, As New, As BaseType, As IInterface, As {Class, IEntity, New} Nothing (Dim x As T = Nothing)
Function Max(Of T As IComparable(Of T))(a As T, b As T) As T Static members per closed type
Shared fields differ for Cache(Of Integer) vs Cache(Of String)
Out/In on interface and delegate type parameters GetType(List(Of)) open generic, MakeGenericType, MakeGenericMethod
No generic math (static abstract interface members) in VB, no unmanaged constraint authoring
Public Class Result(Of T)
Public ReadOnly Property IsSuccess As Boolean
Public ReadOnly Property Value As T
Public ReadOnly Property [Error] As String
Private Sub New(success As Boolean, value As T, err As String)
IsSuccess = success : Me.Value = value : [Error] = err
End Sub
Public Shared Function Ok(value As T) As Result(Of T)
Return New Result(Of T)(True, value, Nothing)
End Function
Public Shared Function Fail(err As String) As Result(Of T)
Return New Result(Of T)(False, Nothing, err)
End Function
Public Function Map(Of TOut)(f As Func(Of T, TOut)) As Result(Of TOut)
Return If(IsSuccess, Result(Of TOut).Ok(f(Value)), Result(Of TOut).Fail([Error]))
End Function
End Class
Public Function ParseAge(s As String) As Result(Of Integer)
Dim n As Integer
If Not Integer.TryParse(s, n) Then Return Result(Of Integer).Fail("Not a number")
If n < 0 Then Return Result(Of Integer).Fail("Negative")
Return Result(Of Integer).Ok(n)
End Function