Marking A Class Static in VB.NET

C#vb.net

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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 Function

End Class
  • Shared is like method of static class.
  • NotInheritable is like sealed.
  • Private New is like static class can not be instantiated.

See:
MSDN - Static Classes and Static Class Members

Solution 3 - C#

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.

Solution 4 - C#

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

Solution 5 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMagicKatView Question on Stackoverflow
Solution 1 - C#Joel CoehoornView Answer on Stackoverflow
Solution 2 - C#Gary NewsomView Answer on Stackoverflow
Solution 3 - C#Charles GrahamView Answer on Stackoverflow
Solution 4 - C#MentorView Answer on Stackoverflow
Solution 5 - C#Ilya RyzhenkovView Answer on Stackoverflow