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:
Public Class Lambdas
Public Shared ReadOnly Property AddFromZeroUpTo As Func(Of Integer, Integer)
Return Function(upTo As Integer) Enumerable.Range(0, upTo + 1).Sum()
Public Shared ReadOnly Property ShowMessageBox As Action(Of String)
Return Function(text As String) MessageBox.Show(text)
SampleClasses.Lambdas.ShowMessageBox(SampleClasses.Lambdas.AddFromZeroUpTo(8)) 'wont work
SampleClasses.Lambdas.AddFromZeroUpTo(8) 'wont work
Dim msg = SampleClasses.Lambdas.ShowMessageBox
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.