Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing an object and calling a method without assignment in VB.Net

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?

like image 483
mdryden Avatar asked Feb 28 '23 04:02

mdryden


2 Answers

The magic word here is Call.

Public Sub DoSomething()
    Call (New MyHelper()).DoIt()
    Call New MyHelper().DoIt()
End Sub
like image 132
Gideon Engelberth Avatar answered May 19 '23 13:05

Gideon Engelberth


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
like image 28
M.A. Hanin Avatar answered May 19 '23 14:05

M.A. Hanin