Whats the difference between these two initialization methods for a class member in VB.Net? - 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.

Related

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

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

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.

Can the initialization order of class fields in VB.NET be influenced by references to other fields?

Take this sample code:
Class Foo
ReadOnly name As String
Public Sub New(name As String, dependentUpon As Foo)
Me.name = name
Console.Write("{0} created. ", name)
Console.WriteLine("Dependent upon {0}.", If(dependentUpon IsNot Nothing,
dependentUpon.Name,
"nothing"))
End Sub
End Class
Class Bar
ReadOnly dependent As New Foo("Dependent", independent) ' <-- !!!
ReadOnly independent As New Foo("Independent", Nothing)
End Class
The output of New Bar() is:
Dependent created. Dependent upon nothing.
Independent created. Dependent upon nothing.
It seems fields are initialized in the same order as they appear in the source code, which (a) leads to an unexpected result, and (b) seems a little puzzling, given that one is normally not permitted to read from uninitialized variables in .NET, yet that seems to be working fine above.
I would've expected VB.NET to be smart enough to initialize referenced fields first, and only then those that reference it; i.e. I'd have liked to see this output instead:
Independent created. Dependent upon nothing.
Dependent created. Dependent upon Independent.
Does someone know a way how to get VB.NET to behave like that instead, without simply having to swap the declaration order of dependent and independent inside class Bar?
Fields are always initialized in the order they're declared.
The restriction against accessing uninitialized variables applies only to local variables, not fields. (that would be too hard to enforce)

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.

Vb.Net scoping question - private fields

I have been looking at a class that has a method that accepts a parameter that is of the same type of the class containing the method.
Public Class test
private _avalue as integer
Public Sub CopyFrom(ByVal from as test)
_avalue = from._avalue
End Sub
End Class
When used in code
a.CopyFrom(b)
It appears that instance "a" has visibility to the private members of the passed in instance "b" and the line
_avalue = from._avalue
runs without error copying the private field from one object instance to the other.
Does anyone know if this is by design. I was under the impression that a private field was only accessible by the instance of the object.
The private scope is related to the type not the instance. So yes, this is by design.
The class test has knowledge about the private parts of itself, so it can use those parts also on other instances of the same type.
You are writing something similar to to a copy constructor.
Since the copying method/function is being written inside of the same class, it will have access to private variables of any instance of its own class.