djv
djv

Reputation: 15774

Why can an anonymous Action invoke in one line in C# but not VB?

In C#

(new Action(() => MessageBox.Show("Hello"))).BeginInvoke(null, null);

In VB the translated code doesn't compile

(New Action(Sub() MessageBox.Show("Hello"))).BeginInvoke(nothing, nothing)

But in VB I can set the result of BeginInvoke to implicit variable a and it will run (thanks @Ric for this suggestion in another post)

Dim a = (New Action(Sub() MessageBox.Show("Hello"))).BeginInvoke(Nothing, Nothing)

But now I want to know why VB requires something to be set on the left hand side in this case, where C# does not.

Upvotes: 3

Views: 1697

Answers (2)

J. Steen
J. Steen

Reputation: 15578

VB.NET simply requires an identifier. You can't invoke a sub or other member directly like that. You can, however, use Call instead.

You typically use the Call keyword when the called expression doesn’t start with an identifier. Use of the Call keyword for other uses isn’t recommended.

http://msdn.microsoft.com/en-us/library/sxz296wz(v=vs.110).aspx

Call (New Action(Sub() MessageBox.Show("Hello"))).BeginInvoke(nothing, nothing)

Upvotes: 5

Dave Doknjas
Dave Doknjas

Reputation: 6542

VB doesn't allow invoking member calls directly on an instantiation. Use:

CType(New Action(Function() MessageBox.Show("Hello")), Action).BeginInvoke(Nothing, Nothing)

Upvotes: 2

Related Questions