Zebra0.com

csharp objects


Text of video

Code for the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OOPS
{
    class Fraction
    {
        // Member attibutes or proerties
        private int Numerator;
        private int Denominator;

        // Constructor with no parameters
        // Example Fraction myFrac=new Fraction();
        public Fraction()
        {
            Numerator = 0;
            Denominator = 1;
        }

        // Constructor with two integer parameters
        // Example Fraction half=new Fraction(1,2);
        public Fraction(int numerator, int denominator)
        {
            // Any numerator is ok.
            Numerator = numerator;
            // Denominator can never be 0!
            if (denominator != 0) Denominator = denominator;
            else Denominator = 1;
        }

        // Override the ToString method: example 1/2
        public override String ToString()
        {
            return "" + Numerator + "/" + Denominator;
        }
        // Accessors retrieve values from the class, usually named get___, also called getter functions
        public int GetNumerator()
        {
            return Numerator;
        }
        public int GetDenominator()
        {
            return Denominator;
        }
        // Mutators change the values in the class, usually named set___, also called setter functions.
        public void SetNumerator(int numerator)
        {
            Numerator = numerator;
        }
        public void SetDenominator(int denominator)
        {
            // Do not accept a value of zero, anything else is OK.
            if (denominator != 0) Denominator = denominator;
        }
        public double ToDouble()
        {
            // The value of 1/2 is 0 (integer division)
            //  However,  if we case Numerator to double, then 1.0/2 is 0.5
            // We do not need to test for divide by 0 because Denominator is never 0.
            return (double)Numerator / Denominator;
        }
        public static bool operator <(Fraction frac1, Fraction frac2)
        {
            // We can compare a<b whether a and b are int, string, double or Fraction 
            return (frac1.ToDouble() < frac2.ToDouble());
        }
        public static bool operator >(Fraction frac1, Fraction frac2)
        {
            // We can compare a>b whether a and b are int, string, double or Fraction 
            return (frac1.ToDouble() > frac2.ToDouble());
        }
   }
}

Code in form load to test:

private void Form1_Load(object sender, EventArgs e)
{
   Fraction myFrac = new Fraction();
   Fraction half = new Fraction(1, 2);
   myFrac.SetDenominator(3);
   if (myFrac < half) Text = myFrac.ToString() + " < " + half.ToString();
   else Text = myFrac.ToString() + " is not < " + half.ToString();
}

End of lesson, Next lesson: Zebra Notes: Open, Save, Save As, and Format with a Rich Text Box