James Monger James Monger - 2 months ago 11
Vb.net Question

Nested function does not have same signature as delegate

I'm trying to achieve a currying-like effect in VB. I want to be able to do this:

Dim wrap = WrapNumber("-")
wrap(5) 'returns "-5-"


Here's my function:

Private Function WrapNumber(ByVal separator As String) As Func(Of Integer, String)

Return Function(ByRef number As Integer) As String
Return separator + number + separator
End Function

End Function


I get an error on the
Return
line with this message:


Nested function does not have the same signature as delegate
Func(Of Integer, String)



I'm not sure why I'm getting this error. The function
WrapNumber
returns a function which takes an
Integer
and returns a
String
, so from what I can see it has the same type as the
Func
given in the
WrapNumber
signature.

Answer

If you turn Option Strict On, it will show you a lot of what's going wrong. In addition to ByRef not being required as stated in the comments, the concatenation is trying to treat separator as a double. If you make those changes then it works fine:

Dim wrap = WrapNumber("-")
Dim test As String = wrap(5)
'test is equal to "-5-"

Private Function WrapNumber(ByVal separator As String) As Func(Of Integer, String)
    Return Function(number As Integer) As String
               Return separator & number.ToString & separator
           End Function
End Function