Thread: Classes in VB.NET |
In this tutorial I'm going to learn you how to create your own classes, both from scratch and with another class as the base.
A Basic Class
First we just create a class, you can write it at the bottom in the other codes or just add a new class item for it.
My class is here called CTutorialClass.Code:Public Class CTutorialClass End Class
Now we add some content in the class:
I just declared a private string. This string can only be accessed from the class itself. And then I also added a public sub called PrintMessage which just show the text in our string in a messagebox.Code:Public Class CTutorialClass Private Message As String = "Hello CodeCall!" Public Sub PrintMessage() MessageBox.Show(Message) End Sub End Class
Now if we go back to our other section of code(the one we want to use the class in).
When we starts writing our class is in the list of proposed items:
We continue to write to get this:
Code:Private Sub frmTutorial_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim CMyInstance As New CTutorialClass CMyInstance.PrintMessage() End Sub
This will create a new instance of our class and then call the PrintMessage sub which will show a messagebox with our message. It will look like this:
This was just a simple class and isn't useful in any way, but more advanced classes will be.
A Class with properties
We're going to continue with our last class, but now we'll add a property.
If we change this a little:Code:Public Class CTutorialClass Private Message As String = "Hello CodeCall!" Private Caption As String Public Sub PrintMessage() MessageBox.Show(Message, Caption) End Sub Public Property Title() As String Get Return Caption End Get Set(ByVal Title As String) Caption = Title End Set End Property End Class
to this:Code:Dim CMyInstance As New CTutorialClass CMyInstance.PrintMessage()
We'll set the Title to CC. This will give our messagebox the caption "CC".Code:Dim CMyInstance As New CTutorialClass CMyInstance.Title = "CC" CMyInstance.PrintMessage()
We can also use it the other way to Get the caption:
Code:Dim Caption as String = CMyInstance.Title
Observe that when we get/set our property we doesn't only need to return/set a variable straight of. We can do like this:
If you only want the user to be able to get the property's value or only allow the user to change it you can create a readonly property or a writeonly property like this:Code:Public Property Title() As String Get Return Caption & "!!!" End Get Set(ByVal Title As String) Caption = Title If Title = "CC" Then MessageBox.Show("Nice Caption!!!") End If End Set End Property
Code:Public ReadOnly Property Title() As String Get Return Caption & "!!!" End Get End PropertyCode:Public WriteOnly Property Title() As String Set(ByVal Title As String) Caption = Title If Title = "CC" Then MessageBox.Show("Nice Caption!!!") End If End Set End Property
After adding a property to the class it's proposed in the list like this:
More alternatives when calling subs
When calling subs/functions of built in classes you often have many alternatives of which variables to use:
This is easily done in the same way you're making normal subs with different alternatives. Don't worry I will explain how:
We'll add 2 subs with the same name:
Code:Public Class CTutorialClass Public Sub moveMouse(ByVal P As Point) Cursor.Position = P End Sub Public Sub moveMouse(ByVal X As Integer, ByVal Y As Integer) Cursor.Position = New Point(X, Y) End Sub End Class
But one has the variable Point while the other one has 2 integer variables. Remember they must have different or it won't work.
So now the user have the option to enter the position he/she wants to move the mouse to(as this example shows) in either a point or in a X and an Y value .
Now it looks like this if we try to call our sub:
Creating and using events
We add an event to our class and then a sub which only calls that event:
So when we later will call the sub the program will raise the event, more to that soon.Code:Public Class CTutorialClass Public Sub raiseOurEvent() RaiseEvent ourEvent(Me, New EventArgs()) End Sub Public Event ourEvent(ByVal sender As Object, ByVal e As EventArgs) End Class
Now we use this code to try our event:
Code:Private Sub frmTutorial_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim CMyInstance As New CTutorialClass AddHandler CMyInstance.ourEvent, AddressOf eventRaised CMyInstance.raiseOurEvent() End Sub Private Sub eventRaised(ByVal sender As Object, ByVal e As EventArgs) MessageBox.Show("Event Raised") End Sub
This will, when our program loads, create a new instance of our class. Then it will add a handler to eventRaised sub from our event.
Then we call our sub which will raise the event which will in its turn make the eventRaised sub to go off which will show the messagebox.
Build a class with another one as base
In this example I will create 2 classes, one which will be the base and the other one that uses the base class as its base.
Here's our base class:
Doesn't contains much actually, but it's just some examples after all.Code:Public Class CTutorialClassBase Public Variable1 As Integer Public Variable2 As String Public Variable3 As Char Public Function ReturnCC() Return "CC" End Function End Class
And the other class:
Code:Public Class CTutorialClass Inherits CTutorialClassBase Public Variable4 as Double Public Variable5 as Short End Class
Now we have Inherited everything from our base class into our other class.
Now we can access the things from our base class from inside the other class:
Or from our instance of the other class:
Make your class easier to use
Now the main functions of the class is done but we want to make it easier to use, it's hard to know what everything does.
Here I've created a class to show how to add "instructions":
Code:''' <summary> ''' A class with the purpose on helping people ''' </summary> ''' <remarks>This class is made for Vswe's tutorial about classes, ''' it doesn't really have any good functions.</remarks> Public Class CTutorialClass ''' <summary> ''' The shoesize number. ''' </summary> ''' <remarks>Holding the double value of the shoe's size</remarks> Public ShoeSize As Double ''' <summary> ''' The walking speed, used to calculate the time of walks. ''' </summary> ''' <remarks>This constant is used to calculate the the time it takes to walk a certain amount of meters. ''' Use CalculateTime to calculate the time it takes.</remarks> Public Const WalkSpeed As Short = 7 ''' <summary> ''' Calculate the time it takes to walk a special lenght ''' </summary> ''' <param name="meters">The amount of meters to walk</param> ''' <returns>Returns the time it takes in seconds</returns> ''' <remarks>Calculates the time it takes to walk by using the meter input and the walkingspeed constant</remarks> Public Function CalculateTime(ByVal meters As Integer) Dim Time As Integer 'calculation goes here Return Time End Function ''' <summary> ''' Calculate the time it takes to walk a special lenght, also check if you got ''' any good shoes ''' </summary> ''' <param name="meters">The amount of meters to walk</param> ''' <param name="Shoes">The biggest shoesize avalible</param> ''' <returns>Returns the time it takes in seconds</returns> ''' <remarks>Calculates the time it takes to walk by using the meter input and the walkingspeed constant</remarks> Public Function CalculateTime(ByVal meters As Integer, ByVal Shoes As Double) Dim Time As Integer If ShoeSize > Shoes Then MessageBox.Show("You don't have any shoes that fits") Else 'calculation goes here End If Return Time End Function End Class
The four I used, It exists a lot more:
- Summery - A short info about the "thing"
- Remarks - A longer description
- Param - Info about a parameter, here you need to write the name of it
- Return - Info about the returning value.
Here I show some examples on how it will look like with these informations:
This was the tutorialHope you have learned anything because it took me 3 hours to write.
Have a good time Codeing
/Vswe
Very cool tutorial! Classes are very important in VB! I like the last section where you showed proper function documentation. Nice work! +rep
There are currently 1 users browsing this thread. (0 members and 1 guests)