What is the difference between "Class program" and "module program" in VB.net [duplicate] - vb.net

This question already has answers here:
Classes vs. Modules in VB.NET
(8 answers)
Closed 3 years ago.
I want convert a C# code to vb.net console.
This is first time I find this two type code structure.
1.
Namespace ConsoleApp4
Module Program
Public Sub Main(ByVal args As String())
test()
End Sub
sub test()
end sub
End Module
End Namespace
2.
Namespace ConsoleApp4
Class Program
Public Shared Sub Main(ByVal args As String())
test()
End Sub
shared sub test()
end sub
End Class
End Namespace
what is the difference of this two type?

Sub Main must be shared to work as entry point of the application. It is automatically shared (or static) in modules. In classes the Shared keyword is required.
A VB module corresponds to a C# static class. Static classes and modules have only static members that can be used without having to create an object. In contrast, a non-static class must be instantiated to access its non-static (C#) or non-shared (VB) members
Module M
Public Function F(ByVal x As integer) As Integer
Return x * x
End Function
End Module
Class C
Public Function T(ByVal x As Integer) AS Integer
Return x + 10
End Function
End Class
With these declarations, you can write
Dim r1 As Integer = M.F(5) ' Or simply F(5) '
Dim o As C = New C() ' Must instantiate class, i.e., create an object.'
Dim r2 As Integer = o.T(32)
If you have variables (or properties) in a module, those exist exactly once. You can, however, create many objects from the same class and each object will contain another copy of these variables
Public Class Person
Public Property FirstName As String
Public Property LastName As String
End Class
Using this class declaration you can write
Dim list As New List(Of Person)()
list.Add( New Person With { .FirstName = "Terry", .LastName = "Adams"} )
list.Add( New Person With { .FirstName = "Lisa", .LastName = "Jones"} )
For Each p As Person In list
Console.WriteLine($"Person = {p.FirstName} {p.LastName}")
Next
Now you have two Person objects in the list having different first and last names.
Classes belong to Object-oriented programming (OOP). I suggest you to read some introductions about it, as .NET is mainly based on OOP concepts.
See also:
Object-oriented programming (Visual Basic)
Explain Object Oriented Programming in VB.NET

