using System; using System.Text; using System.Runtime.Serialization; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; namespace Raytheon.Units { /// /// This class represents a length. /// /// It has no constructors. Instead, it provides multiple methods for creating objects of this /// type. Those methods are of the form FromXXX, where XXX is a unit (e.g. FromMeters). /// /// Properties (e.g. Meters) are provided to convert the value to other units and return /// as type double. /// /// Methods (operator overloads) are provided to perform calculations with related types (e.g. /// Velocity). /// [Serializable] [DataContract] public class Length { public enum Unit { Meters, Centimeters, Millimeters, Micrometers, Nanometers, Inches, Feet } public static IDictionary> UnitAbbreviations = new Dictionary>() { {Unit.Meters, new List(){ "m" } }, {Unit.Centimeters, new List(){ "cm" } }, {Unit.Millimeters, new List(){ "mm" } }, {Unit.Micrometers, new List(){ "um" } }, {Unit.Nanometers, new List(){ "nm" } }, {Unit.Inches, new List(){ "in" } }, {Unit.Feet, new List(){ "ft" } }, }; private const Unit DefaultUnits = Unit.Meters; private const double FeetPerMeter = 3.280839895013123; private const double InchesPerMeter = 12 * FeetPerMeter; private const double MilesPerMeter = FeetPerMeter / 5280; [DataMember(Name = "Length", IsRequired = true)] private double _length; // meters // map: unit => abbreviation, conversion method and property private static IDictionary> _unitInfo = new Dictionary>() { { Unit.Meters, new UnitInfo(UnitAbbreviations[Unit.Meters], FromMeters, typeof(Length).GetProperty("Meters").GetGetMethod()) }, { Unit.Centimeters, new UnitInfo(UnitAbbreviations[Unit.Centimeters], FromCentimeters, typeof(Length).GetProperty("Centimeters").GetGetMethod()) }, { Unit.Millimeters, new UnitInfo(UnitAbbreviations[Unit.Millimeters], FromMillimeters, typeof(Length).GetProperty("Millimeters").GetGetMethod()) }, { Unit.Micrometers, new UnitInfo(UnitAbbreviations[Unit.Micrometers], FromMicrometers, typeof(Length).GetProperty("Micrometers").GetGetMethod()) }, { Unit.Nanometers, new UnitInfo(UnitAbbreviations[Unit.Nanometers], FromNanometers, typeof(Length).GetProperty("Nanometers").GetGetMethod()) }, { Unit.Feet, new UnitInfo(UnitAbbreviations[Unit.Feet], FromFeet, typeof(Length).GetProperty("Feet").GetGetMethod()) }, { Unit.Inches, new UnitInfo(UnitAbbreviations[Unit.Inches], FromInches, typeof(Length).GetProperty("Inches").GetGetMethod()) } }; /// /// Prevents a default instance of the class from being created. /// Use FromXXX methods to create objects of this type. /// /// No one should be calling this, it is only here to prevent users from creating default object private Length() { throw new InvalidOperationException("No one should be calling this, it is only here to prevent users from creating default object"); } /// /// ctor used by this class to create objects in FromXXX methods /// /// The length - meters private Length(double length) { _length = length; } #region conversion properties public double Centimeters { get { return _length * 100; } } public double Feet { get { return _length * FeetPerMeter; } } public double Inches { get { return _length * InchesPerMeter; } } public double Meters { get { return _length; } } public double Micrometers { get { return _length * 1000000; } } public double Millimeters { get { return _length * 1000; } } public double Nanometers { get { return _length * 1000000000; } } #endregion #region creation methods public static Length FromCentimeters(double centimeters) { return new Length(centimeters / 100); } public static Length FromFeet(double feet) { return new Length(feet / FeetPerMeter); } public static Length FromInches(double inches) { return new Length(inches / InchesPerMeter); } public static Length FromMeters(double meters) { return new Length(meters); } public static Length FromMicrometers(double micrometers) { return new Length(micrometers / 1000000); } public static Length FromMillimeters(double millimeters) { return new Length(millimeters / 1000); } public static Length FromNanometers(double nanometers) { return new Length(nanometers / 1000000000); } #endregion public override bool Equals(object obj) { Length l = obj as Length; return (l == null) ? false : (this._length == l._length); } public override int GetHashCode() { return _length.GetHashCode(); } #region binary operators // not implementing %, &, |, ^, <<, >> public static Length operator +(Length left, Length right) { if (null == left) throw new ArgumentNullException("left", "Cannot add a null Length"); if (null == right) throw new ArgumentNullException("right", "Cannot add null Length"); return new Length(left._length + right._length); } public static Length operator -(Length left, Length right) { if (null == left) throw new ArgumentNullException("left", "Cannot subtract a null Length"); if (null == right) throw new ArgumentNullException("right", "Cannot subtract a null Length"); return new Length(left._length - right._length); } public static Length operator *(Length length, double scalar) { if (null == length) throw new ArgumentNullException("length", "Cannot multiply a null Length"); return new Length(length._length * scalar); } public static Length operator *(double scalar, Length length) { if (null == length) throw new ArgumentNullException("length", "Cannot multiply a null Length"); return new Length(scalar * length._length); } public static Length operator /(Length length, double scalar) { if (null == length) throw new ArgumentNullException("length", "Cannot divide a null Length"); if (0.0 == scalar) throw new DivideByZeroException("Cannot divide Length by 0"); return new Length(length._length / scalar); } #endregion #region comparison operators public static bool operator ==(Length left, Length right) { bool bReturn = false; if (object.ReferenceEquals(left, null)) { if (object.ReferenceEquals(right, null)) { //both are null, so we are == bReturn = true; } } else { if (!object.ReferenceEquals(left, null) && !object.ReferenceEquals(right, null)) { bReturn = left._length == right._length; } } return bReturn; } public static bool operator !=(Length left, Length right) { return !(left == right); } public static bool operator <(Length left, Length right) { if (null == left) throw new ArgumentNullException("left", "Cannot compare null Length"); if (null == right) throw new ArgumentNullException("right", "Cannot compare null Length"); return (left._length < right._length); } public static bool operator >(Length left, Length right) { if (null == left) throw new ArgumentNullException("left", "Cannot compare null Length"); if (null == right) throw new ArgumentNullException("right", "Cannot compare null Length"); return (left._length > right._length); } public static bool operator <=(Length left, Length right) { if (null == left) throw new ArgumentNullException("left", "Cannot compare null Length"); if (null == right) throw new ArgumentNullException("right", "Cannot compare null Length"); return (left._length <= right._length); } public static bool operator >=(Length left, Length right) { if (null == left) throw new ArgumentNullException("left", "Cannot compare null Length"); if (null == right) throw new ArgumentNullException("right", "Cannot compare null Length"); return (left._length >= right._length); } #endregion #region operators with non-length classes /// /// Implements the operator / for Velocity = Length / PrecisionTimeSpan /// /// The length. /// The time. /// /// Velocity /// public static Velocity operator /(Length length, PrecisionTimeSpan time) //public static Velocity operator /(Length length, TimeSpan time) { if (null == length) throw new ArgumentNullException("length", "Cannot divide a null Length"); if (null == time) throw new ArgumentNullException("time", "Cannot divide by a null PrecisionTimeSpan"); if (0.0 == time.Milliseconds) throw new DivideByZeroException("Cannot divide Length by 0 time"); return Velocity.FromMetersPerSec(length.Meters / time.Seconds); } /// /// Implements the operator / for PrecisionTimeSpan = Length / Velocity /// /// The length. /// The velocity. /// /// PrecisionTimeSpan /// public static PrecisionTimeSpan operator /(Length length, Velocity velocity) { if (null == length) throw new ArgumentNullException("length", "Cannot divide a null Length"); if (null == velocity) throw new ArgumentNullException("velocity", "Cannot divide by a null Velocity"); if (0.0 == velocity.MetersPerSec) throw new DivideByZeroException("Cannot divide Length by 0 velocity"); return PrecisionTimeSpan.FromSeconds(length.Meters / velocity.MetersPerSec); } #endregion #region parsing public static Length Parse(string s) { return Common.Parse(s, _unitInfo); } public static bool TryParse(string s, out Length value) { try { value = Length.Parse(s); return true; } catch (Exception) { value = null; return false; } } #endregion /// /// Returns a string appended with default units (e.g. "1.23 m/sec^2"). /// /// /// A string that represents this instance /// public override string ToString() { return ToString(DefaultUnits); } /// /// overload that returns a string appended with specified units (e.g. "1.23 ft/sec^2"). /// /// /// public string ToString(Unit units) { double value = (double)_unitInfo[units].PropertyGetter.Invoke(this, null); return $"{value} {_unitInfo[units].Abbreviation[0]}"; } } }