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 is generated method. This means that the compiler actually created a method for it and generated a name for it. You can see from the same figure that the name for this method is Void_Lambda$_2.

Figure 5.2 Subroutines example

5.2

Now you are going to update your sample application in order to test this out yourself. The first step is to add the following methods to the application:

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

    Dim SaySomething = Sub(text) TextBoxResult.Text += text
    SaySomething("World")

End Sub

Private Sub LambdaExpressionSubExample2()

    Dim SayHelloWorld = Sub()
                            TextBoxResult.Text = "Hello"
                            TextBoxResult.Text += "World"
                            TextBoxResult.Text += "Again"
                        End Sub

    SayHelloWorld()

End Sub

The first example demonstrates using lambda expressions that are on a single line and that they can have zero or more parameters. The second example demonstrates how they can also support multiple lines.

Running the program now won't do anything, because you have not added these methods to the examples collection. You accomplish that by adding the boldfaced lines in the following snippet to the constructor:

Public Sub New()
    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    Dim examplesList =
        {
            New With {.Name = "Lambda Expression - Subroutines 1", _
                      .Lambda = New Action(Sub() LambdaExpressionSubExample1())},
            New With {.Name = "Lambda Expression - Subroutines 2", _
                      .Lambda = New Action(Sub() LambdaExpressionSubExample2())}
        }

   _examples = New CollectionView(examplesList)
End Sub

When you run the application, the combo box will have the names you provided for your two examples. When the button is pressed, the selected method executes and the results are displayed in the text box.

This all works because of the Action specified for each example. Action(Of T) is a generic delegate. Chapter 7 covers the concept of generics, so you will not get into that here. The method has many definitions that allow for numerous generic-type parameters that correspond to parameters in the wrapped method. It has no return type, and the only parameter is the actual method to be wrapped. In the case of this example, you are wrapping a lambda expression which calls the appropriate method. Pressing the button retrieves this delegate and calls the Invoke method to execute it.

Creating a Lambda Expression Function

As mentioned in the previous section, subroutines do not return a value. If you need to return a value from your lambda expression, you must define it as a function.

Update the sample application by adding the following methods:

Private Sub LambdaExpressionFunctionExample()
    Dim AreaOfCircle = Function(radius As Integer) As Double
                           ' Compute the area of a circle 
                           Return Math.PI * Math.Pow(radius, 2)
                       End Function

    Dim Circumference = Function(radius As Integer)
                            ' Compute the circumference 
                            Return Math.PI * (radius * 2)
                        End Function

   TextBoxResult.Text = "The area of a circle with a radius of 5 is " +
                        AreaOfCircle(5).ToString() + Environment.NewLine
    TextBoxResult.Text += "The circumference of a circle with a radius of 5 is " +
                           Circumference(5).ToString()

End Sub

This example shows you how to create lambda expressions that are capable of returning a method. As you might imagine, instead of using Sub you use Function. Both of the functions defined take a parameter and return a value, but only the first one specifies the data type of the return value. For the second function, the compiler will infer the return type.

Before you can actually test this example, you need to add it to the examplesList collection by appending the following to the collection initializer:

New With {.Name = "Lambda Expression - Functions", _
          .Lambda = New Action(Sub() LambdaExpressionFunctionExample())}

Note
Since you are adding an item to a list of items, you will need to be sure to always separate the items with a comma. Where you place this comma depends on where you put the item. If you put the item at the top of your existing list, you will put a comma at the end. If you put the item at the bottom, you will add a comma to the end of the previous item. You will need to do this anytime you update this list.

Once that is complete, you can run the application, select the Lambda Expression - Functions item from the list, and execute it by pressing the button. Your results should look similar to those in Figure 5.3.

Figure 5.3 Functions example

5.3
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset