Shared - Visual Basic (original) (raw)

Specifies that one or more declared programming elements are associated with a class or structure at large, and not with a specific instance of the class or structure.

Sharing a member of a class or structure makes it available to every instance, rather than non-shared, where each instance keeps its own copy. Sharing is useful, for example, if the value of a variable applies to the entire application. If you declare that variable to be Shared, then all instances access the same storage location, and if one instance changes the variable's value, all instances access the updated value.

Sharing does not alter the access level of a member. For example, a class member can be shared and private (accessible only from within the class), or non-shared and public. For more information, see Access levels in Visual Basic.

Rules

If Double.IsNaN(result) Then Console.WriteLine("Result is mathematically undefined.")  

Behavior

Sub Main()  
    ' The following line is the preferred way to access Total.  
    ShareTotal.Total = 10  
    ' The following line generates a compiler warning message and  
    ' accesses total through class ShareTotal instead of through  
    ' the variable instanceVar. This works as expected and adds  
    ' 100 to Total.  
    Dim instanceVar As New ShareTotal  
    instanceVar.Total += 100  
    ' The following line generates a compiler warning message and  
    ' accesses total through class ShareTotal instead of calling  
    ' ReturnClass(). This adds 1000 to total but does not work as  
    ' expected, because the WriteLine in ReturnClass() does not run.  
    Console.WriteLine("Value of total is " & CStr(ShareTotal.Total))  
    ReturnClass().Total += 1000  
End Sub  
Public Function ReturnClass() As ShareTotal  
    Console.WriteLine("Function ReturnClass() called")  
    Return New ShareTotal  
End Function  
Public Class ShareTotal  
    Public Shared Property Total As Integer  
End Class  

In the preceding example, the compiler generates a warning message both times the code accesses the shared property Total through an instance. In each case, it makes the access directly through the class ShareTotal and does not make use of any instance. In the case of the intended call to the procedure ReturnClass, this means it does not even generate a call to ReturnClass, so the additional action of displaying "Function ReturnClass() called" is not performed.

The Shared modifier can be used in these contexts:

See also