2

So I've been reading up on lambdas in VB recently and am a bit confused tbh. I've got the code running properly, but want a better understanding. My main question is the use of the Invoke() method and the way of declaring a lambda.

One method I've seen is this:

Dim increment2 = Function(x)
                     Return x + 2
                 End Function

and the other:

Dim func1 As Func(Of Integer, Integer) =
                    Function(value As Integer)
                            Return value + 1
                     End Function

My question is, what's the difference? And what role does the Invoke() method play. I've seen to ways of calling lambdas, one like func1(4) and the other is func1.Invoke(4).

I should mention, that regardless of what change I make the output remains the same (5), leading me believe the change is something not very noticeable. And I'm curious as to what it is.

Storm Claw
  • 59
  • 2
  • 8
  • 1
    The first one will not compile with `Option Strict On`, the second one will. Not to be confused with [generic type inference](https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/generic-procedures#type-inference). As for `Invoke()`, see https://stackoverflow.com/q/16309286/11683. – GSerg Aug 08 '20 at 14:55
  • What's the recommended way? The first example is from the Docs, the second is from another site. – Storm Claw Aug 08 '20 at 14:57
  • 3
    I recommend turning `Option String On`, `Option Explicit On` and `Option Infer On` in the VS settings globally for all projects, and fix any code that stops compiling. You can dismiss that recommendation. – GSerg Aug 08 '20 at 14:58
  • I see. In short, I should follow the second example? – Storm Claw Aug 08 '20 at 15:19
  • 2
    I prefer using type inference when possible. That would be `Dim increment2 = Function(x As Integer) Return x + 2 End Function` – GSerg Aug 08 '20 at 15:52
  • Thanks. You've helped quite a bit. I'll leave this open for a while if someone else has anything useful to add. I'll close this in 24 hours. – Storm Claw Aug 08 '20 at 16:02
  • @StormClaw If there's anything relevant here don't close it, it may be searched and read by future users. I personnaly like what I read, although I would have prefered to read it as an answer, but I get that it would take time write as a _good_ answer. Still good. – laancelot Aug 08 '20 at 20:49
  • Understood, i'll leave it open. – Storm Claw Aug 09 '20 at 13:08

0 Answers0