Lambdas, Closures and Functional Techniques
Functional practices in VB: immutable objects, pure functions, LINQ pipelines, Func/Action parameters (strategy pattern without classes), Result/Option-style types (LanguageExt and CSharpFunctionalExtensions libraries work from VB).
Pitfall: closures capture variables, not values. Copy loop variables when you build deferred lambdas in older patterns.
Dim square = Function(x As Integer) x * x
Dim greet = Sub(n As String) Console.WriteLine($"Hi {n}")
Dim classify = Function(n As Integer) As String
Select Case n
Case Is < 0 : Return "negative"
Case 0 : Return "zero"
Case Else : Return "positive"
End Select
End Function
' Closure
Function Counter() As Func(Of Integer)
Dim c = 0
Return Function()
c += 1
Return c
End Function
End Function
' Higher-order composition
Function Compose(Of A, B, C)(f As Func(Of A, B), g As Func(Of B, C)) As Func(Of A, C)
Return Function(x) g(f(x))
End Function
Dim trimThenUpper = Compose(Of String, String, String)(Function(s) s.Trim(), Function(s) s.ToUpper())
' Partial application / currying
Function Adder(x As Integer) As Func(Of Integer, Integer)
Return Function(y) x + y
End Function
' Memoization
Function Memoize(Of TIn, TOut)(f As Func(Of TIn, TOut)) As Func(Of TIn, TOut)
Dim cache As New Concurrent.ConcurrentDictionary(Of TIn, TOut)
Return Function(x) cache.GetOrAdd(x, f)
End Function