Search code examples
vb.netshared

Setting shared object properties inside class using VB.Net


If I have a class with a shared property, and the properties value is a new object instance created outside of a class procedure (sub/function), can I also set the properties of that shared object outside of a procedure?

Public Class Person

    Private Shared DataItem = New DataItem

    DataItem.Value = 10 ' Assuming Value is a Public Property

End Class

I think in other languages, such as Java, you could create a static block to run and setup static values: static {}

Not sure if you can do that in VB though...

EDIT: Basically the VB equivalent of a static initializer found in Java. Can't seem to find any info on this.


Solution

  • Yes you can. You will need some changes to your code if you want your DataItem variable to be accessible outside of the Person class. You you will need to change Private Shared DataItem to Public Shared DataItem or Friend Shared DataItem. If you want to limit accessibility to reading or writing you can use a method in Person to give access to specific fields. For example:

    Public Class Person
    
        Private Shared DataItem = New DataItem
    
    
        Public Sub SetVariable(ByVal value As Int)
            DataItem.Value = value
        End Sub
    
    End Class
    

    If you wanted Shared method on the parent class you can do this:

    Public Class Person
        Private Shared DataItem = New DataItem
    
        Shared Sub New()
            DataItem = New DataItem()
        End Sub
    End Class
    

    More detail here, https://msdn.microsoft.com/en-us/library/aa711965(VS.71).aspx. From MSDN:

    1. Shared constructors are run before any instance of a class type is created.
    2. Shared constructors are run before any instance members of a structure type are accessed, or before any constructor of a structure type is explicitly called. Calling the implicit parameter less constructor created for structures will not cause the shared constructor to run.
    3. Shared constructors are run before any of the type's shared members are referenced.
    4. Shared constructors are run before any types that derive from the type are loaded.
    5. A shared constructor will not be run more than once during a single execution of a program.