What is the difference between a module and a class?
vb.net, visual-studio
Solution
A class is a type. You can use this type like any other type (`String`, `Integer`, `Date`, `FileInfo` ...) to declare variables, parameters, properties, and function return types.
Let us make a little example:
Public Class Person
Public Property FirstName As String
Public Property LastName As String
Public Overridable Sub Print() 'I will explain Overridable later.
Console.WriteLine($"{FirstName} {LastName}")
End Sub
End Class
Now you can declare variables of type `Person`
Dim sue, pete As Person
Dim persons As List(Of Person)
sue = New Person()
sue.FirstName = "Susan"
sue.LastName = "Miller"
pete = New Person()
pete.FirstName = "Peter"
pete.LastName = "Smith"
persons = New List(Of Person)()
persons.Add(sue)
persons.Add(pete)
For Each person As Person In persons
person.Print()
Next
Whereas modules are static. I.e. Data stored in a module exists exactly once. On the other hand, you do not have to instantiate a module with `New`, therefore they are often used to store global data and for methods that are available globally. For instance, you could store the persons list in a module.
But there is much more you can do with classes. You can derive a class from a base class. This new class inherits everything from the base class and can add more stuff to it. For instance, you could derive an `Employee` class from `Person`
Public Class Employee
Inherits Person
Public Property Salary As Decimal
Public Overrides Sub Print
Console.WriteLine($"{FirstName} {LastName}, Salary = {Salary}")
End Sub
End Class
The `Overridable` keyword in `Person.Print` allows deriving classes to re-define (to override) the `Print` method. (Functions and Subs in classes are called methods.)
Employees are assignment compatible to Persons. You could add an employee to the `persons` list. This does not require any change in the For Each loop, i.e., the call of `person.Print()` automatically calls the right `Print` method (the first one for "normal" persons and the second one for employees).
Dim emp as Employee
emp = New Employee()
emp.FirstName = "Frank"
emp.LastName = "Taggart"
emp.Salary = 3500.00D
persons.Add(emp)
There is much more to say about classes. I hope that you got a certain idea of what you can do with classes.
See Objects and classes in Visual Basic and especially the section Differences between classes and modules.
Problem
When adding a new file to a VB.Net project in Visual Studio, I'm given the option of both a 'Class' and a 'Module'. A class is described as ``` An empty class file ``` While a module is described as ``` A file for storing groups of functions ``` This seems to imply that a module is less useful that a class, since a class can store groups of functions and more. Is it the case that a module is simply a group of functions, or is there more to the module than the visual studio documentation suggests?