Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes vs. Modules in VB.NET

Tags:

vb.net

Is it considered an acceptable practice to use Modules instead of Classes with Shared member functions in VB.NET?

I tend to avoid Modules, because they feel like leftover remains from Visual Basic 6.0 and don't really seem to fit in anymore. On the other hand, there doesn't seem to be much difference between using a Module and a Class with only Shared members. It's not that often that I really have much need for either, but sometimes there are situations where they present a simple solution.

I'm curious to hear whether you have any opinion or preferences one way or the other.

like image 771
Tom Juergens Avatar asked Oct 06 '22 04:10

Tom Juergens


People also ask

What is difference between module and class in VB net?

The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot.

What is the difference between modules and classes?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).

What is difference between class module and form module in VB?

Actually, form are just class module that have control placed on form and can we display form windows. Class modules do not have visual component as compare to form module. Standard module: – Standard module are container for procedure and declaration, commonly accessed by other module with in the application.

What is a module vb net?

A Module is not a class. It is a container element, but is not an object. In a Module, all members are shared and have "Friend" accessibility. Some notes. We cannot instantiate a Module—it serves mainly to organize code in a global, single place.


2 Answers

Modules are VB counterparts to C# static classes. When your class is designed solely for helper functions and extension methods and you don't want to allow inheritance and instantiation, you use a Module.

By the way, using Module is not really subjective and it's not deprecated. Indeed you must use a Module when it's appropriate. .NET Framework itself does it many times (System.Linq.Enumerable, for instance). To declare an extension method, it's required to use Modules.

like image 134
mmx Avatar answered Oct 24 '22 20:10

mmx


I think it's a good idea to keep avoiding modules unless you stick them into separate namespaces. Because in Intellisense methods in modules will be visible from everywhere in that namespace.

So instead of ModuleName.MyMethod() you end up with MyMethod() popups in anywhere and this kind of invalidates the encapsulation. (at least in the programming level).

That's why I always try to create Class with shared methods, seems so much better.

like image 21
dr. evil Avatar answered Oct 24 '22 21:10

dr. evil