Bagikan melalui


Classes vs. Modules

Both classes and modules are reference types that encapsulate the items defined within, but they differ in how items are accessed from other procedures.

Differences Between Classes and Modules

The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot. Because there is only one copy of a standard module's data, when one part of your program changes a public variable in a standard module, any other part of the program gets the same value if it then reads that variable. In contrast, object data exists separately for each instantiated object. Another difference is that unlike standard modules, classes can implement interfaces.

Note

When the Shared modifier is applied to a class member, it is associated with the class itself instead of a particular instance of the class. The member is accessed directly by using the class name, the same way module members are accessed. For more information about shared members, see Shared Members in Visual Basic.

Classes and modules also use different scopes for their members. Members defined within a class are scoped within a specific instance of the class and exist only for the lifetime of the object. To access class members from outside a class, you must use fully qualified names in the format of Object.Member.

On the other hand, members declared within a module are publicly accessible by default, and can be accessed by any code that can access the module. This means that variables in a standard module are effectively global variables because they are visible from anywhere in your project, and they exist for the life of the program.

See Also

Concepts

Structures and Classes

Shared Members in Visual Basic

Reference

Shared (Visual Basic)

Other Resources

Understanding Classes