Overloading an explicit casting operator from fraction to double - CSharp Custom Type

CSharp examples for Custom Type:Operator Overloading

Description

Overloading an explicit casting operator from fraction to double

Demo Code

using System;/*from ww  w .j  ava 2  s. c  o  m*/
public class Fraction {
   //data members
   private int   m_numerator;
   private int   m_denominator;
   //Properties
   public int Numerator {
      get { return m_numerator; }
      set { m_numerator = value; }
   }
   public int Denominator {
      get { return m_denominator; }
      set { m_denominator = value; }
   }
   //Constructors
   public Fraction( ) { m_numerator = 0; m_denominator = 0; }
   public Fraction( int iNumerator, int iDenominator ) {
      m_numerator = iNumerator;
      m_denominator = iDenominator;
   }
   //Arithmetic operators +,-,/,*
   public static Fraction operator+(Fraction f1, Fraction f2) {
      Fraction Result = new Fraction( );

      if( f1.Denominator != f2.Denominator ) {
         Result.Denominator = f1.Denominator * f2.Denominator;
         Result.Numerator   = (f1.Numerator * f2.Denominator) + (f2.Numerator * f1.Denominator);
      } else {
         Result.Denominator = f1.Denominator;
         Result.Numerator  = f1.Numerator + f2.Numerator;
      }
      return Result;
   }
   public static Fraction operator-(Fraction f1, Fraction f2) {
      Fraction Result = new Fraction( );

      if( f1.Denominator != f2.Denominator ) {
         Result.Denominator = f1.Denominator * f2.Denominator;
         Result.Numerator   = (f1.Numerator * f2.Denominator) - (f2.Numerator * f1.Denominator);
      } else {
         Result.Denominator = f1.Denominator;
         Result.Numerator   = f1.Numerator - f2.Numerator;
      }
      return Result;
   }
   //add an explicit casting operator from fraction to double
   public static explicit operator double(Fraction f) {
      double dResult = ((double)f.Numerator / (double)f.Denominator);
      return dResult;
   }
   public static bool operator==(Fraction f1, Fraction f2) {
      //TODO: Implement comparison of f1 to f2
      return true;
   }
   public static bool operator!=(Fraction f1, Fraction f2) {
      return !(f1 == f2);
   }
}
public class OperatorTest {
   public static void Main( ) {
      Fraction f1 = new Fraction( 1, 5 );
      Fraction f2 = new Fraction( 2, 5 );

      Fraction f3 = f1 + f2;

      Console.WriteLine("f1 + f2 = {0}/{1}", f3.Numerator, f3.Denominator );

      f3 = f3 - f2;
      Console.WriteLine("f3 - f2 = {0}/{1}", f3.Numerator, f3.Denominator );

      Console.WriteLine("f3 as a double = {0}", (double)f3);
   }
}

Related Tutorials