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.
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 ...