Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Why does this:

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

gives the following error:

Nested function does not have a signature that is compatible with delegate String)'.

While this:

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

Does not? (The difference is ByRef/ByVal)

Furthermore, how might I implement such a thing?

like image 376
Brian Mulcahy Avatar asked Mar 09 '11 00:03

Brian Mulcahy


1 Answers

You are getting this error because the delegate type Function (ByVal z As Double) As String is not compatible with Function (ByRef z As Double) As String. You need exact match.

Also you can't declare the Func(Of ...) generic delegate with ByRef parameters (ref or out in C#), no matter are you using anonymous function or not.

But you can declare you delegate type and then use it even with your 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 Option Infer is turned on)

Dim Del = Function(ByRef value As Double) value.ToString()
like image 57
Tom Kris Avatar answered Sep 21 '22 13:09

Tom Kris