Marking A Class Static in VB.NET


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.

5/23/2017 12:02:36 PM

Accepted Answer

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 equivalent to a C# static class, use a Module. It can't be inherited and all members, properties, and methods are static/shared.

1/7/2009 4:20:40 PM

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.

MSDN - Static Classes and Static Class Members

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow