Fractions

Line: Object Line
Medium Difficulty Object Orientation Learning Outcome One Learning Outcome Two Learning Outcome Three Exercise
Type: Exercise
You should have completed: Absolute Zero This topic leads to: Bank Account

Summary

In this exercise you will practice handling mathematical fractions and the dangers that come with them, along with more Classes and Objects. You will make use of the 'try'/'catch' statements to prevent your program from experiencing sudden death.

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 'FractionClass.cs' and click 'Add'.
  3. Add code to your 'FractionClass' Class to work with a Numerator and Divisor, along with a parameterised Constructor method that allows the creation of Objects by using the syntax:
    FractionClass f = new FractionClass (34, 3)
    Hint: Make use of the integer data type.
  4. Further enhance the 'FractionClass' Class with a read-only property called 'Result' that, by default, calculates and returns the result of the division operation:
    Numerator / Divisor
  5. Add code to your 'Main()' Method that will create a new 'FractionClass' object and set the Divisor property to 0. Print the 'Result' property to che Console screen. Test out your code. This should crash your program with a Divide by Zero Exception.
  6. Enhance your 'Main()' Method with a 'try'/'catch' to stop the program from carshing, but instead print out the Exception message.
  7. Enhance the 'set' part of the 'Divisor' property to throw a new 'ArgumentException' Exception.
  8. Further enhance your 'Main()' Method to prevent the program from crashing from your latest modification (handle the 'ArgumentException' Exception). Test out your program to prove the Exception is thrown and handled correctly.

Questions

  1. What would be the easiest way of making the 'FractionClass' constructor also perform this (Task 8.) check?
    Hint: It's not a simple copy & paste solution.
  2. How would you change the 'FractionClass' to work with Floats instead of Integers? Note the different behaviour.