Share via


Class MethodsĀ 

The methods of a class are just Sub or Function procedures declared within the class. For example, to create a Withdrawal method for a class named Account, you could add this Public function to the class module:

Public Function WithDrawal(ByVal Amount As Decimal, _
      ByVal TransactionCode As Byte) As Double
    ' Add code here to perform the withdrawal,
    ' return a transaction code, 
    ' or to raise an overdraft error.
End Function

Shared Methods

Shared methods can be invoked directly from the class without first creating an instance of the class. Shared methods are useful when you do not want a method to be associated with a specific instance of a class. Shared methods cannot be declared using the Overridable, NotOverridable, or MustOverride modifiers. Methods declared in modules are implicitly shared and cannot explicitly use the Shared modifier.

Example

Class ShareClass
    Shared Sub SharedSub()
        MsgBox("Shared method.")
    End Sub
End Class

Sub Test()
    ' Call the method.
    ShareClass.SharedSub()
End Sub

Protecting Implementation Details

Utility procedures that are used internally by a class should be declared as Private, Protected, or Friend. Restricting the accessibility of such methods protects the developers who use your objects, by allowing you to make future changes without affecting code that uses the objects.

Protecting the details of an object's implementation is another facet of encapsulation. Encapsulation allows you to enhance the performance of methods, or completely change the way a method is implemented, without having to change code that uses the method.

See Also

Tasks

How to: Add Events to a Class

Reference

Overridable
NotOverridable
MustOverride
Shared (Visual Basic)
Public (Visual Basic)
Private (Visual Basic)
Protected (Visual Basic)
Friend (Visual Basic)

Concepts

Properties vs. Methods
Shared Members in Visual Basic