Capture Variables with Closures: VB.NET: Scope Code Fragments: Listing 1
Closures allow locally scoped variables to be scoped to include code fragments, which are delegates in .NET. These delegates can then be passed around the system as needed and the closure data can communicate information such as whether the operation should be cancelled. This is a much better approach than treating local values as class state because it’s thread safe, reduces the possibility for side effects, and avoids cluttering the class with local data.
Private Sub Test()
Dim customers = _
Customer.GetNewCustomerList()
Dim cancel As Boolean = False
Dim sortDelegate = Function(cust1 _
As Customer, _
cust2 As Customer) CompareCustomers( _
cust1, cust2, cancel)
customers.Sort(sortDelegate)
If cancel Then
Console.WriteLine("Operation Failed")
End If
End Sub
Private Function CompareCustomers(ByVal cust1 _
As Customer, ByVal cust2 As Customer, ByRef _
cancel As Boolean) As Int32
If String.IsNullOrEmpty(cust1.LastName) Or _
String.IsNullOrEmpty(cust2.LastName) Then
cancel = True
Return 0
End If
Dim compare = String.Compare( _
cust1.LastName, cust2.LastName, _
StringComparison. _
InvariantCultureIgnoreCase)
If compare = 0 Then
Return String.Compare(cust1.FirstName, _
cust2.FirstName, _
StringComparison. _
InvariantCultureIgnoreCase)
End If
Return compare
End Function