Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C#'s static the same as NotInheritable in VB.NET?

Tags:

c#

vb.net

A class that contains utility methods is needed over and over all over the place. So, I'd like to make it a static class.

Why static is being converted to NotInheritable?

public static class MyClass 
{
    public static string MyProperty { get; set; } 

    public static void MyMethod()
    {

    }
}

to

Public NotInheritable Class Employee
   Private Sub New()
   End Sub
   Public Shared Property MyProperty() As String
      Get
          Return m_MyProperty
      End Get
      Set
          m_MyProperty = Value
      End Set
  End Property
  Private Shared m_MyProperty As String

  Public Shared Sub MyMethod()
  End Sub
 End Class

In my opinion, this looks more like a sealed class, doesn't it?

like image 963
Richard77 Avatar asked Dec 01 '22 16:12

Richard77


2 Answers

Why static is being converted to NotInheritable?

It's not getting directly converted. The fact that static classes are sealed is what makes the equivalent class in VB.NET NonInheritable

In my opinion, this looks more like a sealed class, doesn't it?

Yes, but it's not "wrong" because static classes are also sealed.

VB.NET does not have the concept of a "static class". The closest it has is module, which is not the exact equivalent of static since it cannot, for example, nest another module within it, while you can define a static class within another static class in C#. So the converter may just be erring on the side of caution by not translating a static class to a Module.

Since static classes in C# are sealed classes that can't be instantiated, the closest thing to an equivalent class in VB.NET is a NotInheritable class with all Shared methods and properties, with a private default instance constructor so the class cannot be instantiated.

So the resulting VB class has all of the characteristics of the source class, but the mechanisms to provide those features are somewhat different.

like image 141
D Stanley Avatar answered Dec 05 '22 01:12

D Stanley


I'm not sure what you've used to convert static to NotInheritable, but they are not equivalent.

NotInheritable in VB.NET is equivalent to sealed in C#.
C#'s static is called Shared in VB.NET.

Of note, is that Shared cannot be applied to classes, only members of a class. This is outlined in the VB.NET specification

Class Declarations:

ClassDeclaration ::=
   [ Attributes ] [ ClassModifier+ ] Class Identifier LineTerminator
   [ ClassBase ]
   [ TypeImplementsClause+ ]
   [ ClassMemberDeclaration+ ]
   End Class LineTerminator
ClassModifier ::= AccessModifier | Shadows | MustInherit | NotInheritable

(note the conspicuous lack of Shared under ClassModifier ::=)

As mentioned by other users, a Module is a better equivalent to a C# static class.

like image 44
Squimmy Avatar answered Dec 05 '22 01:12

Squimmy