C# Creating and Managing Classes (Continued, VAT Calculator)

[This tutorial continues from a previous tutorial, C# Creating Classes ]

VAT Application (Calculator)

Comment out the above code that was written. Now we are going to make a VAT program just as we did in the methods tutorial, however it will be able to do three (3) things:

  • Calculate total product cost after VAT has been added.
  • Calculate the VAT to be paid
  • Calculate amount of VAT paid and find the original product cost

In solution explorer, right click on classes and create a new class file, and name it VAT. You will get the standard mark up. First, to calculate the VAT we can do (VAT rate + 100) / 100, and then multiply that by the product cost.

Method 1

public double totalCost(double pCost, double cRate)
{
 double CR = (cRate + 100) / 100;
 return pCost * CR;
}

Here we have two parameters, pCost and cRate (Product Cost, and Current VAT Rate). Now make a local variable CR and set it to get the percentage multiplier, and then return pCost multiplied CR (percentage multiplier). For example if you entered 20, the percentage multiplier will be 1.2, as 100+20 = 120 then 120 / 100 = 1.2

Method 2

For the second method we are going to find the amount of VAT the user is going to pay. We can do this by first working out the total cost of the product including VAT, and then we can subtract the new cost from the old cost. Insert this code below the previous method:

public double vatAmount(double pCost, double cRate)
{
double vA = (cRate + 100) / 100;
double tCost = pCost * vA;
double result = tCost - pCost;
return result;
}

The first two lines are the same as in the previous method, but the third line result differs. Here we are subtracting the new cost (tcost = total cost) from the original cost (excluding VAT).

Method 3

For the final calculation we are going to work out the amount of VAT paid and the original price when VAT is already included. We can work this out by first getting the percentage multiplier for the current VAT rate (which is 20%, so 1.2), and then divide the product cost by the percentage multiplier. Put this code below the previous method:

public double origPrice(double incVAT, double cRate)
{
double cPrice = (cRate + 100) / 100;
double oPrice = incVAT / cPrice;
return incVAT - oPrice;
}

To find the original cost we use the program.cs file by simply subtracting the productCost from the VAT result.

We have built a new class and the methods, so now we must make it work. Go back to the program.cs file, and below the main method make a new static method called VATApp:

static void VATApp()
{
//Your code here
}

Now since we have three methods it is best to make an If Statement, and then depending on the user input load the correct method in a try catch block. Put this code in VatApp method:

string x = "";
VAT myVAT = new VAT();

Console.WriteLine(@"Press C to calculate total product cost including VAT, Or press R to calculate VAT amount, Or
press A to calculate original cost and VAT amount after VAT has been added.");

x = Console.ReadLine();

First we create a variable named x, which will get the user input and load the correct method, and then we create the myVAT variable and initialize it. Next we print out to the console asking the user to press certain keys depending on the calculation they want to do. We then read the result. Now here is the first part of the If Statement:

1:

 if (x == "c")
        {
         try
        {
         Console.WriteLine("Enter product cost (ex VAT): ");
         string pC = Console.ReadLine();

         Console.WriteLine("Now enter current VAT rate: ");
         string cR = Console.ReadLine();

         var result = myVAT.totalCost(Convert.ToDouble(pC), Convert.ToDouble(cR));
         Console.WriteLine("Total cost is {0:C}", result);
         }
         catch (Exception ex)
         {
         Console.WriteLine(ex.Message.ToString());
         }
       }

If the user hits C then this If Statement will load; this one loads the method totalCost and calculates the total product cost when VAT has been added. It is very similar to the first statement created. If you print out to the console and read the values, the only difference is that we are using a try catch block. Below that add the second part of the If Statement:

2:

 else if (x == "r")
             {
               try
             {
             Console.WriteLine("Enter product cost (ex VAT): ");
             string pC = Console.ReadLine();


             Console.WriteLine("Now enter current VAT rate: ");
             string cR = Console.ReadLine();


             var result = myVAT.vatAmount(Convert.ToDouble(pC), Convert.ToDouble(cR));


             Console.WriteLine("The VAT amount you are paying is {0:C}", result);
             Console.WriteLine("The total cost is {0:C}", result + Convert.ToDouble(pC));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message.ToString());
                }
            }

This is the same as above, so remember to convert the strings to double and {0:C} prints out the result with the currency symbol. Now you will get two results. First you get the VAT amount you are paying:

Console.WriteLine("The VAT amount you are paying is {0:C}", result);

It also calculates the full cost by adding the VAT to the original cost the user enters, which is stored in string PC:

Console.WriteLine("The total cost is {0:C}", result + Convert.ToDouble(pC));

Copy the last If Statement which will go below the previous one:

3:

else if (x == "a")
            {
            try
            {

            Console.WriteLine("Enter product cost (inc VAT): ");
            string pC = Console.ReadLine();


            Console.WriteLine("Now enter current VAT rate: ");
            string cR = Console.ReadLine();


            var result = myVAT.origPrice(Convert.ToDouble(pC), Convert.ToDouble(cR));


            Console.WriteLine("The VAT amount you are paying is {0:C}", result);
            Console.WriteLine("The orignal price without VAT is {0:C}", Convert.ToDouble(pC) - result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message.ToString());
                }
            }
            Console.ReadLine();
        }

This is the same as above, however this time the user enters the product cost including VAT, and then the VAT rate is calculated and printed out. It also gives you the original cost before VAT:

Console.WriteLine("The orignal price without VAT is {0:C}", Convert.ToDouble(pC) - result);

You simply take away the user-entered input (product price including VAT) and subtract it from the result, which has the VAT rate.

The application won't run yet because it is in a different method, so go back to the main method (static void main) and copy:

 string a = "a";
 while (a == "a")
    {
    VATApp();
    }

This is a simple While Statement which will always be true. Once you have done your calculation the program won't close, it will loop itself. This way if you want to work out a few calculations, it is not necessary to start the application again. Hit F5 to debug and run the application.

To keep things brief we used variables that were quite similar, however they did not conflict because they are local to the If Statements and methods. It is best to give variables a unique name so they do not become confusing in the future.

Summary

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