I am using VB.Net 4 and am successfully using a class with the following signature:
Sub Register(Of TMessage)(recipient As Object, action As
System.Action(Of TMessage))
I want to learn about lambdas in VB so I wanted to see if I can simplify my current code.
CURRENTLY: I have the following in the constructor of a class (simplified for clarity)
Public Sub New()
Dim myAction As New Action(Of String)(AddressOf HandleMessage)
Messenger.Default.Register(Of [String])(Me, myAction)
End Sub
And later in the class I have the following:
Private Function HandleMessage(sMsg As String)
If sMsg = "String Value" Then
If Me._Selection.HasChanges Or Me._Selection.HasErrors Then
Return True
End If
Return False
Else
Return False
End If
End Function
QUESTION: Is there a way to simplify this into a lambda like in C# where I don’t have to declare the MyAction variable in the constructor, but just pass the string value to HandleMessage function “inline” with the register sub? (I hope that makes sense)
So your constructor code is equivalent to:
It’s worth mentioning though you don’t need to use lambdas just to get rid of your explicit delegate creation. This is perfectly legal too:
There is a bit of strangeness though with your example: you’ve declared your Register method as taking an
Action(Of TMessage)which means the function passed needs no return value. Your function however is returning aBoolean. Visual Basic here is doing the fancy “delegate relaxation” and is throwing away the return value. So all yourReturn True/Return Falsebits aren’t actually doing anything special.