Reputation: 2858
The questions is pretty straight forward, and can't find the answer in any of my readying. How do shared members from a base class react when a derived object is instantiated when the base class is not instantiated in VB.Net? Does the shared constructor get called at the base level? I am trying to figure out if a base class initializes a set of shared members in the shared new()
method defined at the base class will be accesible by the instantiated derired class, given the proper accessors, if the base class is not instantiated?
Public Class Car
Protected Shared _carCount as Integer
Shared Sub New()
_carCount = 0
End Sub
Shared Public Function GetCount() as integer
return _carCount
End Sub
End Class
Public Class Sedan
Inherits Car
Shared Sub New()
_carCount = _carCount + 1
End Sub
End Sub
Sub Main()
Dim someSedan as New Sedan
System.Console.Writeline(someSedan.GetCount())
End Sub
This code is not checked, but it should give enough of an idea what I am talking about.
Upvotes: 1
Views: 770
Reputation: 14585
Shared members (Static in C#) don't concern themselves with instantiation so they will act just as they were intended. Shared constructors get called the first time the type is used so your sub class will have it's shared constructor called then the base class's
Since shared (static) cannot be inherited, they will both run.
If the set of members are static then they will be "initialized" on that TYPE. Again, you can't inherit shared (static) members. You would have to explicitly call them from the base class to "initialize" them from the sub class
as far as derived from another language, it doesn't matter. It will work the same. I'ts all IL in the end.
If you want to initialize a sub class but not the base class then you need to use composition, not inheritence.
Upvotes: 0
Reputation: 564413
"derived object is instantiated when the when the base class is not instantiated in VB.Net?"
When you instantiate a derived class, the base class constructor is always called. A constructor for an instance of a type implicity calls that type's base class constructor first - even if you don't explicitly choose a constructor, the default constructor is run.
Does the shared constructor get called at the base level?
Yes. The shared constructor will get called at some point before the first access of the base class type. This includes instantiation of the derived class, as any instantation of the derived class automatically (implicity) calls the base class constructor. This, in turn, forces the type to be accessed.
The CLI specification guarantees that the shared (static) constructors will all be run prior to this occurring. You do not have to worry - your shared members will all get initialized via the shared constructor prior to being used.
Upvotes: 3