Func (Of Tin, Tout) using lambda expression with ByRef argument gives an incompatible signature error

Why is this:

Private [Function] As Func(Of Double, String) = Function(ByRef z As Double) z.ToString 

gives the following error:

The nested function does not have a signature compatible with the String delegate).

So far it is:

 Private [Function] As Func(Of Double, String) = Function(ByVal z As Double) z.ToString 

Is not it? (Difference - ByRef / ByVal)

Also, how can I implement such a thing?

+8
lambda func
source share
2 answers

You get this error because the delegate type of the (ByVal z As Double) As String function is not compatible with the (ByRef z As Double) As String function . You need an exact match.

Also, you cannot declare a common Func (Of ...) delegate with ByRef (ref or out in C #) parameters, regardless of whether you use an anonymous function or not.

But you can declare a delegation type and then use it even with an anonymous function

 Delegate Function ToStringDelegate(ByRef value As Double) As String Sub Main() Dim Del As ToStringDelegate = Function(ByRef value As Double) value.ToString() End Sub 

or you can use implicit typing (if the Infer parameter is enabled)

 Dim Del = Function(ByRef value As Double) value.ToString() 
+11
source share

On MSDN , it mentions the following rules for applicability to variable domains in lambda expressions:

  • The intercepted variable will not be garbage collected until the delegate that refers to it goes out of scope.
  • The variables entered in the lambda expression are not visible in the external method.
  • A lambda expression cannot directly capture ref [ByRef in VB] or the out parameter of a placement method.
  • The return statement in a lambda expression does not return a return method.
  • A lambda expression cannot contain a goto statement, a break or continue statement whose target is outside the body or in the body of the contained anonymous function.
+6
source share

All Articles