'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor

You have referred to a ReadOnly variable from within a lambda expression, which is not permitted. The following code causes this error by sending the ReadOnly variable m as the argument to a ByRef parameter.

Class Class1

    ReadOnly m As Integer

    Sub New()
        ' The use of m triggers the error.
        Dim f = Function() Test(m)
    End Sub

    Function Test(ByRef n As Integer) As String
    End Function

End Class

Error ID: BC36602

To correct this error

  • If possible, change parameter n in function Test to a ByVal parameter, as shown in the following code.

    Class Class1Fix1
    
        ReadOnly m As Integer
    
        Sub New()
            Dim f = Function() Test(m)
        End Sub
    
        Function Test(ByVal n As Integer) As String
        End Function
    
    End Class
    

To correct this error

  • Assign the ReadOnly variable m to a local variable in the constructor, and use the local variable in place of m, as shown in the following code.

    Class Class1Fix2
         ReadOnly m As Integer
    
        Sub New()
            Dim temp = m
            Dim f = Function() Test(temp)
        End Sub
    
        Function Test(ByRef n As Integer) As String
        End Function
    
    End Class
    

See Also

Concepts

Lambda Expressions

Reference

ReadOnly (Visual Basic)

Using Constructors and Destructors