Jump to content

Classes in VB.NET

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
Vswe

Vswe

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 9,552 posts
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.

Public Class CTutorialClass


End Class

My class is here called CTutorialClass.





Now we add some content in the class:


Public Class CTutorialClass


    Private Message As String = "Hello CodeCall!"


    Public Sub PrintMessage()

        MessageBox.Show(Message)

    End Sub


End 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.



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:


Posted Image


We continue to write to get this:


    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:


Posted Image

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.

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

If we change this a little:

        Dim CMyInstance As New CTutorialClass

        CMyInstance.PrintMessage()

to this:

        Dim CMyInstance As New CTutorialClass

        CMyInstance.Title = "CC"

        CMyInstance.PrintMessage()

We'll set the Title to CC. This will give our messagebox the caption "CC".

We can also use it the other way to Get the caption:
        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:

    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

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:

    Public ReadOnly Property Title() As String

        Get

            Return Caption & "!!!"

        End Get

    End Property

    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:

Posted Image







More alternatives when calling subs

When calling subs/functions of built in classes you often have many alternatives of which variables to use:

Posted Image


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:

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:


Posted Image







Creating and using events


We add an event to our class and then a sub which only calls that event:

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

So when we later will call the sub the program will raise the event, more to that soon.

Now we use this code to try our event:

    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:

Public Class CTutorialClassBase


    Public Variable1 As Integer

    Public Variable2 As String

    Public Variable3 As Char



    Public Function ReturnCC()

        Return "CC"

    End Function


End Class

Doesn't contains much actually, but it's just some examples after all.



And the other class:


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:


Posted Image


Or from our instance of the other class:

Posted Image










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":


''' <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:


Posted Image



Posted Image



Posted Image



http://i150.photobuc.../Vswe/Info4.jpg



http://i150.photobuc.../Vswe/Info5.jpg



http://i150.photobuc.../Vswe/Info6.jpg




This was the tutorial :) Hope you have learned anything because it took me 3 hours to write. :)

Have a good time Codeing :D
/Vswe

#2
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Very cool tutorial! Classes are very important in VB! I like the last section where you showed proper function documentation. Nice work! +rep