Reputation: 1384
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:
I tried consulting multiple articles, but nowhere found this exact answers. Please help.
Upvotes: 32
Views: 64028
Reputation: 8327
Use 'shared' to make a class sub or function 'static' (in the C# sense). In VB, shared is like a synonym for static, in this context.
Upvotes: 15
Reputation: 17002
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.
Upvotes: 44