December 18, 2014
Hot Topics:

Implementing a Decimal-to-Fraction Class with Operator Overloading

  • August 15, 2007
  • By Paul Kimmel
  • Send Email »
  • More Articles »

If you implement a conversion operator—CType, as I did to support cross type arithmetic—you have to specify whether the conversion is widening or narrowing. In the Fraction class above, you can perform operations on doubles and Fractions, as shown in Listing 2, a simple test console application.

Listing 2: A console application to test the Fraction class.

Module Module1

   Sub Main()
      While (True)
         Console.WriteLine("Enter a decimal number (q=quit)"
         Dim value As String = Console.ReadLine()
         If (value = "q") Then Return

         Dim fraction As Fraction = New Fraction(value)
         Console.WriteLine("{0} is equivalent to {1}", _
            fraction.Number, fraction.ToString())

         Console.WriteLine("Test: {0}={1} is {2}", _
                           fraction, 0.25, fraction = 0.25)
         Console.WriteLine("Test: {0}*{1} is {2}", fraction, 0.5, _
                           fraction * 0.5)
      End While

   End Sub

End Module

Step through the code to see that operations like fraction * 0.5 actually calls the CType conversion operator, the constructor, and the operator* method.

Finally, the StringBuilder class is used to display the properly formatted fraction.

Summary

Calculating fractions is an opportunity to explore some interesting elements of the .NET framework. While you are parsing the sign, storing the whole number, and calculating the fraction, you can use Regular Expressions, Math class methods, the Euclidean algorithm, and experiment with operator overloading.

Enjoy.

About the Author

Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his new book UML DeMystified from McGraw-Hill/Osborne. Paul is a software architect for Tri-State Hospital Supply Corporation. You may contact him for technology questions at pkimmel@softconcepts.com.

If you are interested in joining or sponsoring a .NET Users Group, check out www.glugnet.org. Glugnet is opening a users group branch in Flint, Michigan in August 2007. If you are interested in attending, check out the www.glugnet.org web site for updates.

Copyright © 2007. All Rights Reserved.
By Paul Kimmel. pkimmel@softconcepts.com





Page 4 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel