Microsoft KB Archive/308371

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

Article ID: 308371

Article Last Modified on 12/6/2006

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-



This article was previously published under Q308371





IN THIS TASK
SUMMARY
 * Requirements
 * Create a New Visual Basic .NET Project and Class
 * Create the Instance Method, Shared Method, and Shared Property
 * Compile the Class
 * Create the Test Module
 * Compile the Test Module
 * Troubleshoot

REFERENCES



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 &quot;Me,&quot; 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).

Back to the top

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

Back to the top

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.  Start Visual Studio .NET or Visual Studio 2005, and create a new Visual Basic Console Application project named SharedMethod. From the Project menu, click Add Class to create a new class.  Add two private instance fields as follows: 'Instance variables Private myInt As Integer Private myStr As String   Use the Shared keyword to add two private shared fields as follows: 'Class variables Private Shared sharedInt As Integer Private Shared sharedPropValue As String  Save the project.

Back to the top

Create the Instance Method, Shared Method, and Shared Property
  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 </li>  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 </li>  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 </li> Save Class1.vb.</li></ol>

Back to the top

Compile the Class
  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 &quot;Me&quot; keyword here because instance members are not accessible from within a shared member. Remove the offending line of code. </li>  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. </li>  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. </li> Rebuild the class.</li></ol>

Back to the top

Create the Test Module
 Open Module1.vb.</li>  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= &quot;Class&quot;      'Ok        outStr = Class1.sharedProp      'Ok        Class1.mySub                  'Error only available to an                                         'instance </li>  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 = &quot;Obj Ref&quot;    'Ok        outStr = MyObject.sharedProp       'Ok        MyObject.mySub                   'This will fail at runtime as                                           'MyObject is Nothing </li> Save the project.</li></ol>

Back to the top

Compile the Test Module
 <li>Build the project.</li> <li> 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. </li> <li>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 &quot;System.NullReferenceException&quot; error. Click No in the Just-In-Time dialog box to return to the source code.</li> <li> 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 </li> <li> To create an instantiated object, modify the offending code as follows: Dim MyObject As New Class1 </li> <li>Save, rebuild, and run the project.</li></ol>

Back to the top

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.

Back to the top

<div class="references_section">