.net – Static Method implementation in VB.NET

.netstaticvb.net

I am confused with Static implementation in VB.NET. In C#, we can create Static class and static methods to write utility methods for our application.

Now, VB.NET lets us create Module in place of static class. If we create a method in the module, by default it becomes static. But in my application, I have written the below code:

Public Class Utility
    Public Shared Function GetValue() As String
       // My code
    End Function
End Class

By writing the code, I am able to access the utility method as Utility.GetValue(). As this is not a static class, I am supposed to instantiate an object of it. But this method is available for both the class and objects of Utility

Now my questions are:

  1. Is the implementation I have done may violate any of the features of static class that module provide?
  2. What will be difference between this and implementing a module instead?
  3. If I create a module instead, will the scope of that will be same as this class? I want to access the method throughout the project as well as other projects where this one is referenced.

I tried consulting multiple articles, but nowhere found this exact answers. Please help.

Best Solution

A VB.NET module is a static class. The compiler handles this for you. Every method and property on it is static (Shared).

A class with a static (Shared) member on it is exactly that: a class with a static (Shared) member. You don't have to create an instance of it to access the static (Shared) method, but you do to get to any of its instance members.

You can also define a Sub New() in a module, and it becomes the static constructor for the module. The first time you try to invoke a member on the module, the static constructor will be invoked to initialize the static class.