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
comments powered by Disqus

Featured

  • Mastering AI Development and Building AI Apps with GitHub Copilot

    Two Microsoft experts explain how GitHub Copilot is evolving from a coding assistant into a broader platform for building, customizing and testing AI-powered developer workflows.

  • VS Code 1.123 Adds Agent Session Sync, 1M Context Windows

    Microsoft released Visual Studio Code 1.123 on June 3, adding agent-focused features, larger model context support, integrated browser updates and a new delay for some automatic extension updates.

  • Copilot Billing Shock Hits Developers

    Developer complaints about GitHub Copilot's new usage-based billing model have centered on unexpectedly rapid AI credit consumption, and neither GitHub nor Microsoft has responded directly to the backlash, though they have previously published guidance to lessen model usage costs.

  • Hands On with GitHub Copilot App Technical Preview: Turning a Blazor Issue into a PR

    GitHub's brand-new Copilot desktop app, in technical preview, handled a small Blazor issue from planning through pull request creation, but the hands-on test also showed why developers still need to verify agent work in the running app before merging.

Subscribe on YouTube