R. K. R. K. - 1 year ago 74
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)
Return Function(upTo As Integer) Enumerable.Range(0, upTo + 1).Sum()
End Get
End Property

Public Shared ReadOnly Property ShowMessageBox As Action(Of String)
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

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

' Use the delegate returned from AddFromZeroUp

' That's the same as above with the Invoke omitted

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download