Vector Class

Line: Object Line
Easy Object Orientation Learning Outcome One Learning Outcome Two Learning Outcome Three Walkthrough
Type: Walkthrough
You should have completed: Data Copier This topic leads to: Absolute Zero

Summary

This task will push the Class/Object definiton and relantionship slightly further than the previous exercise. You will create a new Class and create several objects based on it that interact with one another.

Task

  1. Create a new C# Console project in Visual Studio.
  2. Right click the Project name found in the Solution Explorer on the right hand side of Visual Studio, select 'Add', select 'New item...' and finally select 'Class' from the list. Give it the name 'VectorClass.cs' and click 'Add'.
  3. Write code in 'VectorClass.cs' necessary to create a new Class called VectorClass, with two public properties: 'x' and 'y'. Use either approach from the 'Data Copier' exercise as you see fit.
  4. In 'Program.cs', write code for the creation of two Objects based on the 'VectorClass' Class. Assign some values to each Class' 'x' and 'y' properties. Test them out by displaying them all on the Console.
  5. Now follow the code below to add what is called a Constructor method to your 'VectorClass'. The Constructor method allows you to perform some initialisation tasks on your new Object. Typically, you would assign some values to some of the Object's properties so they are available from the beginning. Your vector class should now look like this:
    code snippet
  6. Modify your Main() method to take advantage of the newly added Constructor and set some initial values for both your Objects' 'x' and 'y' properties. Test them out.
  7. Add a new method to your 'VectorClass' Class that returns the sum of its 'x' and 'y' properties. Test it out. Your Vector Class should now look like this:
    code snippet
    Your Main Class should look like this:
    code snippet

Questions

  1. How would you modify your Vector Class to also allow assigning the same value to both 'x' and 'y' properties using a Constructor? Hint: look at Method Overloading, this also works for Contructors.
  2. How would you modify your Vector Class to also have the ability (Method or Property) of returning the result of multiplying the values of its two properties, 'x' and 'y'? Test this out in Main().
  3. Can you modifiy this class to be able to perform the calculations of the dot product and cross product operations? You may need to look these up.