Dela via


Lambda Expressions

A lambda expression is a function without a name that calculates and returns a single value. Lambda expressions can be used wherever a delegate type is valid.

Note

The RemoveHandler statement is an exception. You cannot pass a lambda expression in for the delegate parameter of RemoveHandler.

The following example is a lambda expression that increments its argument and returns the value.

Function (num As Integer) num + 1

Because a lambda expression is an expression, it can only be used as part of a statement.

For example, you might assign the function to a variable name, especially if you want to use it more than one time.

Dim add1 = Function(num As Integer) num + 1

To call the function, send in a value for the parameter.

' The following line prints 6.
Console.WriteLine(add1(5))

Alternatively, you can declare and run the function at the same time.

Console.WriteLine((Function(num As Integer) num + 1)(5))

A lambda expression can be returned as the value of a function call (as is shown in the example in the Context section later in this topic), or passed in as an argument to a delegate parameter. In the following example, Boolean lambda expressions are passed in as an argument to method testResult. The method applies the Boolean test to an integer argument, value, and displays "Success" if the lambda expression returns True when applied to value, or "Failure" if the lambda expression returns False.

Module Module2

    Sub Main()
        ' The following line will print Success, because 4 is even.
        testResult(4, Function(num) num Mod 2 = 0)
        ' The following line will print Failure, because 5 is not > 10.
        testResult(5, Function(num) num > 10)
    End Sub 

    ' Sub testResult takes two arguments, an integer value and a  
    ' Boolean function.  
    ' If the function returns True for the integer argument, Success 
    ' is displayed. 
    ' If the function returns False for the integer argument, Failure 
    ' is displayed. 
    Sub testResult(ByVal value As Integer, ByVal fun As Func(Of Integer, Boolean))
        If fun(value) Then
            Console.WriteLine("Success")
        Else
            Console.WriteLine("Failure")
        End If 
    End Sub 

End Module

Lambda Expressions in Queries

In Language-Integrated Query (LINQ), lambda expressions underlie many of the standard query operators. The compiler creates lambda expressions to capture the calculations defined in fundamental query methods such as Where, Select, Order By, Take While, and others.

For example, consider the following query:

Dim londonCusts = From cust In db.Customers 
                  Where cust.City = "London" 
                  Select cust

This example is compiled to the following code:

Dim londonCusts = db.Customers _
    .Where(Function(cust) cust.City = "London") _
    .Select(Function(cust) cust)

For more information about query methods, see Queries (Visual Basic).

Lambda Expression Syntax

The syntax of a lambda expression resembles that of a standard function. The differences are as follows:

  • A lambda expression does not have a name.

  • Lambda expressions cannot have modifiers, such as Overloads or Overrides.

  • Lambda expressions do not use an As clause to designate the return type of the function. Instead, the type is inferred from the value that the body of the lambda expression evaluates to. For example, if the body of the lambda expression is Where cust.City = "London", its return type is Boolean.

  • The body of the function must be an expression, not a statement. The body can consist of a call to a function procedure, but not a call to a sub procedure.

  • There is no Return statement. The value returned by the function is the value of the expression in the body of the function.

  • There is no End Function statement.

  • Either all parameters must have specified data types or all must be inferred.

  • Optional and Paramarray parameters are not permitted.

  • Generic parameters are not permitted.

As a result of these restrictions, and of the ways in which lambda expressions are used, they usually are short and uncomplicated.

Context

A lambda expression shares its context with the method within which it is defined. It has the same access rights as any code written in the containing method. This includes access to member variables, functions and subs, Me, and parameters and local variables in the containing method.

Access to local variables and parameters in the containing method can extend beyond the lifetime of that method. As long as a delegate referring to a lambda expression is not available to garbage collection, access to the variables in the original environment is retained. In the following example, variable target is local to makeTheGame, the method in which the lambda expression playTheGame is defined. Note that the returned lambda expression, assigned to takeAGuess in Main, still has access to the local variable target.

Module Module1

    Sub Main()
        ' Variable takeAGuess is a Boolean function. It stores the target 
        ' number that is set in makeTheGame. 
        Dim takeAGuess As gameDelegate = makeTheGame()

        ' Set up the loop to play the game. 
        Dim guess As Integer 
        Dim gameOver = False 
        While Not gameOver
            guess = CInt(InputBox("Enter a number between 1 and 10 (0 to quit)", "Guessing Game", "0"))
            ' A guess of 0 means you want to give up. 
            If guess = 0 Then
                gameOver = True 
            Else 
                ' Tests your guess and announces whether you are correct. Method takeAGuess 
                ' is called multiple times with different guesses. The target value is not  
                ' accessible from Main and is not passed in.
                gameOver = takeAGuess(guess)
                Console.WriteLine("Guess of " & guess & " is " & gameOver)
            End If 
        End While 

    End Sub 

    Delegate Function gameDelegate(ByVal aGuess As Integer) As Boolean 

    Public Function makeTheGame() As gameDelegate

        ' Generate the target number, between 1 and 10. Notice that  
        ' target is a local variable. After you return from makeTheGame, 
        ' it is not directly accessible.
        Randomize()
        Dim target As Integer = CInt(Int(10 * Rnd() + 1))

        ' Print the answer if you want to be sure the game is not cheating 
        ' by changing the target at each guess.
        Console.WriteLine("(Peeking at the answer) The target is " & target)

        ' The game is returned as a lambda expression. The lambda expression 
        ' carries with it the environment in which it was created. This  
        ' environment includes the target number. Note that only the current 
        ' guess is a parameter to the returned lambda expression, not the target.  

        ' Does the guess equal the target? 
        Dim playTheGame = Function(guess As Integer) guess = target

        Return playTheGame

    End Function 

