Declaring Shared Fields


Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 11.  Shared Members

Declaring Shared Fields

Fields are variables defined in classes and structures. (Effectively, the use of data in modules is roughly equivalent to the use of shared fields in structures and classes.)

To define a shared field, precede the field declaration with the desired access specifier , the Shared keyword, the variable name , and the data type. Include an initializer if it's appropriate to do so. The following statement demonstrates declaring a shared integer:

 Public Shared Counter As Long = 0 

No matter how few or how many instances of the objects there are containing the preceding statement, there will only ever be exactly one Counter field for that class. Contained in a class, Counter may appear this way:

 Public Class SharedInteger   Public Shared Counter As Integer = 0 End Class 

Counter can be accessed using the class name:

 SharedInteger.Counter = 1 

Counter also can be accessed through an instance of the class:

 Dim Instance As SharedInteger Instance.Counter = 1 

In both examples, .Counter refers to the same Counter field, yet the first fragment accesses Counter using the class and the second example refers to Counter through the object named Instance. If we were able to evaluate the address of Counter in both examples, the address of SharedInteger.Counter would be equal to the address of Instance.Counter.

Shared fields have been used for reference counting. For example, COM uses reference counting to determine when to release an object. Each time an object is created, the code increments the counter. When an object is released, the counter is decreased. Memory allocated in the object is released only when the reference count is decreased to zero. (Keep in mind that the garbage collector takes care of releasing memory in Visual Basic .NET; reference counting is used for COM objects and historically for languages that haven't implemented garbage collection.)

In new code, you might want to implement shared fields to store data that doesn't change regardless of the state of a particular instance. Practical examples of shared fields include the Math.Pi and Math.E values representing the ratio of a circle's circumference to diameter and the natural logarithmic base, respectively.


Visual BasicR. NET Unleashed
Visual BasicR. NET Unleashed
Year: 2001
Pages: 222 © 2008-2017.
If you may any questions please contact us: