Shared versus Instance

 <  Day Day Up  >  

By default, all members of classes and structures are instance members . This means that all instances of a class or structure each have their own copy of the member. The following example will not print anything, because each Customer object has its own copy of the Name field. When the Name field of variable x is changed, it doesn't affect the Name field of variable y .

 Class Customer   Public Name As String End Class Module Test   Sub Main()     Dim x, y As Customer     x = New Customer()     y = New Customer()     x.Name = "John Doe"     If y.Name = x.Name Then       Console.WriteLine("Equal")     End If   End Sub End Module 

Members declared with the Shared modifier, however, are shared members . Shared members are shared by all instances of the class or structure. That means that if one instance of a class or structure changes the value of a shared member, all other instances of the class or structure will see the new value. For example:

 Class Customer   Public Prefix As String   Public Name As String   Public Shared PrintPrefix As Boolean = True   Sub PrintName()     If PrintPrefix Then       Console.Write(Prefix)     End If     Console.WriteLine(Name)   End Sub End Class Module Test   Sub Main()     Dim x, y As Customer     x = New Customer()     x.Prefix = "Mr."     x.Name = "John Smith"     Customer.PrintPrefix = False     x.PrintName()  ' Prints 'John Smith'   End Sub End Module 

In the preceding example, changing the shared PrintPrefix field changes the value for all instances of Customer , so the PrintName subroutine will not print the prefix.

Instance members can only be accessed through an instance of a type. Shared members, however, can be accessed either through an instance of a type or by using the type name itself. For example, one way to change PrintPrefix would be to say Customer.PrintPrefix = False , as it was in the preceding example. It would not be valid, however, to say Customer.Name = "John Doe" , because Customer is not an instance ”it's a type. Because shared members can be called without an instance, they cannot refer to instance members.

Style

For clarity, shared members should always be accessed through the type name, not an instance.


 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net