Sometimes we want data to belong to a Class
instance—each instantiation has its own data. But in VB.NET, sometimes an array is best shared between many class
instances.
By specify the Shared modifier on an array, we can reuse that array's data throughout all instances. We can read and modify this global data.
This program introduces an Example class
, and in the class
we declare and initialize 2 Shared arrays. The first one (values) has Integers and the second has Strings.
PrintAll
which loops over the 2 arrays with For-Each
statements. It prints all the array contents.PrintAll
, we display the new values stored in the 2 Shared arrays.Class Example Shared Dim values() = {10, 20, 30, 40, 50} Shared Dim colors() As String = {"blue", "yellow", "orange", "red"} Public Shared Sub AddValues() ' Modify the elements in the Shared integer array. For i = 0 To values.Length - 1 values(i) += 1 Next End Sub Public Shared Sub ReassignColors() ' Create new colors array. colors = {"tan", "magenta", "grey"} End Sub Public Shared Sub PrintAll() ' Write contents of arrays to console. For Each value in values Console.WriteLine(value) Next For Each color in colors Console.WriteLine(color) Next Console.WriteLine("...") End Sub End Class Module Module1 Sub Main() ' Step 1: print the contents of the shared arrays. Example.PrintAll() ' Step 2: modify the elements within a shared array. Example.AddValues() ' Step 3: reassign the colors array to a new array. Example.ReassignColors() ' Step 4: print all changed data. Example.PrintAll() End Sub End Module10 20 30 40 50 blue yellow orange red ... 11 21 31 41 51 tan magenta grey ...
Shared arrays are an ideal way to store data that it used throughout many class
instances. This can reduce memory usage, speed up class
construction, and make programs simpler.