1

Having sample trivial class

Class A
    Property Property1 As Integer = 5
    Sub Action1()
        Debug.Print(Property1.ToString())
    End Sub
End Class

I can always call Action1() like

Dim instanceA As New A
instanceA.Action1()

But can I call the method without using the variable? Something like

(New A).Action1()

I'm getting syntax error at the 1st character when attempting that.

miroxlav
  • 11,796
  • 5
  • 58
  • 99

1 Answers1

1

The reason that you get a syntax error is that a line of VB code cannot begin with the New keyword. I find that the best way around that is to use the otherwise useless Call keyword:

Call New A().Action1()
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • Upon your answer I've found that exactly the above case is covered in [Call statement documentation](https://msdn.microsoft.com/en-us/library/sxz296wz.aspx). There is one more case which always requires using `Call`. It is `Call (Sub() Console.Write("Hello"))()`. – miroxlav Jul 07 '15 at 06:17