Shared ArrayUse Shared arrays within a class to store data among many instances of the class.
This page was last reviewed on Jan 9, 2024.
Shared array. 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.
Example. 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.
Step 1 We call a Function called PrintAll which loops over the 2 arrays with For-Each statements. It prints all the array contents.
Step 2 We mutate the elements within the values array by adding 1 to each of them. A Shared array can be modified.
Step 3 It is possible to reassign a Shared array to a new array. The new array can be used in the same way as the old one.
Step 4 With another call to 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 Module
10 20 30 40 50 blue yellow orange red ... 11 21 31 41 51 tan magenta grey ...
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 9, 2024 (new).
© 2007-2024 Sam Allen.