O'Reilly logo

Professional Visual Basic 2012 and .NET 4.5 Programming by Todd Herman, Gastón Hillar, David McCarter, Rob Windsor, Billy Hollis, Bill Sheldon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Lambda Expressions

The previous section showed you how to create lambda expressions in their simplest forms. What are they for, though? It was mentioned earlier that they are delegates and can be used anywhere delegates are used, but what exactly does that mean? The purpose of this section is to answer those questions by showing you how they can be used in practical situations.

Handling Events with Lambdas

One of the most common places that you will find lambda expressions being used is as event handlers. Chapter 3 covers events and event handlers in detail, but a simple definition is that they are delegates that are called when a particular event is fired.

The typical approach for handling events is to create a method that represents the handler and providing the address of it in the AddHandler statement.

AddHandler timer.tick, AddressOf TimerTickHandler
Private Sub TimerTickHandler(ByVal sender As Object, ByVal e As EventArgs)
    ' Handle the event
End Sub

Lambda expressions allow you to do this without having to create the named handler method. To see this in action, add the following code to your sample application:

Private Sub LambdaExpressionAsEventHandler() Dim timer As DispatcherTimer = New DispatcherTimer(Windows.Threading.DispatcherPriority.Normal) timer.Interval = TimeSpan.FromSeconds(5) AddHandler timer.Tick, Sub(source, args) timer.Stop() TextBoxResult.Text = "The timer has elapsed at " + DateTime.Now.ToLongTimeString() End Sub timer.Start() TextBoxResult.Text ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required