r/visualbasic • u/Bonejob VB Guru • Nov 28 '14
Understanding Classes
I received a PM last night from a student struggling to understand classes, constructors an de-constructors.
Lets start with an analogy;
Class = Blueprint
Object = Item created from BlueprintClasses are a set of instructions that define what the object has for functions, properties and procedures. Instantiating and object makes a valid usable object from the class.
Lets make a basic class
Public Class House
Public Property colour As String
Public Property streetNumber As Integer
Public Function CheckStreet(street As Integer) As Boolean
If street = StreetNumber Then
Return True
Else
Return False
End If
End Function
End ClassThis class has a couple of properties describing the house, and a function that returns true or false when provided a street. Here is how you would create and instance of the class (Instantiate) that you could use.
Dim firstHouse As New House
OR
Dim secondHouse As House
secondHouse = New HouseYou man notice this class has no Sub New (The constructor) in it. This is because the VB compiler checks for the presence of a constructor in the class when it compiles. If none is found, it automatically adds a no-argument constructor.
Lets add a constructor to the above code
Public Sub New
End SubThat's it, you can use this sub to do many things, like set values of properties, load objects with datasets, pass objects to the class that it might need.
Passing values into a constructor is done similarly to a standard sub. This is called parametrized construction
Public Sub New(_Colour as string,_Street as Integer)
colour = _colour
streetNumber = _Street
End SubTo implement this class;
Dim newHouse as new House("red",35)
debug.print(newHouse.CheckStreet(35))in your debug you will find TRUE if you were to run this class.
Deconstruction is the process of implementing IDisposable using a Dispose sub to recover used resources. The only time I ever recover my own resources is when I am dealing with massive paged datasets.
Here is the MSDN article. I don't usually bother disposing of my own resources for the .Net garbage collector deals with it. My old University professors is probably hunting me down as we speak for saying this :)
I hope this covers this a bit more clearly, if people want I can come up with more info about Inheritance.
Bone
2
u/PostalElf VB.Net Intermediate Dec 01 '14
To add onto this excellent post: yes, you can stack objects in objects! The easiest way to do this would be to simply declare a new custom class as a property of your class, like so:
Where xyCoordinates is a custom class that looks like this: