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.
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: