How to create and use shared members by using Visual Basic .NET or Visual Basic 2005

Summary

This article describes how to implement shared members within a class, as well as how to reference other class members from shared methods and shared properties.

Visual Basic .NET or Visual Basic 2005 provides the necessary language features to enable object-oriented programming. Central to this approach is the class that implements its functionality using methods (functions and procedures), properties, and fields. These are referred to as members.

Shared members (which are called static or class members in some other languages) are not associated with a specific instance of a class and are thus shared by all objects that are instantiated from that class. To call a shared member, you can qualify it either with the class name or with an object of that class. Because shared members are not associated with object instances, they do not have access to non-shared members (which are accessed through "Me," which represents the current object instance).

Non-shared members are called instance members because they are associated with individual object instances. Think of shared members as belonging to the class and instance members belonging to instances of the class (that is, objects).

Requirements

This article assumes that you are familiar with the following topics:
  • Object-oriented concepts
  • Creating classes in Visual Basic .NET or in Visual Basic 2005
  • Visual Basic .NET or Visual Basic 2005 properties

Create a New Visual Basic .NET or Visual Basic 2005 Project and Class

The code in this project demonstrates how to implement shared methods, shared properties, and instance methods. Some of the following code contains deliberate errors to illustrate key points about how to access other members from shared members. As a result, the code compiles only after you comment out or remove the lines that cause the error.
  1. Start Visual Studio .NET or Visual Studio 2005, and create a new Visual Basic Console Application project named SharedMethod.
  2. From the Project menu, click Add Class to create a new class.
  3. Add two private instance fields as follows:
        'Instance variables
    Private myInt As Integer
    Private myStr As String
  4. Use the Shared keyword to add two private shared fields as follows:
        'Class variables
    Private Shared sharedInt As Integer
    Private Shared sharedPropValue As String
  5. Save the project.

Create the Instance Method, Shared Method, and Shared Property

  1. Add the following instance method named mySub:
       'An instance method
    Sub mySub()
    myInt = 1 ' Ok, same as Me.myInt = 1
    sharedInt = 1 ' Ok, same as Class1.sharedInt = 1
    End Sub
  2. Use the Shared keyword to add the following shared method named sharedSub. Remember that shared methods can only access other shared members and not instance members.
        'A class method
    Shared Sub sharedSub()
    myInt = 1 ' Error, cannot access Me.myInt
    sharedInt = 1 ' Ok, same as Class1.sharedInt = 1
    End Sub
  3. Use the Shared keyword to add a shared, read-write string property named sharedProp as follows:
        'A class property
    Shared Property sharedProp() As String
    Get
    'can only refer to shared variables
    Return myStr 'Error, cannot access Me.myStr
    Return sharedPropValue 'Ok, same as Return Class1.sharedPropValue

    End Get
    Set(ByVal Value As String)
    'can only refer to shared variables
    myStr = Value 'Error, cannot access Me.myStr
    sharedPropValue = Value 'Ok, same as Class1.sharedPropValue = Value
    End Set
    End Property
  4. Save Class1.vb.

Compile the Class

  1. Build the class, and notice that three error messages appear in the Task List window.

    The first error occurs at the following line of code in the SharedSub method:
    myInt = 1       ' Error, cannot access Me.myInt
    Because SharedSub is a shared member, it is associated with the class and can only access shared members. You cannot use the "Me" keyword here because instance members are not accessible from within a shared member. Remove the offending line of code.
  2. The second error occurs at the following line of code in the sharedProp property:
    Return myStr      'Error, cannot access Me.myStr
    Remove the offending line of code.
  3. The third error occurs at the following line of code in the
    sharedProp property:
    myStr = Value              'Error, cannot access Me.myStr
    Remove the offending line of code.
  4. Rebuild the class.

Create the Test Module

  1. Open Module1.vb.
  2. Add the following code, which uses the class name to reference Class1 members, to the sub Main procedure:
    Dim outStr As String

    'Use class to refer to members
    Class1.sharedSub() 'Ok
    Class1.sharedProp= "Class" 'Ok
    outStr = Class1.sharedProp 'Ok
    Class1.mySub() 'Error only available to an
    'instance
  3. Add the following code, which uses an object reference to reference Class1 members:
    'Use an object reference to refer to members
    Dim MyObject As Class1
    MyObject.sharedSub() 'Ok
    MyObject.sharedProp = "Obj Ref" 'Ok
    outStr = MyObject.sharedProp 'Ok
    MyObject.mySub() 'This will fail at runtime as
    'MyObject is Nothing
  4. Save the project.

Compile the Test Module

  1. Build the project.
  2. Notice that an error message appears in the Task List window. This error occurs in the following line of code:
            Class1.mySub()                  'Error only available to an 
    'instance
    mysub is an instance method and thus is only available to an instance of a Class1 object. Remove the offending line of code.
  3. From the Debug menu, click Start Without Debugging to run the application outside of the debugger. Note that the Just-In-Time (JIT) debugger displays the "System.NullReferenceException" error. Click No in the Just-In-Time dialog box to return to the source code.
  4. This exception occurs because the following line of code creates an object reference instead of the instantiated object, which is required to execute an instance method.
            Dim MyObject As Class1
  5. To create an instantiated object, modify the offending code as follows:
            Dim MyObject As New Class1()
  6. Save, rebuild, and run the project.

Troubleshoot

  • You can only invoke instance methods and properties on an object instance. Within the instance method, you can reference both instance and shared members.
  • To invoke shared members, you can use the class itself, an object reference, or an object instance. Within the shared member, you can only reference other shared members.
  • You cannot refer to an instance member of a class from within a shared method or within a shared member initializer without an explicit instance of the class. Me is valid only within an instance method.

References

For more information about using shared methods, refer to the "Shared Methods" topic in the "Visual Basic Language Specification" section of the Visual Basic .NET or Visual Basic 2005 online documentation, visit the following Microsoft Website: For a general description of object-oriented programming in Visual Basic .NET or in Visual Basic 2005, refer to the "Visual Basic .NET" or "Visual Basic 2005" section of the Visual Basic .NET or Visual Basic 2005 online documentation, visit the following Microsoft Website:
For additional information, click the article number below to view the article in the Microsoft Knowledge Base:
308230 How To Define and Use Properties in Visual Basic .NET
Propriedades

ID do Artigo: 308371 - Última Revisão: 6 de dez de 2006 - Revisão: 1

Comentários