Lambda Expressions

In the simplest terms, a lambda expression is an anonymous method that is sometimes referred to as an inline method or function. While the name and general principle comes from Lambda calculus, lambda expressions were first introduced in version 3.5 of the .NET Framework. Language Integrated Query (LINQ), discussed in Chapters 8, was also first introduced in version 3.5 of the framework and would not function without lambda expressions.

An anonymous method is an unnamed method that is created inline, or inside of a method, rather than as a method block itself. They are typically used as delegates, which are discussed in Chapter 3. They behave just like any other method and can have both parameters and return values.

All code discussed in this section is related to the MainWindow.xaml.vb file.

Creating a Lambda Expression Subroutine

As you already know, a subroutine is a method that has no return value. You create a lambda expression with no return value the same way you would a normal subroutine, but you either provide it as a delegate parameter or assign it to a variable.

Dim SayHello = Sub() TextBoxResult.Text = "Hello"
SayHello()

The lambda expression simply writes the word “Hello” to the text box on the main window. It is stored in the SayHello variable, and you can call it like you would any regular method.

If you debug the code and put the cursor over the SayHello variable, after that line has executed, you will see (as shown in Figure 5.2) that its type ...

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.