Visual Basic Creating and Managing Classes

In previous tutorials you worked with classes: Console is a system class and WriteLine is one of its methods. You can make your own classes, which is useful for code re-use. Classes simply contain methods or events. In the example below, we will create a simple application which calculates VAT. It will be able to perform three calculations.

Syntax

Public Class <classname>

Your methods here.

End Class

Create a new Visual Basic Console Application and name it Classes. In solution explorer, right click on classes and make a new class file. Name it Car.vb (See image below):

Solution Explorer - Visual Basic Creating Classes

Next we are going to create some methods. Copy the code below:

Public Function manufacturer(vmanufacturer As String)
 Return vmanufacturer
End Function

Public Function model(vModel As String)
 Return vModel
End Function

Public Function colour(vcolour As String)
 Return vcolour
End Function

Here we have made several methods and are simply returning the parameter. In the Module.vb file, add:

Dim myCar As New Car()

Console.WriteLine("Please enter your car manufacturer: ")
Dim m As String = myCar.manufacturer(Console.ReadLine())

Console.WriteLine("Please enter car model :")
Dim mo As String = myCar.model(Console.ReadLine())

Console.WriteLine("Please enter car colour")
Dim c As String = myCar.colour(Console.ReadLine())

Console.WriteLine("You car details: " & vbLf & " " & m & " " & vbLf & " " & mo & vbLf & " " & c)
Console.ReadLine()

This class is quite simple: First we create the variable myCar and then initialize it. Then we print to the console and read the user’s results, as in previous tutorials. Finally, we print out the details the user entered. When you type myCar. you will get the list of methods this class has.

Public vs Private

In the above example we used a public function, which allows this method to be accessed both inside outside the current class. If we change this to a private function, the method will be accessible only from inside the current class.

VAT Application (Calculator)

The above example is simple and has very little code; in the next example we will make a VAT application which will perform 3 tasks:

  • Calculate total product cost including VAT
  • Calculate the VAT to be paid
  • Calculate the amount of VAT paid when the product already has VAT added

Comment out the previous code you have written, and then make a new class file and name it VAT.vb. We will write three methods:

Method 1

Public Function totalProductCost(ByVal pCost As Double, ByVal cRate As Double)

Dim CR As Double = (cRate + 100) / 100
Return pCost * CR

End Function

This method calculates the total product cost when VAT is added. To calculate the VAT we use the percentage multiplier, so the current VAT rate is 20%:

  1. 100 + 20 = 120
  2. 120 / 100 = 1.2
  3. <product cost> * 1.2 = answer

We have a variable called CR which calculates the percentage multiplier, and we then return pCost * CR (ProductCost * CurrentRate). We also have two parameters, pCost and cRate, which are used to make the calculation when we ask the user for the product cost and VAT rate.

Method 2

This time we will calculate the VAT amount which is being paid.

Public Function CalculateVAT(ByVal productCost As Double, ByVal currentRate As Double)

Dim CR As Double = (currentRate + 100) / 100
Dim totalCost = productCost * CR
Return totalCost - productCost

End Function

This method is similar to the previous one, except we return the totalCost (VAT has been added) subtracted from productCost (original amount ex VAT). This produces the VAT amount paid.

Method 3

Public Function origPrice(ByVal itemCost As Double, ByVal vatRate As Double)

Dim cRate = (vatRate + 100) / 100
Dim oPrice = itemCost / cRate
Return itemCost - oPrice

End Function

The last method finds the amount of VAT paid when VAT is already included in the price. First we get the percentage multiplier, and then we divide the product cost by the percentage multiplier. Then we simply subtract itemcost from original price.

Now that we have written the methods it is time to call them. Return to Module.vb and add the following below the Sub Main method:

Sub VATApp()

End Sub

Inside this method we will write our code, and we will use an If Statement to determine the function the user has chosen. There are 3 functions in our application. Copy this:

Dim f As String = Nothing
Dim myVAT As New VAT 

Console.WriteLine("PRESS C TO CALCULATE TOTAL PRODUCT COST INC VAT, PRESS R TO CALCULATE VAT AMOUNT PAID, PRESS A TO CALCULATE ORIGINAL PRICE")
f = Console.ReadLine()

Here we have a variable called f which is nothing. Next we initialize our variable myVAT and create a new object; when you use a new keyword you are creating an object. We then print to the console and read the line. Here is the first part of the If Statement:

1:

The first function will calculate the total product cost including VAT

If (f = "c") Then

 Console.WriteLine("Please Enter Product Cost (EX VAT): ")
 Dim pCost As String = Console.ReadLine()

 Console.WriteLine("Enter Current VAT Rate: ")
 Dim CRate As String = Console.ReadLine()

 Dim result As Double = myVAT.totalProductCost(Convert.ToDouble(pCost), Convert.ToDouble(CRate))
 Console.WriteLine("The total cost is: {0:C} ", result)

This is similar to our previous tutorials. First we get the user’s input and read the value. Then we have a variable called result which is data type double. Here we call our class myVAT. When you type myVAT. you will get a list of methods available to the class, and when you insert the brackets  you will get a tool-tip showing you the arguments this method takes. The method cannot take 0 arguments! In the arguments we convert the strings to double. Then we print out the result; the {0:C} gives the result a currency symbol.

2:

Below that If Statement is the second part, which calculates the VAT amount you are going to pay.

ElseIf (f = "r") Then

  Console.WriteLine("Please Enter Product Cost (EX VAT): ")
  Dim productCost As String = Console.ReadLine()

  Console.WriteLine("Please Enter VAT Rate: ")
  Dim CurrentRate As String = Console.ReadLine()

  Dim VATPaid As Double = myVAT.CalculateVAT(Convert.ToDouble(productCost), Convert.ToDouble(CurrentRate))
  Console.WriteLine("VAT being paid: {0:C} ", VATPaid)

  Console.WriteLine("Total cost is: {0:C} ", Convert.ToDouble(productCost) + Convert.ToDouble(VATPaid))

This is similar to the above method, as it performs the same calculation. However, it produces the VAT amount being paid, and the last line is the total cost.

3:

The final method will rpoduce the VAT amount paid when VAT is already included.

Else
  If (f = "a") Then

   Console.WriteLine("Please Enter Product Cost (INC VAT): ")
   Dim totalCost As String = Console.ReadLine()

   Console.WriteLine("Please Enter VAT Rate: ")
   Dim vatR = Console.ReadLine()


   Dim total As Double = myVAT.origPrice(Convert.ToDouble(totalCost), Convert.ToDouble(vatR))
   Console.WriteLine("VAT Added: {0:C} ", total)

   Console.WriteLine("Original Price: {0:C} ", Convert.ToDouble(totalCost) - Convert.ToDouble(total))
   End If

   End If

   Console.ReadLine()

This will find the VAT amount paid as well as the original cost. This program will not run yet, so in Sub Main you need to put:

  Dim x As Integer = 3

        While x = 3
            Try
                VATApp()
            Catch ex As Exception
                Console.WriteLine(ex.Message.ToString())
            End Try
        End While

        Console.ReadLine()

This is a simple While Statement which calls our method VATApp. It is in a While Statement because it will keep looping, so once you finish your calculation you can do another.

Summary

  • We started with the class keyword
  • A private method is available inside the current class and a public method is available both inside and outside
  • When you use a new keyword you are making a new object
  • Remember to initialize the class variable