/// <summary> /// Convert from one Measurement to another. This takes care of finding /// a ConvertProc out of the converters dictionary and applies it; throws /// an Exception if the (incoming.BaseUnit -> outgoingUnits) converter /// function cannot be found. /// </summary> /// <param name="from">The Measurement to convert</param> /// <param name="to">The units of measure to convert to</param> /// <returns>Converted Measurement</returns> public static IMeasurement Convert(IMeasurement from, string to) { // Identity transformation always works. We do handle // differences in exponent if (_SIUnits.BaseUnit(to) == from.BaseUnit) { if (_SIUnits.Exponent(to) == from.Exponent) { return(from); } var toExp = _SIUnits.Exponent(to); var expDiff = from.Exponent - toExp; return(new Measurement(from.Quantity * (decimal)Math.Pow(10, expDiff), toExp, _SIUnits.BaseUnit(to))); } // Can we find a converter for these two units? Use TryGetValue() // to avoid the KeyNotFoundException that gets thrown using the // traditional [] lookup--we want to throw our own exception. // ConvertProc converter = null; if (converters.TryGetValue(new Tuple <string, string>(from.BaseUnit, to), out converter)) { return(converter(from)); } // I dunno what the hell you're trying to convert // throw new Exception( String.Format( "Unrecognized Measurement conversion: {0} to {1}", from.BaseUnit, to)); }