Operator overloading + (plus) , - (minus) - CSharp Custom Type

CSharp examples for Custom Type:Operator Overloading

Description

Operator overloading + (plus) , - (minus)

Demo Code

using System;/*from   w w  w. j a  v  a 2 s  .c  o  m*/
public class Fraction {

   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( );
      //In order to add fractions, the denominators need to be the same
      //the fastest way is to multiply them together and adjust the numerators
      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( );
      //In order to subtract fractions, the denominators need to be the same
      //the fastest way is to multiply them together and adjust the numerators
      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 class OperatorTest {
   public static void Main( ) {
      Fraction f1 = new Fraction( 1, 5 );
      Fraction f2 = new Fraction( 2, 5 );
      //Add the Fractions
      Fraction f3 = f1 + f2;
      //Display the result
      Console.WriteLine("f1 + f2 = {0}/{1}", f3.Numerator, f3.Denominator );
      //Substract f2 from f3 should get f1
      f3 = f3 - f2;
      Console.WriteLine("f3 - f2 = {0}/{1}", f3.Numerator, f3.Denominator );
   }
}

Result


Related Tutorials