A Quantity class with units

Posted by Ryan Ohs on Geeks with Blogs See other posts from Geeks with Blogs or by Ryan Ohs
Published on Mon, 17 May 2010 18:10:53 GMT Indexed on 2010/05/18 1:32 UTC
Read the original article Hit count: 419

Filed under:

Goals

  • Create a class that associates a numeric quantity with a unit of measurement.
  • Provide support for simple arithmetic and comparison operations.

Implementation

  • An immutable class (Could have been struct but I may try inheritance later)
  • Unit is stored in an enumeration
  • Supported operations:
  • Addition w/ like units
  • Subtraction w/ like units
  • Multiplication by scalar
  • Division by scalar
  • Modulus by scalar
  • Equals()
  • >, >=, <, <=, ==
  • IComparable
  • ToString()
  • Implicit cast to Decimal

The Source

The souce can be downloaded from Github.

Notes

  • This class does not support any arithmetic that would modify the unit.
  • This class is not suitable for manipulating currencies.

Future Ideas

  • Have a CompositeQuantity class that would allow quantities with unlike units to be combined.
  • Similar currency class with support for allocations/distributions.
  • Provide conversion between units. (Actually I think this would be best placed in an external service. Many situations I deal with require some sort of dynamic conversion ratio.)

© Geeks with Blogs or respective owner