Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marking A Class Static in VB.NET

Tags:

c#

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.

like image 288
MagicKat Avatar asked Sep 25 '08 20:09

MagicKat


People also ask

What is static in VB net?

A static variable continues to exist and retains its most recent value. The next time your code calls the procedure, the variable is not reinitialized, and it still holds the latest value that you assigned to it. A static variable continues to exist for the lifetime of the class or module that it is defined in.

How do you declare a static class?

We can declare a class static by using the static keyword. A class can be declared static only if it is a nested class. It does not require any reference of the outer class. The property of the static class is that it does not allows us to access the non-static members of the outer class.

What is an static class?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.

What is static class in dotnet?

In static class, you are not allowed to create objects. In non-static class, you are allowed to create objects using new keyword. The data members of static class can be directly accessed by its class name. The data members of non-static class is not directly accessed by its class name.


2 Answers

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.

like image 50
Joel Coehoorn Avatar answered Sep 19 '22 20:09

Joel Coehoorn


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

like image 27
Gary Newsom Avatar answered Sep 18 '22 20:09

Gary Newsom