Delegates and Lambdas in VB 10 by ThinqLinq

Delegates and Lambdas in VB 10

Yesterday, I had the pleasure of demonstrating Delegates, Lambdas and Expressions at the Alabama Code Camp. This is not the first time I presented this. The original demo project is still available in the Downloads section of this site. This time however, I was able to round off the VB set of the demos to demonstrate all of the abilities available in C# 3.0 due to the new Statement and Multi-line Lambda language enhancements coming in VB 10. The complete VB 10 version of the project is available to download now as well.

Here are some of the added methods. (Note, this has been tested against the October 2008 beta release of Visual Studio 2010. Be aware of the evaluation time bomb in this release if you intend to use it.) The DoTrick method takes an Action delegate which means that it takes no parameters and returns no values. In VB this equates to a Sub and in VB 10 is refered to as a Statement Lambda.

'Anonymous delegate
animal.DoTrick(Sub() Console.WriteLine("Anonymous Method"))

' Lambda expression as a variable
Dim LiftOneLeg As TrickAction =
   Sub()
      animal.LegsOnGround -= 1
   End Sub
animal.DoTrick(LiftOneLeg)

'Lambda expression inline
animal.DoTrick(Sub()
      animal.LegsOnGround += 3
   End Sub)

'Multi-line lambda
animal.DoTrick(Sub()
      animal.LegsOnGround = 0
      Console.WriteLine("I'm Jumping now!")
      animal.LegsOnGround = 4
   End Sub)

I also included a nice consise combination of VB 9 function lambdas with VB 10 Statement lambdas. In this case, I find the animals that have broken business rules (Predicates which are delegates that return a boolean) and then iterate over them using the ForEach method that takes an Action delegate which can be fulfilled with a statement lambda.

animals _
   .Where(Function(item) Not item.IsValid).ToList _
   .ForEach(Sub(item) Console.WriteLine(item.ToString))

For this update, I also include a demonstration of a common use of Lambda's, particularly in Silverlight applications where all data access is asynchronous. Since all delegates actually inherit from MultiCastDelegate, all delegates by default offer asynchronous BeginInvoke/EndInvoke possibilities in addition to the Synchronous Invoke method.

With BeginInvoke, we use a lambda that takes an IAsynchResult object as a parameter. In the past we had to declare the call back as a separate method. With the inclusion of multi-line statement lambdas, we can now declare the callback directly inline with the BeginInvoke request as follows:

Public Sub BeginTrick(ByVal trick As Action)
   trick.BeginInvoke(Sub(result)
         Thread.Sleep(1000)
         Console.WriteLine("...Trick Completed for " & ToString())
      End Sub, Me)
End Sub

If you missed this presentation, I'll be doing it again at the South Florida Code Camp next week. Come on down and check it out.

Posted on - Comment
Categories: Code Camp - VB - VB Dev Center -
comments powered by Disqus