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 ...
Get Professional Visual Basic 2012 and .NET 4.5 Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.