End Module

The following example demonstrates the wide range of access rights of the nested lambda expression. When the returned lambda expression is executed from Main as aDel, it accesses these elements:

  • A field of the class in which it is defined: aField

  • A property of the class in which it is defined: aProp

  • A parameter of method functionWithNestedLambda, in which it is defined: level1

  • A local variable of functionWithNestedLambda: localVar

  • A parameter of the lambda expression in which it is nested: level2

Module Module3

    Sub Main()
        ' Create an instance of the class, with 1 as the value of  
        ' the property. 
        Dim lambdaScopeDemoInstance = New LambdaScopeDemoClass _
            With {.Prop = 1}

        ' Variable aDel will be bound to the nested lambda expression   
        ' returned by the call to functionWithNestedLambda. 
        ' The value 2 is sent in for parameter level1. 
        Dim aDel As aDelegate = _
            lambdaScopeDemoInstance.functionWithNestedLambda(2)

        ' Now the returned lambda expression is called, with 4 as the  
        ' value of parameter level3.
        Console.WriteLine("First value returned by aDel:   " & aDel(4))

        ' Change a few values to verify that the lambda expression has  
        ' access to the variables, not just their original values.
        lambdaScopeDemoInstance.aField = 20
        lambdaScopeDemoInstance.Prop = 30
        Console.WriteLine("Second value returned by aDel: " & aDel(40))
    End Sub 

    Delegate Function aDelegate(ByVal delParameter As Integer) _
        As Integer 

    Public Class LambdaScopeDemoClass
        Public aField As Integer = 6
        Dim aProp As Integer 

        Property Prop() As Integer 
            Get 
                Return aProp
            End Get 
            Set(ByVal value As Integer)
                aProp = value
            End Set 
        End Property 

        Public Function functionWithNestedLambda _
           (ByVal level1 As Integer) As aDelegate
            Dim localVar As Integer = 5

            ' When the nested lambda expression is executed the first  
            ' time, as aDel from Main, the variables have these values: 
            ' level1 = 2 
            ' level2 = 3, after aLambda is called in the Return statement 
            ' level3 = 4, after aDel is called in Main 
            ' locarVar = 5 
            ' aField = 6 
            ' aProp = 1 
            ' The second time it is executed, two values have changed: 
            ' aField = 20 
            ' aProp = 30 
            ' level3 = 40 
            Dim aLambda = Function(level2 As Integer) _
                              Function(level3 As Integer) _
                                  level1 + level2 + level3 + localVar _
                                  + aField + aProp

            ' The function returns the nested lambda, with 3 as the  
            ' value of parameter level2. 
            Return aLambda(3)
        End Function 

    End Class 
End Module

Converting to a Delegate Type

A lambda expression can be implicitly converted to a compatible delegate type. For more information about the general requirements for compatibility, see Relaxed Delegate Conversion.

In addition, when you assign lambda expressions to delegates, you can specify the parameter names but omit their data types, letting the types be taken from the delegate. In the following example, a lambda expression is assigned to a variable named del of type ExampleDel, a delegate that takes two parameters, an integer and a string. Notice that the data types of the parameters in the lambda expression are not specified. However, del does require an integer argument and a string argument, as specified in the definition of ExampleDel.

' Definition of function delegate ExampleDel. 
Delegate Function ExampleDel(ByVal arg1 As Integer, _
                             ByVal arg2 As String) As Integer
' Declaration of del as an instance of ExampleDel, with no data  
' type specified for the parameters, m and s. 
Dim del As ExampleDel = Function(m, s) m

' Valid call to del, sending in an integer and a string.
Console.WriteLine(del(7, "up"))

' Neither of these calls is valid. Function del requires an integer 
' argument and a string argument. 
' Not valid. 
' Console.WriteLine(del(7, 3)) 
' Console.WriteLine(del("abc"))

Examples

  • The following example defines a lambda expression that returns True if the nullable argument has an assigned value, and False if its value is Nothing.

    Dim notNothing = Function(num? As Integer) _
                 num IsNot Nothing 
    Dim arg As Integer = 14
    Console.WriteLine("Does the argument have an assigned value?")
    Console.WriteLine(notNothing(arg))
    
  • The following example defines a lambda expression that returns the index of the last element in an array.

    Dim numbers() As Integer = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    Dim lastIndex = Function(intArray() As Integer) _
                        intArray.Length - 1
    For i = 0 To lastIndex(numbers)
        numbers(i) = numbers(i) + 1
    Next
    

See Also

Tasks

How to: Pass Procedures to Another Procedure in Visual Basic

How to: Create a Lambda Expression

Concepts

Procedures in Visual Basic

Introduction to LINQ in Visual Basic

Delegates and the AddressOf Operator

Nullable Value Types

Relaxed Delegate Conversion

Reference

Function Statement (Visual Basic)