Anonymous type property '<propertyname>' cannot be used in the definition of a lambda expression within the same initialization list

Properties defined in the initialization list of an anonymous type cannot be part of a lambda expression definition in the same list. For example, in the following code, property Num cannot be included in the definition of LambdaFun.

' Not valid.
'Dim anon = New With {.Num = 4, .LambdaFun = Function() .Num > 0}

Error ID: BC36549

To correct this error

  1. Consider splitting the anonymous type into two parts:

    Dim anon1 = New With {.Num = 4}
    Dim anon2 = New With {.LambdaFun = Function() anon1.Num > 0}
    ' - or -
    Dim anon3 = New With {.lambdaFun = Function(n As Integer) n > 0}
    Console.WriteLine((anon2.LambdaFun)())
    Console.WriteLine(anon3.lambdaFun(anon1.Num))
    anon1.Num = -5
    Console.WriteLine((anon2.LambdaFun)())
    Console.WriteLine(anon3.lambdaFun(anon1.Num))
    

    Note that if you declare anon1.Num as a Key property, its value cannot be changed.

  2. An alternative is to use a regular function statement to access the anonymous type property:

    Function testNum(ByVal n As Integer) As Boolean
        Return n > 0
    End Function
    Console.WriteLine(testNum(anon1.Num))
    
  3. Similarly, you can use a lambda function that is defined outside the anonymous type:

    Dim lambdaFun1 = Function() anon1.Num > 0
    Dim lambdaFun2 = Function(n As Integer) n > 0
    

See Also

Concepts

Lambda Expressions

Anonymous Types