views:

60

answers:

3

I'm not entirely sure what to call what C# does, so I haven't had any luck searching for the VB.Net equivalent syntax (if it exists, which I suspect it probably doesn't).

In c#, you can do this:

public void DoSomething() {
    new MyHelper().DoIt(); // works just fine
}

But as far as I can tell, in VB.Net, you must assign the helper object to a local variable or you just get a syntax error:

Public Sub DoSomething()
    New MyHelper().DoIt() ' won't compile
End Sub

Just one of those curiosity things I run into from day to day working on mixed language projects - often there is a VB.Net equivalent which uses less than obvious syntax. Anyone?

A: 
Public Sub DoSomething()
    (New MyHelper()).DoIt() 
End Sub

Try that. Legal syntax, should work fine.

EDIT: Nope, it isn't.

Tom Tresansky
Thanks, but no dice, still a syntax error.
mdryden
Right you are.Weird that this: Dim a As SomeObject = (New SomeOtherObject()).Function() is legal, but (New SomeOtherObject()).Function() by itself is not...
Tom Tresansky
@Tom: simple reason: a logical line can contain a statement but *not* an expression (unlike in most other languages). This is “necessary” to simplify the distinction between `=` as an assignment (statement) and an equality comparison (expression).
Konrad Rudolph
+3  A: 

The magic word here is Call.

Public Sub DoSomething()
    Call (New MyHelper()).DoIt()
    Call New MyHelper().DoIt()
End Sub
Gideon Engelberth
It is magical! Nice for showing both options (with and without parentheses). +1
M.A. Hanin
Perfect, thanks :)
mdryden
A: 

Gideon Engelberth is right about using Call. It is the best option.

Another option is to use a With statement:

With New MyHelper()
    .DoIt()
End With
M.A. Hanin