pufferfish
pufferfish

Reputation: 291

Invoke anonymous methods

Is there any difference under the hood between line 4 and line 5?

Why can't VB.net handle Line 3?

What is the proper way to call the function?

Dim aFunc As New Tuple(Of Func(Of String))(Function() "Hello World")
Dim s As String
s = aFunc.Item1() 'does not compile
s = (aFunc.Item1)()
s = aFunc.Item1.Invoke()

Upvotes: 2

Views: 302

Answers (2)

Andrew Morton
Andrew Morton

Reputation: 25023

aFunc.Item1 is a Function, so you can't assign it to a String. You appear to want:

Dim aFunc As New Tuple(Of Func(Of String))(Function() "Hello World")
Dim s As String
Dim f As Func(Of String) = aFunc.Item1
s = f.Invoke()

EDIT: s = aFunc.Item1() accesses the property Item1. To invoke the function which that property refers to, you can use s = aFunc.Item1()(), which is equivalent to your line 4. At a guess, property access is stronger than function invocation (if those are the correct terms).

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 941485

This looks like a compiler bug to me, the parentheses should make it unambiguously a method call. Hard to state this for a fact however, parens are heavily overloaded in vb.net to mean many things. Clearly it is the tuple that makes the compiler fumble, it works fine without it. This came up in this week's StackExchange podcast with Eric Lippert btw, you might want to listen to it to get the laundry list of things it can mean.

You could post this to connect.microsoft.com to get the opinion of the language designers. The behavior is certainly unintuitive enough to call it a bug. The workarounds you found are good. Both generate the exact same code and add no overhead, something you can see by running ildasm.exe on your assembly.

Upvotes: 3

Related Questions