As just stated in a recent question and answer, you can’t inherit from a static class. How does one enforce the rules that go along with static classes inside VB.NET? Since the framework is compatible between C# and VB it would make sense that there would be a way to mark a class static, but there doesn’t seem to be a way.
Module == static class
If you just want a class that you can’t inherit, use a NotInheritable class. But it won’t be static/Shared. You could mark all the methods, properties, and members as Shared, but that’s not strictly the same thing as a static class in C# since it’s not enforced by the compiler.
If you really want the vb.net equivalent to a C# static class, use a Module. It can’t be inherited and all members, properties, and methods are static/shared.
Almost there. You’ve got to prevent instantiation, too.
NotInheritable Class MyStaticClass ''' <summary> ''' Prevent instantiation. ''' </summary> Private Sub New() End Sub Public Shared Function MyMethod() As String End Sub End Class
- Shared is like method of static class.
- NotInheritable is like sealed.
- Private New is like static class can not be instantiated.
If you just want to create a class that you can’t inherit, in C# you can use Sealed, and in VB.Net use NotInheritable.
The VB.Net equivalent of static is shared.
You can create static class in vb.net. The solution is
Friend NotInheritable Class DB Public Shared AGE As Integer = 20 End Class
AGE variable is public static, you can use it in other code just like this
Dim myage As Integer = DB.AGE
Friend = public, NotInheritable = static
From the CLR point of view, C# static class is just “sealed” and “abstract” class. You can’t create an instance, because it is abstract, and you can’t inherit from it since it is sealed. The rest is just some compiler magic.
I think the VB.NET equivalent of