R. K. R. K. - 5 months ago 27
Vb.net Question

vb.net lambda too many arguments

I'm new to VB.net and am currently writing some codesamples for common constructs (that wont make any sense) that I will probably need in an upcoming project. I have a class with lambda expressions as properties, which looks like this:

Namespace SampleClasses
Public Class Lambdas
Public Shared ReadOnly Property AddFromZeroUpTo As Func(Of Integer, Integer)
Get
Return Function(upTo As Integer) Enumerable.Range(0, upTo + 1).Sum()
End Get
End Property

Public Shared ReadOnly Property ShowMessageBox As Action(Of String)
Get
Return Function(text As String) MessageBox.Show(text)
End Get
End Property
End Class
End Namespace


Now when I try to call those lambdas some lines work, some wont, and I dont really get why.

SampleClasses.Lambdas.ShowMessageBox()(SampleClasses.Lambdas.AddFromZeroUpTo(8)) 'works
SampleClasses.Lambdas.ShowMessageBox(SampleClasses.Lambdas.AddFromZeroUpTo(8)) 'wont work
SampleClasses.Lambdas.AddFromZeroUpTo(8) 'wont work
SampleClasses.Lambdas.AddFromZeroUpTo()(8) 'works
Dim msg = SampleClasses.Lambdas.ShowMessageBox
msg(SampleClasses.Lambdas.AddFromZeroUpTo(8)) 'works


I'm really stumped at this behaviour and have no clue why this behaves this way, thanks for any suggestions what to look for or explanations.

Answer Source

Both ShowMessageBox and AddFromZeroUpTo are properties. And they are defined to be ReadOnly and to return a delegate of some sort.
So you get the value of these properties and Invoke the delegates returned.
You can't pass anything to these properties like they were methods.

If you add the Invoke method implicit in your calls you get

' Get the delegate returned and invoke it
Lambdas.ShowMessageBox.Invoke(Lambdas.AddFromZeroUpTo(8)) 

' Doesn't make sense. ShowMessageBox is a read only property
'Lambdas.ShowMessageBox(Lambdas.AddFromZeroUpTo(8)) 'wont work

' Use the delegate returned from AddFromZeroUp
Lambdas.AddFromZeroUpTo.Invoke(8) 

' That's the same as above with the Invoke omitted
Lambdas.AddFromZeroUpTo()(8) 

' First calls the delegate returned by 
' AddFromZeroUpTo and with the return value calls the delegate returned
' by ShowMessageBox
Dim msg = Lambdas.ShowMessageBox
msg(Lambdas.AddFromZeroUpTo(8))

Notice that this code works only if you have Option Strict turned Off on your project. A very unwise move from many points of view.