0

Is there a way to call directly a method without creating instance of specific class like it is in C# so apart from that way:

Dim myclass as New ClassX
myclass.MyMethod()

is there a way to use soemthing like:

New ClassX.MyMethod

i found this way and seems to be working but not sure if its correct:

   (New ClassX).MyMethod

1 Answer 1

5

If your method is an instance-level method you can only access it by using an instance of the class. By using

(New ClassX).MyMethod

you implicitly create a new instance that you access only once.

An alternative is to change the method's signature and mark it as a Shared method:

Public Class ClassX
    Public Shared Sub MyMethod()
        ' ...
    End Sub
End Class

Shared is the VB.NET way of creating a static method as it is called in C#. This way, you can access the method by only specifying the class name without creating an instance:

ClassX.MyMethod()
Sign up to request clarification or add additional context in comments.

2 Comments

hi i was not talking about shared - i was talking not shared class (sorry should mentioned). Ok so in case non shared class it is correct to use this convence right?: (New ClassX).MyMethod
Please note that the class itself is not Shared. It is just the specific method that is Shared. So you can call this method without creating an instance, but not the others that are not Shared. Of course it is ok to use (New ClassX).MyMethod if required, but it is that done seldom. If it is a widely used case to call MyMethod without having an instance, I'd mark the method Shared.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.