My Cheatsheets

# VB.NET Lambdas and Closures Cheat Sheet

1️⃣ What is a Lambda in VB.NET?

A lambda expression is an anonymous function that can be assigned to a variable or passed as an argument.

Basic Lambda Syntax

' Single-line function
Dim add As Func(Of Integer, Integer, Integer) = Function(x, y) x + y
Console.WriteLine(add(3, 5)) ' Output: 8

Lambda with a Block Body (Multi-line Lambda)

Dim sayHello As Action(Of String) = Sub(name)
    Console.WriteLine("Hello, " & name & "!")
End Sub

sayHello("Alice") ' Output: Hello, Alice!

Key Notes:


2️⃣ What is a Closure in VB.NET?

A closure is a function that remembers variables from its outer scope even after the outer function has finished execution.

Basic Closure Example: Counter

Function MakeCounter() As Func(Of Integer)
    Dim count As Integer = 0
    Return Function()
               count += 1
               Return count
           End Function
End Function

Dim counter = MakeCounter()
Console.WriteLine(counter()) ' Output: 1
Console.WriteLine(counter()) ' Output: 2

Key Notes:


3️⃣ Closures with Parameters

Closures can take parameters to make them more dynamic.

Example: Counter with Step Value

Function MakeCounter(start As Integer) As Func(Of Integer, Integer)
    Dim count As Integer = start
    Return Function(step As Integer)
               count += step
               Return count
           End Function
End Function

Dim counter = MakeCounter(10)
Console.WriteLine(counter(2)) ' Output: 12
Console.WriteLine(counter(5)) ' Output: 17

Key Notes:


4️⃣ Closures with Objects

You can return objects with multiple functions.

Example: Counter with Reset Function

Function MakeCounter(start As Integer) As Object
    Dim count As Integer = start
    Return New With {
        .NextValue = Function()
                        count += 1
                        Return count
                    End Function,
        .Reset = Sub()
                    count = start
                 End Sub
    }
End Function

Dim counter = MakeCounter(10)
Console.WriteLine(counter.NextValue()) ' Output: 11
Console.WriteLine(counter.NextValue()) ' Output: 12
counter.Reset()
Console.WriteLine(counter.NextValue()) ' Output: 11

Key Notes:


5️⃣ When to Use Lambdas vs. Closures?

Feature Use Lambda Use Closure
Simple inline function ✅ Yes ❌ No
Captures state between calls ❌ No ✅ Yes
Used in Where(), Select(), etc. ✅ Yes ❌ No
Event handlers ✅ Yes ✅ Yes
Multiple independent instances ❌ No ✅ Yes

🚀 Final Takeaways

Lambdas are useful for short, inline functions but are not as elegant as in C# or JavaScript. ✅ Closures shine when you need stateful functions that remember values between calls. ✅ Use closures to create independent, self-contained function instances.

Would you like more examples or deeper explanations? 🚀