The difference between a Module and a Class is subtle; there is only ever one instance of a Module in all your program's life, and you cannot make multiple instances of it using the New keyword. By contrast you have to make an instance of a Class before you can use it..
In order to run, the .net framework runtime has to be able to find an available Main method without having to create an instance of a Class. This is achieved either by having the Main be kept inside a Module (and thus the Main is available because the module is available without having to instantiate a Class) or having it declared as Shared and be inside a Class (in which case you can conceive that a special thing happens that makes the shared Subs available without a class instance)
It's a hard difference to explain if you're not really well introduced to the concepts of OO programming and what "instances" actually means:
Class Person
Public Name as String
Public Sub New(n as String)
Name = n
End Sub
End Class
This declares a class of type person. Nothing about it refers to a particular person and it doesn't cause any Person object to exist in the computer memory until you use New:
Dim cj as New Person("Caius Jard")
Dim g as New Person("gxmgxm")
g.Name = "gsmgxm" 'correct a typo! this edits the name in the g object. it leaves cj's name alone
Now two instances of a Person object are in your computer memory, one named for me and one for you. You cannot do this with a Module. If we'd declared Person as Module there would only be one of them in all the entire program, accessed by the reference "Person":
Person.Name = "Caius Jard"
Person.Name = "gsmgxm" 'this overwrites my name. The program cannot remember more than one Person
and we couldn't have multiples. Consider that, at the time you launch your program, the runtime finds everything that is declared to be a Module and creates just one of them. This is somewhat vital for all sorts of advanced reasons that I won't get into, and Modules definitely do have their place in the grand scheme of things but thy aren't always incredibly useful in OO programming because more of the time we want more than one instance of a thing so we can model multiple things simultaneously.
So that's a precis on Class vs Module and why they are. In order to call any Sub or Function, you have to be able to call it on something. You have to have a DVD player before you can put a DVD in it and press Play - equally in programming, you have to have something that you can put your Main sub on, so you (or the .net runtime) can refer to it with Program.Main() and execute the instructions of the Sub.. That's how Subs and Functions work - theyre either associated with the special single instance (if it's a Module or a Shared Sub/Function of a Class), or they're associated with some object instance in the computer memory, and calling the Sub/Function acts on the object instance that was referred to:
Class Person
Public Name as String
Public Sub SetNameBlank()
Name = ""
End Sub
End Class
cj.SetNameBlank() 'the name of the cj object we declared before, is now blank
g.SetNameBlank()
By specifying the object instance name cj then the Sub name, we establish context - the actions listed in SetNameBlank will be carried out against the cj object, not the g one. If we'd declared SetNameBlank as Shared then they would have taken place in the shared context, not related to either cj or g, and Shared SetNameBlank() could be invoked without cj or g even existing
Going back to the reason you're asking your question right now, what the difference between these two (in the context of a "Main" Sub), the answer is..
..is "not much" from the perspective of getting your app going. Either approach is fine. Your Main method will have to start kicking things off my making object instances of the other Classes you have in your program and getting them to do things. It probably wont make new instances of the class that your Main is in so right now it doesn't really matter whether you put your main in a module or a class - it achieves the same end result that there is a Sub the runtime can call into to start things moving, without needing to create an instance of a Class first
https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/program-structure/main-procedure

Related

Visual Basic - stack overflow from object references

I'm making a little text based adventure game in VB and I have different classes for different functions in the game (to keep organized). Well, I need two classes to reference each other. I'll explain.
So these two classes are Direct.vb and Commands.vb. I created references in the files so that they could execute methods in each other's code.
Direct.vb references Commands.vb like so:
Dim comm As New Commands
And then Commands.vb references Direct.vb in the same way.
Dim dir As New Direct
But when I run the program to see if it works, it throws a StackOverflowException. I think these classes are doing an infinite loop of references.
Is there a way I can fix this?
You can reference one class from the other, but you can't have them both create a new instance of the other.
In your current case, say you create one Commands, this creates one Direct, this creates one Commands, this creates one Direct, etc., etc.
This will fill the heap and the stack, but the stack runs out first with constructor functions.
The solution is to use a reference only, so omit the New keyword from at least one of these classes. Without knowing the specifics, it's not really possible to give more specific advise. Typically, though, this kind of construction would work:
Public Class Commands
Private dir As Direct
Public Sub New()
dir = New Direct(Me)
End Sub
End Class
Public Class Direct
Private cmd As Commands
Public Sub New(ByVal cmdInstance As Commands)
cmd = cmdInstance
End Sub
End Class

Reference to a non-shared member requires an object reference in VB.net

I have a VB.net program that I got from someone else. It is comprised of a main form and 6 other modules (all .vb files). These files all have a "VB" icon next to them in the Explorer pane. I am trying to make a call to a sub-routine in one of the modules from the main form. My line of code is:
QuoteMgr.StartGettingQuotesLevel2(sSym)
where QuoteMgr is the name of the module and StartGettingQuotesLevel2(sSym) is the name of the sub-routine. When I enter this, I get the error message:
Reference to a non-shared member requires an object reference.
The sub-routine is defined in the QuoteMgr Module as follows:
Public Sub StartGettingQuotesLevel2(ByVal oSymbol As String)
What is strange is when I enter:
QuoteMgr.
(the name of the module with a period), it does not show me all the sub-routines and functions in the module. It only shows:
Update_Level1
Update_Level12
Update_Level2
These are Public Const in the module.
Can you tell me what I need to do?
What the compiler is trying to tell you with this error message
Reference to a non-shared member requires an object reference
is that the StartGettingQuotesLevel2 subroutine is an instance method not a shared or class method, see a more detailed explanation here
To call an instance method, you need to have an object instance to call it on. In your case, an object instance of the class type QuoteMgr. Like in the example below:
' create a new QuoteMgr object instance
Dim myQuoteMgr As QuoteMgr = New QuoteMgr()
' call its instance method with "abc" as its oSymbol argument.
myQuoteMgr.StartGettingQuotesLevel2("abc")
It is possible that you only want a single QuoteMgr object instance to be created and used by your main form. In that case, you can make it a member variable of your main form and create it once.
Public Partial Class MainForm
' Create it as a private member variable of the main form
Private m_QuoteMgr As QuoteMgr = New QuoteMgr()
' Use it when "some" button is pressed
Private Sub btnSome_Click(sender As Object, e As EventArgs) Handles btnSome.Click
m_QuoteMgr.StartGettingQuotesLevel2(txtSymbol.Text)
' And possibly do something with the results.
End Sub
End Class
Also, if instances of your QuoteMgr class depend on other object instances for their tasks, you will have to supply these to the constructor method of the QuoteMgr class as the arguments for its constructor's method parameters. Constructors (Sub New(...)) look like this:
Public Class QuoteMgr
' This is a constructor that takes two arguments
' - oMainSymbol: a string value
' - oKernel: an instance of the type Kernel
Public Sub New(oMainSymbol As String, ByRef oKernel As Kernel)
' ....
End Sub
End Class
That means, that when you create a QuoteMgr instance, you have to call its constructor method with the things it need, for example
' There must be an instance of Kernel created somewhere.
Dim myKernel As Kernel = ....
' create a new QuoteMgr object instance with these arguments:
' - oMainSymbol = "SYMABC"
' - oKernel = myKernel
Dim myQuoteMgr As QuoteMgr = New QuoteMgr("SYMABC", myKernel)
Some other recommendations
The explanations I have provided, are about basic VB.NET language features (e.g. the terms highlighted in bold). I suggest that before you make any changes to the code you have, you (1) make a backup of it, and (2) try to read a tutorial and practice on something smaller.
The compiler is (virtually) always right. When it gives you an error message, read it carefully, it will indicate the line where something is wrong and a message that tells you what it needs or is missing.
It is not the purpose of Stack Overflow to provide tutorials or code. It is a Q&A site where the best questions and answers deal with specific, delineated programming problems, for which succinct answers are possible.
Right click your application and go to Properties.
Make sure your application type is "Windows Forms Application".
It means that the routine you are trying to call needs to reference an instance of the form to access the routine. You can either reference an instance as Alex says, or you can make the routine 'Shared', so it doesn't need an instance. To do this, change the definition in QuoteMgr.vb to
Friend Shared Sub StartGettingQuotesLevel2(ByVal oSymbol As String)
Switching it to `Shared' may start showing compiler errors, if the routine accesses form controls or module-level variables. These will need to be added to the parameter list.

Whats the difference between these two initialization methods for a class member in VB.Net?

Whats the difference between these two initialization methods for obj? I've seen both of these, but know know if there is an appropriate time to use one vs the other. I found this post which covers C#, but not sure if the same applies to VB.Net.
Public Class Class1
Sub New()
End Sub
Dim obj As New Object
End Class
vs
Public Class Class1
Sub New()
obj=New Object
End Sub
Dim obj As Object
End Class
My apologies ahead of time if this a duplicate.
In this case, there is no difference. The main difference would be if your constructor does other operations -
In that case, the inline initialization (Dim obj As New Object) will occur prior to any code inside the constructor. Putting the initialization in the constructor lets you choose the order of initialization.
Virtually nothing is different about these samples. In both cases you get the following order of operations
Constructor for Class1 is called
Base constructor (Object in this case) is called
Field obj is assigned a value
In all likely hood it results in identical IL being generated.
Your first version is "declarative". The advantages of it are:
It is easier to see how an field as initialized, as you don't have to look for it in the constructor.
If you have multiple constructors you don't need to repeat yourself.
Your first version is "imperative". The advantages of it are:
You control exactly when it gets created.
You can have different versions for each constructor.
I personally default to declarative style code whenever possible.

Does instantiating and initializing work only when tied to button click?

Beginner question. How come I can do this:
Public Class Form1
Private StudentsInMyRoom As New ArrayList
Public Class student
Public name As String
Public courses As ArrayList
End Class
Private Sub btnCreateStudent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateStudent.Click
Dim objStudent As New student
objStudent.name = "Ivan"
objStudent.courses = New ArrayList
StudentsInMyRoom.Add(objStudent)
End Sub
End Class
But I CANNOT do this:
Public Class Form1
Private StudentsInMyRoom As New ArrayList
Public Class student
Public name As String
Public courses As ArrayList
End Class
Dim objStudent As New student
objStudent.name = "Ivan"
objStudent.courses = New ArrayList
StudentsInMyRoom.Add(objStudent)
End Class
In the second example, all of the objStudent.etc get squiggly underlined and it says "declaration expected" when I hover over it. It's the same code except now it is not tied to clicking a button. Can't figure out what is the difference.
It's because the implementation needs to be in a method, the way you have it means the code couldn't possibly be executed, how would you reference this code from elsewhere?
It doesn't have to be tied to a click however:
Private Sub AnyNameYouLike
Dim objStudent As New student
objStudent.name = "Ivan"
objStudent.courses = New ArrayList
StudentsInMyRoom.Add(objStudent)
End Sub
Will work.
Rather than tell you how to fix this code directly, I'm going to explain what I think is going wrong with your thought process, so you can also do a better job writing code in the future.
What I see here is a simple misunderstanding for someone new to programming of how classes work. When you build and define a class, you are not (yet) allocating any memory in the computer, and you are not yet telling the computer to do anything. All you are doing is telling the computer about how an object might look at some point in the future. It's not until you actually create an instance of that class that anything happens:
Public Class MyClass
Public MyField As String
End Class
'Nothing has happened yet
Public myInstance As New MyClass()
'Now finally we have something we can work with,
' but we still haven't done anything
myInstance.MyField = "Hello World"
'It's only after this last line that we put a string into memory
Classes can only hold a few specific kinds of things: Fields, Properties, Delegates (events), and Methods (Subs and Functions). All of these things in the class are declarations of something, rather than the thing itself.
Looking at your samples, the code from your second example belongs inside of a method.
If you want this code to run every time you work with a new instance of your class, then there is a special method, called a constructor, that you can use. That is declared like this:
Public Class MyClass
Public MyField As String
'This is a constructor
Public Sub New()
MyField = "Hello World"
End Sub
End Class
However, even after this last example you still haven't told the computer to do any work. Again, you must create an instance of the class before the code in that constructor will run.
This is true of all code in all .Net programs anywhere. The way your program starts out is that the .Net framework creates an instance of a special object or form and then calls (runs) a specific method in that form to sort of get the ball rolling for your program. Everything else comes from there.
Eventually you will also learn about Shared items and Modules, that can (sort of) break this rule, in that you don't have to create an instance of the object before using it. But until you are comfortable working with instances, you should not worry about that too much.
Finally, I want to point out two practices in your code that professional programmers would consider poor practice. The first is ArrayLists. I can forgive this, because I suspect you are following a course of study that just hasn't covered generics yet. I only bring it up so you can know not to get too attached to them: there is something better coming. The second is your "obj" prefix. This was considered good practice once upon a time, but is no longer fashionable and now thought to be harmful to the readability of your code. You should not use these prefixes.

Curious question - Interface Variables (ie dim x as Iinterface = object?) And also if object is a form

vb.net windows forms question.
I've got 3 forms that have exactly the same functions, so I decided to create an interface.
public Interface IExample
public sub Add()
Public sub Edit()
Public sub View()
End Interface
Then I created the 3 forms, and added the 'implements interface IExample' to each.
public class frmExample1
implements Interface IExample
Same for frmExample2, frmExample3
Finally, in code, I declare a variable of the interface type ..
Dim objfrmExample as IExample
then ...
objFrmExample = frmExample2
At this point, objfrmExample is now instantiated, even though I've not done a "objfrmExpample = new [what-goes-here?] " and I'm curious as to why.
I could possibly guess that because you cannot instantiate an interface variable, then vb.net automatically creates an instance. But thats just a guess. The question is , what is meant by declaring a variable of type Interface, and how does it work?
Anyway, just curious :-)
At this point, objfrmExample is now instantiated, even though I've not done a "objfrmExpample = new [what-goes-here?] " and I'm curious as to why.
This has nothing to do with interfaces. You can always treat a form class name in VB as though it were an instance. The reason is that the VB compiler creates properties of all your forms inside My.Forms. Now you can access a “default” instance of each form by accessing My.Forms.<FormName>.
Now comes the ugly part: you can also omit My.Forms.. In other words, whenever you write just FormName and from the context it’s unambiguous that you need an instance rather than the class name, VB will act as though you’d written My.Forms.<FormName>.
Luckily, this only works for forms, not for any other classes. VB creates each default instance when you first access it. So as long as you don’t access a default instance, it’s not created. Once you access it for the first time, VB creates it and invokes its constructor.
When you declare a variable of type interface you can work with any object that implements the interface. Therefore when setting a variable that is of an interface type equal to a class that implements the interface an implicit cast is done. For example.
Dim oExample as IExample
dim testForm as MyTestForm
oExample = MyTestForm
Now, this is the way that you do it, you can do an explicit cast this way
Dim oExample as IExample
Dim testForm as MyTestForm
oExample = CType(MyTestForm, IExample)
For your specific example with VB.NET and an un-instantiated form this is due to a VB "feature" that auto-creates an instance of the form.