diff --git a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs index 8694e214b9..d42f27cf6c 100644 --- a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs @@ -164,6 +164,8 @@ private void GenerateStaticConstructor() Writer.WL($@" }}, BaseUnit, Zero, BaseDimensions, QuantityType.{_quantity.Name}); + + RegisterDefaultConversions(DefaultConversionFunctions); }} "); } @@ -213,9 +215,9 @@ private void GenerateInstanceConstructors() _value = Guard.EnsureValidNumber(value, nameof(value));" : @" _value = value;"); - Writer.WL(@" + Writer.WL($@" _unit = firstUnitInfo?.Value ?? throw new ArgumentException(""No units were found for the given UnitSystem."", nameof(unitSystem)); - } + }} "); } @@ -224,6 +226,11 @@ private void GenerateStaticProperties() Writer.WL($@" #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions {{ get; }} = new UnitConverter(); + /// public static QuantityInfo<{_unitEnumName}> Info {{ get; }} @@ -360,27 +367,29 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) if(unit.SingularName == _quantity.BaseUnit) continue; - Writer.WL( $@" - unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{_quantity.BaseUnit}, {_quantity.Name}Unit.{unit.SingularName}, quantity => quantity.ToUnit({_quantity.Name}Unit.{unit.SingularName}));"); + var func = unit.FromBaseToUnitFunc.Replace("{x}", "quantity.Value"); + Writer.WL($@" + unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{_quantity.BaseUnit}, {_quantity.Name}Unit.{unit.SingularName}, quantity => new {_quantity.Name}({func}, {_quantity.Name}Unit.{unit.SingularName}));"); } - Writer.WL( $@" + Writer.WL($@" // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{_quantity.BaseUnit}, {_unitEnumName}.{_quantity.BaseUnit}, quantity => quantity); - // Register in unit converter: {_quantity.Name}Unit -> BaseUnit" ); + // Register in unit converter: {_quantity.Name}Unit -> BaseUnit"); foreach(var unit in _quantity.Units) { if(unit.SingularName == _quantity.BaseUnit) continue; - Writer.WL($@" - unitConverter.SetConversionFunction<{_quantity.Name}>({_quantity.Name}Unit.{unit.SingularName}, {_unitEnumName}.{_quantity.BaseUnit}, quantity => quantity.ToBaseUnit());" ); + var func = unit.FromUnitToBaseFunc.Replace("{x}", "quantity.Value"); + Writer.WL($@" + unitConverter.SetConversionFunction<{_quantity.Name}>({_quantity.Name}Unit.{unit.SingularName}, {_unitEnumName}.{_quantity.BaseUnit}, quantity => new {_quantity.Name}({func}, {_unitEnumName}.{_quantity.BaseUnit}));"); } - Writer.WL( $@" + Writer.WL($@" }} /// @@ -903,11 +912,42 @@ double IQuantity.As(Enum unit) /// /// Converts this {_quantity.Name} to another {_quantity.Name} with the unit representation . /// + /// The unit to convert to. /// A {_quantity.Name} with the specified unit. public {_quantity.Name} ToUnit({_unitEnumName} unit) {{ - var convertedValue = GetValueAs(unit); - return new {_quantity.Name}(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + }} + + /// + /// Converts this {_quantity.Name} to another {_quantity.Name} using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A {_quantity.Name} with the specified unit. + public {_quantity.Name} ToUnit({_unitEnumName} unit, UnitConverter unitConverter) + {{ + if(Unit == unit) + {{ + // Already in requested units. + return this; + }} + else if(unitConverter.TryGetConversionFunction((typeof({_quantity.Name}), Unit, typeof({_quantity.Name}), unit), out var conversionFunction)) + {{ + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return ({_quantity.Name})converted; + }} + else if(Unit != BaseUnit) + {{ + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + }} + else + {{ + throw new NotImplementedException($""Can not convert {{Unit}} to {{unit}}.""); + }} }} /// @@ -916,7 +956,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is {_unitEnumName} unitAs{_unitEnumName})) throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit)); - return ToUnit(unitAs{_unitEnumName}); + return ToUnit(unitAs{_unitEnumName}, DefaultConversionFunctions); + }} + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + {{ + if(!(unit is {_unitEnumName} unitAs{_unitEnumName})) + throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit)); + + return ToUnit(unitAs{_unitEnumName}, unitConverter); }} /// @@ -941,62 +990,16 @@ IQuantity IQuantity.ToUnit(Enum unit) IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit({_unitEnumName} unit) => ToUnit(unit); /// - IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit({_unitEnumName} unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private {_valueType} GetValueInBaseUnit() - {{ - switch(Unit) - {{"); - foreach (var unit in _quantity.Units) - { - var func = unit.FromUnitToBaseFunc.Replace("{x}", "_value"); - Writer.WL($@" - case {_unitEnumName}.{unit.SingularName}: return {func};"); - } - - Writer.WL($@" - default: - throw new NotImplementedException($""Can not convert {{Unit}} to base units.""); - }} - }} - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal {_quantity.Name} ToBaseUnit() - {{ - var baseUnitValue = GetValueInBaseUnit(); - return new {_quantity.Name}(baseUnitValue, BaseUnit); - }} + /// + IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private {_valueType} GetValueAs({_unitEnumName} unit) {{ - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - {{"); - foreach (var unit in _quantity.Units) - { - var func = unit.FromBaseToUnitFunc.Replace("{x}", "baseUnitValue"); - Writer.WL($@" - case {_unitEnumName}.{unit.SingularName}: return {func};"); - } - - Writer.WL(@" - default: - throw new NotImplementedException($""Can not convert {Unit} to {unit}.""); - } - } + var converted = ToUnit(unit); + return ({_valueType})converted.Value; + }} #endregion "); @@ -1084,7 +1087,7 @@ public string ToString(string format, IFormatProvider? provider) }} #endregion -" ); +"); } private void GenerateIConvertibleMethods() diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs index b0c7b9a5d6..40610f5685 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs @@ -76,6 +76,7 @@ public override string Generate() Writer.WL(GeneratedFileHeader); Writer.WL($@" using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -95,16 +96,37 @@ namespace UnitsNet.Tests // ReSharper disable once PartialTypeWithSinglePart public abstract partial class {_quantity.Name}TestsBase : QuantityTestsBase {{"); - foreach (var unit in _quantity.Units) Writer.WL($@" + foreach(var unit in _quantity.Units) Writer.WL($@" protected abstract double {unit.PluralName}InOne{_baseUnit.SingularName} {{ get; }}"); Writer.WL(""); Writer.WL($@" // ReSharper disable VirtualMemberNeverOverriden.Global"); - foreach (var unit in _quantity.Units) Writer.WL($@" + foreach(var unit in _quantity.Units) Writer.WL($@" protected virtual double {unit.PluralName}Tolerance {{ get {{ return 1e-5; }} }}"); Writer.WL($@" // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor({_unitEnumName} unit) + {{ + return unit switch + {{"); + foreach(var unit in _quantity.Units) Writer.WL($@" + {GetUnitFullName(unit)} => ({unit.PluralName}InOne{_baseUnit.SingularName}, {unit.PluralName}Tolerance),"); + Writer.WL($@" + _ => throw new NotSupportedException() + }}; + }} + + public static IEnumerable UnitTypes = new List + {{"); + foreach(var unit in _quantity.Units) + { + Writer.WL($@" + new object[] {{ {GetUnitFullName(unit)} }},"); + } + Writer.WL($@" + }}; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() {{ @@ -116,14 +138,14 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() {{ var quantity = new {_quantity.Name}(); Assert.Equal(0, quantity.Value);"); - if (_quantity.BaseType == "decimal") Writer.WL($@" + if(_quantity.BaseType == "decimal") Writer.WL($@" Assert.Equal(0m, ((IDecimalQuantity)quantity).Value);"); Writer.WL($@" Assert.Equal({_baseUnitFullName}, quantity.Unit); }} "); - if (_quantity.BaseType == "double") Writer.WL($@" + if(_quantity.BaseType == "double") Writer.WL($@" [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() {{ @@ -183,7 +205,7 @@ public void Ctor_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() {{ {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); - foreach (var unit in _quantity.Units) Writer.WL($@" + foreach(var unit in _quantity.Units) Writer.WL($@" AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, {baseUnitVariableName}.{unit.PluralName}, {unit.PluralName}Tolerance);"); Writer.WL($@" }} @@ -192,7 +214,7 @@ public void Ctor_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() {{"); int i = 0; - foreach (var unit in _quantity.Units) + foreach(var unit in _quantity.Units) { var quantityVariable = $"quantity{i++:D2}"; Writer.WL($@" @@ -205,7 +227,7 @@ public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() Writer.WL($@" }} "); - if (_quantity.BaseType == "double") Writer.WL($@" + if(_quantity.BaseType == "double") Writer.WL($@" [Fact] public void From{_baseUnit.PluralName}_WithInfinityValue_ThrowsArgumentException() {{ @@ -224,7 +246,7 @@ public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() public void As() {{ var {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); - foreach (var unit in _quantity.Units) Writer.WL($@" + foreach(var unit in _quantity.Units) Writer.WL($@" AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, {baseUnitVariableName}.As({GetUnitFullName(unit)}), {unit.PluralName}Tolerance);"); Writer.WL($@" }} @@ -246,29 +268,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() }} }} - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit({_unitEnumName} unit) {{ - var {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); - foreach (var unit in _quantity.Units) - { - var asQuantityVariableName = $"{unit.SingularName.ToLowerInvariant()}Quantity"; + var inBaseUnits = {_quantity.Name}.From(1.0, {_quantity.Name}.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - Writer.WL(""); - Writer.WL($@" - var {asQuantityVariableName} = {baseUnitVariableName}.ToUnit({GetUnitFullName(unit)}); - AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, (double){asQuantityVariableName}.Value, {unit.PluralName}Tolerance); - Assert.Equal({GetUnitFullName(unit)}, {asQuantityVariableName}.Unit);"); - } - Writer.WL($@" + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); }} - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual({_unitEnumName} unit) {{ - var quantityInBaseUnit = {_quantity.Name}.From{_baseUnit.PluralName}(1).ToBaseUnit(); - Assert.Equal({_quantity.Name}.BaseUnit, quantityInBaseUnit.Unit);"); - Writer.WL($@" + var quantity = {_quantity.Name}.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + }} + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit({_unitEnumName} unit) + {{ + // See if there is a unit available that is not the base unit. + var fromUnit = {_quantity.Name}.Units.FirstOrDefault(u => u != {_quantity.Name}.BaseUnit && u != {_unitEnumName}.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == {_unitEnumName}.Undefined) + fromUnit = {_quantity.Name}.BaseUnit; + + var quantity = {_quantity.Name}.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); }} [Fact] @@ -701,9 +735,9 @@ public void GetHashCode_Equals() }} "); - if( _quantity.GenerateArithmetic ) + if(_quantity.GenerateArithmetic) { - Writer.WL( $@" + Writer.WL($@" [Theory] [InlineData(1.0)] [InlineData(-1.0)] @@ -716,7 +750,7 @@ public void NegationOperator_ReturnsQuantity_WithNegatedValue(double value) Writer.WL($@" }} -}}" ); +}}"); return Writer.ToString(); } } diff --git a/UnitsNet.Tests/CustomQuantities/HowMuch.cs b/UnitsNet.Tests/CustomQuantities/HowMuch.cs index d41f0dcfab..ff41feb577 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuch.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuch.cs @@ -49,6 +49,8 @@ public IQuantity ToUnit(Enum unit) throw new ArgumentException("Must be of type HowMuchUnit.", nameof(unit)); } + public IQuantity ToUnit(Enum unit, UnitConverter unitConverter) => throw new NotImplementedException(); + public IQuantity ToUnit(UnitSystem unitSystem) => throw new NotImplementedException(); public override string ToString() => $"{Value} {Unit}"; diff --git a/UnitsNet.Tests/DummyIQuantity.cs b/UnitsNet.Tests/DummyIQuantity.cs index 04f97a7ea2..6bcb848c2d 100644 --- a/UnitsNet.Tests/DummyIQuantity.cs +++ b/UnitsNet.Tests/DummyIQuantity.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using JetBrains.Annotations; namespace UnitsNet.Tests @@ -17,44 +15,22 @@ internal class DummyIQuantity : IQuantity public double Value => throw new NotImplementedException(); - public double As(Enum unit) - { - throw new NotImplementedException(); - } - - public double As(UnitSystem unitSystem) - { - throw new NotImplementedException(); - } - - public string ToString([CanBeNull] IFormatProvider provider) - { - throw new NotImplementedException(); - } - - public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) - { - throw new NotImplementedException(); - } - - public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) - { - throw new NotImplementedException(); - } - - public string ToString(string format, IFormatProvider formatProvider) - { - throw new NotImplementedException(); - } - - public IQuantity ToUnit(Enum unit) - { - throw new NotImplementedException(); - } - - public IQuantity ToUnit(UnitSystem unitSystem) - { - throw new NotImplementedException(); - } + public double As(Enum unit ) => throw new NotImplementedException(); + + public double As(UnitSystem unitSystem ) => throw new NotImplementedException(); + + public string ToString([CanBeNull] IFormatProvider provider ) => throw new NotImplementedException(); + + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix ) => throw new NotImplementedException(); + + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args ) => throw new NotImplementedException(); + + public string ToString(string format, IFormatProvider formatProvider ) => throw new NotImplementedException(); + + public IQuantity ToUnit(Enum unit ) => throw new NotImplementedException(); + + public IQuantity ToUnit(Enum unit, UnitConverter unitConverter) => throw new NotImplementedException(); + + public IQuantity ToUnit(UnitSystem unitSystem ) => throw new NotImplementedException(); } } diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs index 8fdff341d5..13abeeccbc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -69,6 +70,46 @@ public abstract partial class AccelerationTestsBase : QuantityTestsBase protected virtual double StandardGravityTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AccelerationUnit unit) + { + return unit switch + { + AccelerationUnit.CentimeterPerSecondSquared => (CentimetersPerSecondSquaredInOneMeterPerSecondSquared, CentimetersPerSecondSquaredTolerance), + AccelerationUnit.DecimeterPerSecondSquared => (DecimetersPerSecondSquaredInOneMeterPerSecondSquared, DecimetersPerSecondSquaredTolerance), + AccelerationUnit.FootPerSecondSquared => (FeetPerSecondSquaredInOneMeterPerSecondSquared, FeetPerSecondSquaredTolerance), + AccelerationUnit.InchPerSecondSquared => (InchesPerSecondSquaredInOneMeterPerSecondSquared, InchesPerSecondSquaredTolerance), + AccelerationUnit.KilometerPerSecondSquared => (KilometersPerSecondSquaredInOneMeterPerSecondSquared, KilometersPerSecondSquaredTolerance), + AccelerationUnit.KnotPerHour => (KnotsPerHourInOneMeterPerSecondSquared, KnotsPerHourTolerance), + AccelerationUnit.KnotPerMinute => (KnotsPerMinuteInOneMeterPerSecondSquared, KnotsPerMinuteTolerance), + AccelerationUnit.KnotPerSecond => (KnotsPerSecondInOneMeterPerSecondSquared, KnotsPerSecondTolerance), + AccelerationUnit.MeterPerSecondSquared => (MetersPerSecondSquaredInOneMeterPerSecondSquared, MetersPerSecondSquaredTolerance), + AccelerationUnit.MicrometerPerSecondSquared => (MicrometersPerSecondSquaredInOneMeterPerSecondSquared, MicrometersPerSecondSquaredTolerance), + AccelerationUnit.MillimeterPerSecondSquared => (MillimetersPerSecondSquaredInOneMeterPerSecondSquared, MillimetersPerSecondSquaredTolerance), + AccelerationUnit.MillistandardGravity => (MillistandardGravityInOneMeterPerSecondSquared, MillistandardGravityTolerance), + AccelerationUnit.NanometerPerSecondSquared => (NanometersPerSecondSquaredInOneMeterPerSecondSquared, NanometersPerSecondSquaredTolerance), + AccelerationUnit.StandardGravity => (StandardGravityInOneMeterPerSecondSquared, StandardGravityTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { AccelerationUnit.CentimeterPerSecondSquared }, + new object[] { AccelerationUnit.DecimeterPerSecondSquared }, + new object[] { AccelerationUnit.FootPerSecondSquared }, + new object[] { AccelerationUnit.InchPerSecondSquared }, + new object[] { AccelerationUnit.KilometerPerSecondSquared }, + new object[] { AccelerationUnit.KnotPerHour }, + new object[] { AccelerationUnit.KnotPerMinute }, + new object[] { AccelerationUnit.KnotPerSecond }, + new object[] { AccelerationUnit.MeterPerSecondSquared }, + new object[] { AccelerationUnit.MicrometerPerSecondSquared }, + new object[] { AccelerationUnit.MillimeterPerSecondSquared }, + new object[] { AccelerationUnit.MillistandardGravity }, + new object[] { AccelerationUnit.NanometerPerSecondSquared }, + new object[] { AccelerationUnit.StandardGravity }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -268,73 +309,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(AccelerationUnit unit) { - var meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - - var centimeterpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.CentimeterPerSecondSquared); - AssertEx.EqualTolerance(CentimetersPerSecondSquaredInOneMeterPerSecondSquared, (double)centimeterpersecondsquaredQuantity.Value, CentimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.CentimeterPerSecondSquared, centimeterpersecondsquaredQuantity.Unit); - - var decimeterpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.DecimeterPerSecondSquared); - AssertEx.EqualTolerance(DecimetersPerSecondSquaredInOneMeterPerSecondSquared, (double)decimeterpersecondsquaredQuantity.Value, DecimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.DecimeterPerSecondSquared, decimeterpersecondsquaredQuantity.Unit); - - var footpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.FootPerSecondSquared); - AssertEx.EqualTolerance(FeetPerSecondSquaredInOneMeterPerSecondSquared, (double)footpersecondsquaredQuantity.Value, FeetPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.FootPerSecondSquared, footpersecondsquaredQuantity.Unit); - - var inchpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.InchPerSecondSquared); - AssertEx.EqualTolerance(InchesPerSecondSquaredInOneMeterPerSecondSquared, (double)inchpersecondsquaredQuantity.Value, InchesPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.InchPerSecondSquared, inchpersecondsquaredQuantity.Unit); - - var kilometerpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.KilometerPerSecondSquared); - AssertEx.EqualTolerance(KilometersPerSecondSquaredInOneMeterPerSecondSquared, (double)kilometerpersecondsquaredQuantity.Value, KilometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.KilometerPerSecondSquared, kilometerpersecondsquaredQuantity.Unit); - - var knotperhourQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.KnotPerHour); - AssertEx.EqualTolerance(KnotsPerHourInOneMeterPerSecondSquared, (double)knotperhourQuantity.Value, KnotsPerHourTolerance); - Assert.Equal(AccelerationUnit.KnotPerHour, knotperhourQuantity.Unit); - - var knotperminuteQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.KnotPerMinute); - AssertEx.EqualTolerance(KnotsPerMinuteInOneMeterPerSecondSquared, (double)knotperminuteQuantity.Value, KnotsPerMinuteTolerance); - Assert.Equal(AccelerationUnit.KnotPerMinute, knotperminuteQuantity.Unit); + var inBaseUnits = Acceleration.From(1.0, Acceleration.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var knotpersecondQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.KnotPerSecond); - AssertEx.EqualTolerance(KnotsPerSecondInOneMeterPerSecondSquared, (double)knotpersecondQuantity.Value, KnotsPerSecondTolerance); - Assert.Equal(AccelerationUnit.KnotPerSecond, knotpersecondQuantity.Unit); - - var meterpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.MeterPerSecondSquared); - AssertEx.EqualTolerance(MetersPerSecondSquaredInOneMeterPerSecondSquared, (double)meterpersecondsquaredQuantity.Value, MetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MeterPerSecondSquared, meterpersecondsquaredQuantity.Unit); - - var micrometerpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.MicrometerPerSecondSquared); - AssertEx.EqualTolerance(MicrometersPerSecondSquaredInOneMeterPerSecondSquared, (double)micrometerpersecondsquaredQuantity.Value, MicrometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MicrometerPerSecondSquared, micrometerpersecondsquaredQuantity.Unit); - - var millimeterpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.MillimeterPerSecondSquared); - AssertEx.EqualTolerance(MillimetersPerSecondSquaredInOneMeterPerSecondSquared, (double)millimeterpersecondsquaredQuantity.Value, MillimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MillimeterPerSecondSquared, millimeterpersecondsquaredQuantity.Unit); - - var millistandardgravityQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.MillistandardGravity); - AssertEx.EqualTolerance(MillistandardGravityInOneMeterPerSecondSquared, (double)millistandardgravityQuantity.Value, MillistandardGravityTolerance); - Assert.Equal(AccelerationUnit.MillistandardGravity, millistandardgravityQuantity.Unit); - - var nanometerpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.NanometerPerSecondSquared); - AssertEx.EqualTolerance(NanometersPerSecondSquaredInOneMeterPerSecondSquared, (double)nanometerpersecondsquaredQuantity.Value, NanometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.NanometerPerSecondSquared, nanometerpersecondsquaredQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var standardgravityQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.StandardGravity); - AssertEx.EqualTolerance(StandardGravityInOneMeterPerSecondSquared, (double)standardgravityQuantity.Value, StandardGravityTolerance); - Assert.Equal(AccelerationUnit.StandardGravity, standardgravityQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(AccelerationUnit unit) + { + var quantity = Acceleration.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AccelerationUnit unit) { - var quantityInBaseUnit = Acceleration.FromMetersPerSecondSquared(1).ToBaseUnit(); - Assert.Equal(Acceleration.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Acceleration.Units.FirstOrDefault(u => u != Acceleration.BaseUnit && u != AccelerationUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == AccelerationUnit.Undefined) + fromUnit = Acceleration.BaseUnit; + + var quantity = Acceleration.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs index 9495e04c8f..01cd7be916 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -71,6 +72,48 @@ public abstract partial class AmountOfSubstanceTestsBase : QuantityTestsBase protected virtual double PoundMolesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AmountOfSubstanceUnit unit) + { + return unit switch + { + AmountOfSubstanceUnit.Centimole => (CentimolesInOneMole, CentimolesTolerance), + AmountOfSubstanceUnit.CentipoundMole => (CentipoundMolesInOneMole, CentipoundMolesTolerance), + AmountOfSubstanceUnit.Decimole => (DecimolesInOneMole, DecimolesTolerance), + AmountOfSubstanceUnit.DecipoundMole => (DecipoundMolesInOneMole, DecipoundMolesTolerance), + AmountOfSubstanceUnit.Kilomole => (KilomolesInOneMole, KilomolesTolerance), + AmountOfSubstanceUnit.KilopoundMole => (KilopoundMolesInOneMole, KilopoundMolesTolerance), + AmountOfSubstanceUnit.Megamole => (MegamolesInOneMole, MegamolesTolerance), + AmountOfSubstanceUnit.Micromole => (MicromolesInOneMole, MicromolesTolerance), + AmountOfSubstanceUnit.MicropoundMole => (MicropoundMolesInOneMole, MicropoundMolesTolerance), + AmountOfSubstanceUnit.Millimole => (MillimolesInOneMole, MillimolesTolerance), + AmountOfSubstanceUnit.MillipoundMole => (MillipoundMolesInOneMole, MillipoundMolesTolerance), + AmountOfSubstanceUnit.Mole => (MolesInOneMole, MolesTolerance), + AmountOfSubstanceUnit.Nanomole => (NanomolesInOneMole, NanomolesTolerance), + AmountOfSubstanceUnit.NanopoundMole => (NanopoundMolesInOneMole, NanopoundMolesTolerance), + AmountOfSubstanceUnit.PoundMole => (PoundMolesInOneMole, PoundMolesTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { AmountOfSubstanceUnit.Centimole }, + new object[] { AmountOfSubstanceUnit.CentipoundMole }, + new object[] { AmountOfSubstanceUnit.Decimole }, + new object[] { AmountOfSubstanceUnit.DecipoundMole }, + new object[] { AmountOfSubstanceUnit.Kilomole }, + new object[] { AmountOfSubstanceUnit.KilopoundMole }, + new object[] { AmountOfSubstanceUnit.Megamole }, + new object[] { AmountOfSubstanceUnit.Micromole }, + new object[] { AmountOfSubstanceUnit.MicropoundMole }, + new object[] { AmountOfSubstanceUnit.Millimole }, + new object[] { AmountOfSubstanceUnit.MillipoundMole }, + new object[] { AmountOfSubstanceUnit.Mole }, + new object[] { AmountOfSubstanceUnit.Nanomole }, + new object[] { AmountOfSubstanceUnit.NanopoundMole }, + new object[] { AmountOfSubstanceUnit.PoundMole }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -276,77 +319,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(AmountOfSubstanceUnit unit) { - var mole = AmountOfSubstance.FromMoles(1); - - var centimoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Centimole); - AssertEx.EqualTolerance(CentimolesInOneMole, (double)centimoleQuantity.Value, CentimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Centimole, centimoleQuantity.Unit); - - var centipoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.CentipoundMole); - AssertEx.EqualTolerance(CentipoundMolesInOneMole, (double)centipoundmoleQuantity.Value, CentipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.CentipoundMole, centipoundmoleQuantity.Unit); - - var decimoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Decimole); - AssertEx.EqualTolerance(DecimolesInOneMole, (double)decimoleQuantity.Value, DecimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Decimole, decimoleQuantity.Unit); - - var decipoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.DecipoundMole); - AssertEx.EqualTolerance(DecipoundMolesInOneMole, (double)decipoundmoleQuantity.Value, DecipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.DecipoundMole, decipoundmoleQuantity.Unit); - - var kilomoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Kilomole); - AssertEx.EqualTolerance(KilomolesInOneMole, (double)kilomoleQuantity.Value, KilomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Kilomole, kilomoleQuantity.Unit); - - var kilopoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.KilopoundMole); - AssertEx.EqualTolerance(KilopoundMolesInOneMole, (double)kilopoundmoleQuantity.Value, KilopoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.KilopoundMole, kilopoundmoleQuantity.Unit); - - var megamoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Megamole); - AssertEx.EqualTolerance(MegamolesInOneMole, (double)megamoleQuantity.Value, MegamolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Megamole, megamoleQuantity.Unit); + var inBaseUnits = AmountOfSubstance.From(1.0, AmountOfSubstance.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var micromoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Micromole); - AssertEx.EqualTolerance(MicromolesInOneMole, (double)micromoleQuantity.Value, MicromolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Micromole, micromoleQuantity.Unit); - - var micropoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.MicropoundMole); - AssertEx.EqualTolerance(MicropoundMolesInOneMole, (double)micropoundmoleQuantity.Value, MicropoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.MicropoundMole, micropoundmoleQuantity.Unit); - - var millimoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Millimole); - AssertEx.EqualTolerance(MillimolesInOneMole, (double)millimoleQuantity.Value, MillimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Millimole, millimoleQuantity.Unit); - - var millipoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.MillipoundMole); - AssertEx.EqualTolerance(MillipoundMolesInOneMole, (double)millipoundmoleQuantity.Value, MillipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.MillipoundMole, millipoundmoleQuantity.Unit); - - var moleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Mole); - AssertEx.EqualTolerance(MolesInOneMole, (double)moleQuantity.Value, MolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Mole, moleQuantity.Unit); - - var nanomoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Nanomole); - AssertEx.EqualTolerance(NanomolesInOneMole, (double)nanomoleQuantity.Value, NanomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Nanomole, nanomoleQuantity.Unit); - - var nanopoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.NanopoundMole); - AssertEx.EqualTolerance(NanopoundMolesInOneMole, (double)nanopoundmoleQuantity.Value, NanopoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.NanopoundMole, nanopoundmoleQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var poundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.PoundMole); - AssertEx.EqualTolerance(PoundMolesInOneMole, (double)poundmoleQuantity.Value, PoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.PoundMole, poundmoleQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(AmountOfSubstanceUnit unit) + { + var quantity = AmountOfSubstance.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AmountOfSubstanceUnit unit) { - var quantityInBaseUnit = AmountOfSubstance.FromMoles(1).ToBaseUnit(); - Assert.Equal(AmountOfSubstance.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = AmountOfSubstance.Units.FirstOrDefault(u => u != AmountOfSubstance.BaseUnit && u != AmountOfSubstanceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == AmountOfSubstanceUnit.Undefined) + fromUnit = AmountOfSubstance.BaseUnit; + + var quantity = AmountOfSubstance.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs index 24063f7fe9..eb9a8dc24f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class AmplitudeRatioTestsBase : QuantityTestsBase protected virtual double DecibelVoltsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AmplitudeRatioUnit unit) + { + return unit switch + { + AmplitudeRatioUnit.DecibelMicrovolt => (DecibelMicrovoltsInOneDecibelVolt, DecibelMicrovoltsTolerance), + AmplitudeRatioUnit.DecibelMillivolt => (DecibelMillivoltsInOneDecibelVolt, DecibelMillivoltsTolerance), + AmplitudeRatioUnit.DecibelUnloaded => (DecibelsUnloadedInOneDecibelVolt, DecibelsUnloadedTolerance), + AmplitudeRatioUnit.DecibelVolt => (DecibelVoltsInOneDecibelVolt, DecibelVoltsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { AmplitudeRatioUnit.DecibelMicrovolt }, + new object[] { AmplitudeRatioUnit.DecibelMillivolt }, + new object[] { AmplitudeRatioUnit.DecibelUnloaded }, + new object[] { AmplitudeRatioUnit.DecibelVolt }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(AmplitudeRatioUnit unit) { - var decibelvolt = AmplitudeRatio.FromDecibelVolts(1); + var inBaseUnits = AmplitudeRatio.From(1.0, AmplitudeRatio.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var decibelmicrovoltQuantity = decibelvolt.ToUnit(AmplitudeRatioUnit.DecibelMicrovolt); - AssertEx.EqualTolerance(DecibelMicrovoltsInOneDecibelVolt, (double)decibelmicrovoltQuantity.Value, DecibelMicrovoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelMicrovolt, decibelmicrovoltQuantity.Unit); - - var decibelmillivoltQuantity = decibelvolt.ToUnit(AmplitudeRatioUnit.DecibelMillivolt); - AssertEx.EqualTolerance(DecibelMillivoltsInOneDecibelVolt, (double)decibelmillivoltQuantity.Value, DecibelMillivoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelMillivolt, decibelmillivoltQuantity.Unit); - - var decibelunloadedQuantity = decibelvolt.ToUnit(AmplitudeRatioUnit.DecibelUnloaded); - AssertEx.EqualTolerance(DecibelsUnloadedInOneDecibelVolt, (double)decibelunloadedQuantity.Value, DecibelsUnloadedTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelUnloaded, decibelunloadedQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var decibelvoltQuantity = decibelvolt.ToUnit(AmplitudeRatioUnit.DecibelVolt); - AssertEx.EqualTolerance(DecibelVoltsInOneDecibelVolt, (double)decibelvoltQuantity.Value, DecibelVoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelVolt, decibelvoltQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(AmplitudeRatioUnit unit) + { + var quantity = AmplitudeRatio.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AmplitudeRatioUnit unit) { - var quantityInBaseUnit = AmplitudeRatio.FromDecibelVolts(1).ToBaseUnit(); - Assert.Equal(AmplitudeRatio.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = AmplitudeRatio.Units.FirstOrDefault(u => u != AmplitudeRatio.BaseUnit && u != AmplitudeRatioUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == AmplitudeRatioUnit.Undefined) + fromUnit = AmplitudeRatio.BaseUnit; + + var quantity = AmplitudeRatio.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs index b495603ee4..bfecc91bbc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -73,6 +74,50 @@ public abstract partial class AngleTestsBase : QuantityTestsBase protected virtual double TiltTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AngleUnit unit) + { + return unit switch + { + AngleUnit.Arcminute => (ArcminutesInOneDegree, ArcminutesTolerance), + AngleUnit.Arcsecond => (ArcsecondsInOneDegree, ArcsecondsTolerance), + AngleUnit.Centiradian => (CentiradiansInOneDegree, CentiradiansTolerance), + AngleUnit.Deciradian => (DeciradiansInOneDegree, DeciradiansTolerance), + AngleUnit.Degree => (DegreesInOneDegree, DegreesTolerance), + AngleUnit.Gradian => (GradiansInOneDegree, GradiansTolerance), + AngleUnit.Microdegree => (MicrodegreesInOneDegree, MicrodegreesTolerance), + AngleUnit.Microradian => (MicroradiansInOneDegree, MicroradiansTolerance), + AngleUnit.Millidegree => (MillidegreesInOneDegree, MillidegreesTolerance), + AngleUnit.Milliradian => (MilliradiansInOneDegree, MilliradiansTolerance), + AngleUnit.Nanodegree => (NanodegreesInOneDegree, NanodegreesTolerance), + AngleUnit.Nanoradian => (NanoradiansInOneDegree, NanoradiansTolerance), + AngleUnit.NatoMil => (NatoMilsInOneDegree, NatoMilsTolerance), + AngleUnit.Radian => (RadiansInOneDegree, RadiansTolerance), + AngleUnit.Revolution => (RevolutionsInOneDegree, RevolutionsTolerance), + AngleUnit.Tilt => (TiltInOneDegree, TiltTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { AngleUnit.Arcminute }, + new object[] { AngleUnit.Arcsecond }, + new object[] { AngleUnit.Centiradian }, + new object[] { AngleUnit.Deciradian }, + new object[] { AngleUnit.Degree }, + new object[] { AngleUnit.Gradian }, + new object[] { AngleUnit.Microdegree }, + new object[] { AngleUnit.Microradian }, + new object[] { AngleUnit.Millidegree }, + new object[] { AngleUnit.Milliradian }, + new object[] { AngleUnit.Nanodegree }, + new object[] { AngleUnit.Nanoradian }, + new object[] { AngleUnit.NatoMil }, + new object[] { AngleUnit.Radian }, + new object[] { AngleUnit.Revolution }, + new object[] { AngleUnit.Tilt }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -284,81 +329,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(AngleUnit unit) { - var degree = Angle.FromDegrees(1); - - var arcminuteQuantity = degree.ToUnit(AngleUnit.Arcminute); - AssertEx.EqualTolerance(ArcminutesInOneDegree, (double)arcminuteQuantity.Value, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, arcminuteQuantity.Unit); - - var arcsecondQuantity = degree.ToUnit(AngleUnit.Arcsecond); - AssertEx.EqualTolerance(ArcsecondsInOneDegree, (double)arcsecondQuantity.Value, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, arcsecondQuantity.Unit); - - var centiradianQuantity = degree.ToUnit(AngleUnit.Centiradian); - AssertEx.EqualTolerance(CentiradiansInOneDegree, (double)centiradianQuantity.Value, CentiradiansTolerance); - Assert.Equal(AngleUnit.Centiradian, centiradianQuantity.Unit); - - var deciradianQuantity = degree.ToUnit(AngleUnit.Deciradian); - AssertEx.EqualTolerance(DeciradiansInOneDegree, (double)deciradianQuantity.Value, DeciradiansTolerance); - Assert.Equal(AngleUnit.Deciradian, deciradianQuantity.Unit); - - var degreeQuantity = degree.ToUnit(AngleUnit.Degree); - AssertEx.EqualTolerance(DegreesInOneDegree, (double)degreeQuantity.Value, DegreesTolerance); - Assert.Equal(AngleUnit.Degree, degreeQuantity.Unit); - - var gradianQuantity = degree.ToUnit(AngleUnit.Gradian); - AssertEx.EqualTolerance(GradiansInOneDegree, (double)gradianQuantity.Value, GradiansTolerance); - Assert.Equal(AngleUnit.Gradian, gradianQuantity.Unit); - - var microdegreeQuantity = degree.ToUnit(AngleUnit.Microdegree); - AssertEx.EqualTolerance(MicrodegreesInOneDegree, (double)microdegreeQuantity.Value, MicrodegreesTolerance); - Assert.Equal(AngleUnit.Microdegree, microdegreeQuantity.Unit); - - var microradianQuantity = degree.ToUnit(AngleUnit.Microradian); - AssertEx.EqualTolerance(MicroradiansInOneDegree, (double)microradianQuantity.Value, MicroradiansTolerance); - Assert.Equal(AngleUnit.Microradian, microradianQuantity.Unit); + var inBaseUnits = Angle.From(1.0, Angle.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var millidegreeQuantity = degree.ToUnit(AngleUnit.Millidegree); - AssertEx.EqualTolerance(MillidegreesInOneDegree, (double)millidegreeQuantity.Value, MillidegreesTolerance); - Assert.Equal(AngleUnit.Millidegree, millidegreeQuantity.Unit); - - var milliradianQuantity = degree.ToUnit(AngleUnit.Milliradian); - AssertEx.EqualTolerance(MilliradiansInOneDegree, (double)milliradianQuantity.Value, MilliradiansTolerance); - Assert.Equal(AngleUnit.Milliradian, milliradianQuantity.Unit); - - var nanodegreeQuantity = degree.ToUnit(AngleUnit.Nanodegree); - AssertEx.EqualTolerance(NanodegreesInOneDegree, (double)nanodegreeQuantity.Value, NanodegreesTolerance); - Assert.Equal(AngleUnit.Nanodegree, nanodegreeQuantity.Unit); - - var nanoradianQuantity = degree.ToUnit(AngleUnit.Nanoradian); - AssertEx.EqualTolerance(NanoradiansInOneDegree, (double)nanoradianQuantity.Value, NanoradiansTolerance); - Assert.Equal(AngleUnit.Nanoradian, nanoradianQuantity.Unit); - - var natomilQuantity = degree.ToUnit(AngleUnit.NatoMil); - AssertEx.EqualTolerance(NatoMilsInOneDegree, (double)natomilQuantity.Value, NatoMilsTolerance); - Assert.Equal(AngleUnit.NatoMil, natomilQuantity.Unit); - - var radianQuantity = degree.ToUnit(AngleUnit.Radian); - AssertEx.EqualTolerance(RadiansInOneDegree, (double)radianQuantity.Value, RadiansTolerance); - Assert.Equal(AngleUnit.Radian, radianQuantity.Unit); - - var revolutionQuantity = degree.ToUnit(AngleUnit.Revolution); - AssertEx.EqualTolerance(RevolutionsInOneDegree, (double)revolutionQuantity.Value, RevolutionsTolerance); - Assert.Equal(AngleUnit.Revolution, revolutionQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tiltQuantity = degree.ToUnit(AngleUnit.Tilt); - AssertEx.EqualTolerance(TiltInOneDegree, (double)tiltQuantity.Value, TiltTolerance); - Assert.Equal(AngleUnit.Tilt, tiltQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(AngleUnit unit) + { + var quantity = Angle.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AngleUnit unit) { - var quantityInBaseUnit = Angle.FromDegrees(1).ToBaseUnit(); - Assert.Equal(Angle.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Angle.Units.FirstOrDefault(u => u != Angle.BaseUnit && u != AngleUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == AngleUnit.Undefined) + fromUnit = Angle.BaseUnit; + + var quantity = Angle.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs index 6e94f37657..3731afa216 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class ApparentEnergyTestsBase : QuantityTestsBase protected virtual double VoltampereHoursTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ApparentEnergyUnit unit) + { + return unit switch + { + ApparentEnergyUnit.KilovoltampereHour => (KilovoltampereHoursInOneVoltampereHour, KilovoltampereHoursTolerance), + ApparentEnergyUnit.MegavoltampereHour => (MegavoltampereHoursInOneVoltampereHour, MegavoltampereHoursTolerance), + ApparentEnergyUnit.VoltampereHour => (VoltampereHoursInOneVoltampereHour, VoltampereHoursTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ApparentEnergyUnit.KilovoltampereHour }, + new object[] { ApparentEnergyUnit.MegavoltampereHour }, + new object[] { ApparentEnergyUnit.VoltampereHour }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ApparentEnergyUnit unit) { - var voltamperehour = ApparentEnergy.FromVoltampereHours(1); + var inBaseUnits = ApparentEnergy.From(1.0, ApparentEnergy.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilovoltamperehourQuantity = voltamperehour.ToUnit(ApparentEnergyUnit.KilovoltampereHour); - AssertEx.EqualTolerance(KilovoltampereHoursInOneVoltampereHour, (double)kilovoltamperehourQuantity.Value, KilovoltampereHoursTolerance); - Assert.Equal(ApparentEnergyUnit.KilovoltampereHour, kilovoltamperehourQuantity.Unit); - - var megavoltamperehourQuantity = voltamperehour.ToUnit(ApparentEnergyUnit.MegavoltampereHour); - AssertEx.EqualTolerance(MegavoltampereHoursInOneVoltampereHour, (double)megavoltamperehourQuantity.Value, MegavoltampereHoursTolerance); - Assert.Equal(ApparentEnergyUnit.MegavoltampereHour, megavoltamperehourQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var voltamperehourQuantity = voltamperehour.ToUnit(ApparentEnergyUnit.VoltampereHour); - AssertEx.EqualTolerance(VoltampereHoursInOneVoltampereHour, (double)voltamperehourQuantity.Value, VoltampereHoursTolerance); - Assert.Equal(ApparentEnergyUnit.VoltampereHour, voltamperehourQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ApparentEnergyUnit unit) + { + var quantity = ApparentEnergy.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ApparentEnergyUnit unit) { - var quantityInBaseUnit = ApparentEnergy.FromVoltampereHours(1).ToBaseUnit(); - Assert.Equal(ApparentEnergy.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ApparentEnergy.Units.FirstOrDefault(u => u != ApparentEnergy.BaseUnit && u != ApparentEnergyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ApparentEnergyUnit.Undefined) + fromUnit = ApparentEnergy.BaseUnit; + + var quantity = ApparentEnergy.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs index 595427df3e..aa5184f730 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class ApparentPowerTestsBase : QuantityTestsBase protected virtual double VoltamperesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ApparentPowerUnit unit) + { + return unit switch + { + ApparentPowerUnit.Gigavoltampere => (GigavoltamperesInOneVoltampere, GigavoltamperesTolerance), + ApparentPowerUnit.Kilovoltampere => (KilovoltamperesInOneVoltampere, KilovoltamperesTolerance), + ApparentPowerUnit.Megavoltampere => (MegavoltamperesInOneVoltampere, MegavoltamperesTolerance), + ApparentPowerUnit.Voltampere => (VoltamperesInOneVoltampere, VoltamperesTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ApparentPowerUnit.Gigavoltampere }, + new object[] { ApparentPowerUnit.Kilovoltampere }, + new object[] { ApparentPowerUnit.Megavoltampere }, + new object[] { ApparentPowerUnit.Voltampere }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ApparentPowerUnit unit) { - var voltampere = ApparentPower.FromVoltamperes(1); + var inBaseUnits = ApparentPower.From(1.0, ApparentPower.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var gigavoltampereQuantity = voltampere.ToUnit(ApparentPowerUnit.Gigavoltampere); - AssertEx.EqualTolerance(GigavoltamperesInOneVoltampere, (double)gigavoltampereQuantity.Value, GigavoltamperesTolerance); - Assert.Equal(ApparentPowerUnit.Gigavoltampere, gigavoltampereQuantity.Unit); - - var kilovoltampereQuantity = voltampere.ToUnit(ApparentPowerUnit.Kilovoltampere); - AssertEx.EqualTolerance(KilovoltamperesInOneVoltampere, (double)kilovoltampereQuantity.Value, KilovoltamperesTolerance); - Assert.Equal(ApparentPowerUnit.Kilovoltampere, kilovoltampereQuantity.Unit); - - var megavoltampereQuantity = voltampere.ToUnit(ApparentPowerUnit.Megavoltampere); - AssertEx.EqualTolerance(MegavoltamperesInOneVoltampere, (double)megavoltampereQuantity.Value, MegavoltamperesTolerance); - Assert.Equal(ApparentPowerUnit.Megavoltampere, megavoltampereQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var voltampereQuantity = voltampere.ToUnit(ApparentPowerUnit.Voltampere); - AssertEx.EqualTolerance(VoltamperesInOneVoltampere, (double)voltampereQuantity.Value, VoltamperesTolerance); - Assert.Equal(ApparentPowerUnit.Voltampere, voltampereQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ApparentPowerUnit unit) + { + var quantity = ApparentPower.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ApparentPowerUnit unit) { - var quantityInBaseUnit = ApparentPower.FromVoltamperes(1).ToBaseUnit(); - Assert.Equal(ApparentPower.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ApparentPower.Units.FirstOrDefault(u => u != ApparentPower.BaseUnit && u != ApparentPowerUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ApparentPowerUnit.Undefined) + fromUnit = ApparentPower.BaseUnit; + + var quantity = ApparentPower.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs index f109ab006d..1d8d35a570 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class AreaDensityTestsBase : QuantityTestsBase protected virtual double KilogramsPerSquareMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AreaDensityUnit unit) + { + return unit switch + { + AreaDensityUnit.KilogramPerSquareMeter => (KilogramsPerSquareMeterInOneKilogramPerSquareMeter, KilogramsPerSquareMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { AreaDensityUnit.KilogramPerSquareMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(AreaDensityUnit unit) { - var kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); + var inBaseUnits = AreaDensity.From(1.0, AreaDensity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilogrampersquaremeterQuantity = kilogrampersquaremeter.ToUnit(AreaDensityUnit.KilogramPerSquareMeter); - AssertEx.EqualTolerance(KilogramsPerSquareMeterInOneKilogramPerSquareMeter, (double)kilogrampersquaremeterQuantity.Value, KilogramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.KilogramPerSquareMeter, kilogrampersquaremeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(AreaDensityUnit unit) + { + var quantity = AreaDensity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaDensityUnit unit) { - var quantityInBaseUnit = AreaDensity.FromKilogramsPerSquareMeter(1).ToBaseUnit(); - Assert.Equal(AreaDensity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = AreaDensity.Units.FirstOrDefault(u => u != AreaDensity.BaseUnit && u != AreaDensityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == AreaDensityUnit.Undefined) + fromUnit = AreaDensity.BaseUnit; + + var quantity = AreaDensity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs index c885ab32f6..835911e9a6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -53,6 +54,30 @@ public abstract partial class AreaMomentOfInertiaTestsBase : QuantityTestsBase protected virtual double MillimetersToTheFourthTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AreaMomentOfInertiaUnit unit) + { + return unit switch + { + AreaMomentOfInertiaUnit.CentimeterToTheFourth => (CentimetersToTheFourthInOneMeterToTheFourth, CentimetersToTheFourthTolerance), + AreaMomentOfInertiaUnit.DecimeterToTheFourth => (DecimetersToTheFourthInOneMeterToTheFourth, DecimetersToTheFourthTolerance), + AreaMomentOfInertiaUnit.FootToTheFourth => (FeetToTheFourthInOneMeterToTheFourth, FeetToTheFourthTolerance), + AreaMomentOfInertiaUnit.InchToTheFourth => (InchesToTheFourthInOneMeterToTheFourth, InchesToTheFourthTolerance), + AreaMomentOfInertiaUnit.MeterToTheFourth => (MetersToTheFourthInOneMeterToTheFourth, MetersToTheFourthTolerance), + AreaMomentOfInertiaUnit.MillimeterToTheFourth => (MillimetersToTheFourthInOneMeterToTheFourth, MillimetersToTheFourthTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { AreaMomentOfInertiaUnit.CentimeterToTheFourth }, + new object[] { AreaMomentOfInertiaUnit.DecimeterToTheFourth }, + new object[] { AreaMomentOfInertiaUnit.FootToTheFourth }, + new object[] { AreaMomentOfInertiaUnit.InchToTheFourth }, + new object[] { AreaMomentOfInertiaUnit.MeterToTheFourth }, + new object[] { AreaMomentOfInertiaUnit.MillimeterToTheFourth }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -204,41 +229,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(AreaMomentOfInertiaUnit unit) { - var metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - - var centimetertothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.CentimeterToTheFourth); - AssertEx.EqualTolerance(CentimetersToTheFourthInOneMeterToTheFourth, (double)centimetertothefourthQuantity.Value, CentimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.CentimeterToTheFourth, centimetertothefourthQuantity.Unit); + var inBaseUnits = AreaMomentOfInertia.From(1.0, AreaMomentOfInertia.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var decimetertothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.DecimeterToTheFourth); - AssertEx.EqualTolerance(DecimetersToTheFourthInOneMeterToTheFourth, (double)decimetertothefourthQuantity.Value, DecimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.DecimeterToTheFourth, decimetertothefourthQuantity.Unit); - - var foottothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.FootToTheFourth); - AssertEx.EqualTolerance(FeetToTheFourthInOneMeterToTheFourth, (double)foottothefourthQuantity.Value, FeetToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.FootToTheFourth, foottothefourthQuantity.Unit); - - var inchtothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.InchToTheFourth); - AssertEx.EqualTolerance(InchesToTheFourthInOneMeterToTheFourth, (double)inchtothefourthQuantity.Value, InchesToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.InchToTheFourth, inchtothefourthQuantity.Unit); - - var metertothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth); - AssertEx.EqualTolerance(MetersToTheFourthInOneMeterToTheFourth, (double)metertothefourthQuantity.Value, MetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.MeterToTheFourth, metertothefourthQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var millimetertothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.MillimeterToTheFourth); - AssertEx.EqualTolerance(MillimetersToTheFourthInOneMeterToTheFourth, (double)millimetertothefourthQuantity.Value, MillimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.MillimeterToTheFourth, millimetertothefourthQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(AreaMomentOfInertiaUnit unit) + { + var quantity = AreaMomentOfInertia.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaMomentOfInertiaUnit unit) { - var quantityInBaseUnit = AreaMomentOfInertia.FromMetersToTheFourth(1).ToBaseUnit(); - Assert.Equal(AreaMomentOfInertia.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = AreaMomentOfInertia.Units.FirstOrDefault(u => u != AreaMomentOfInertia.BaseUnit && u != AreaMomentOfInertiaUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == AreaMomentOfInertiaUnit.Undefined) + fromUnit = AreaMomentOfInertia.BaseUnit; + + var quantity = AreaMomentOfInertia.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs index 0eeb5c8c8c..d77e8fbd30 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -69,6 +70,46 @@ public abstract partial class AreaTestsBase : QuantityTestsBase protected virtual double UsSurveySquareFeetTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AreaUnit unit) + { + return unit switch + { + AreaUnit.Acre => (AcresInOneSquareMeter, AcresTolerance), + AreaUnit.Hectare => (HectaresInOneSquareMeter, HectaresTolerance), + AreaUnit.SquareCentimeter => (SquareCentimetersInOneSquareMeter, SquareCentimetersTolerance), + AreaUnit.SquareDecimeter => (SquareDecimetersInOneSquareMeter, SquareDecimetersTolerance), + AreaUnit.SquareFoot => (SquareFeetInOneSquareMeter, SquareFeetTolerance), + AreaUnit.SquareInch => (SquareInchesInOneSquareMeter, SquareInchesTolerance), + AreaUnit.SquareKilometer => (SquareKilometersInOneSquareMeter, SquareKilometersTolerance), + AreaUnit.SquareMeter => (SquareMetersInOneSquareMeter, SquareMetersTolerance), + AreaUnit.SquareMicrometer => (SquareMicrometersInOneSquareMeter, SquareMicrometersTolerance), + AreaUnit.SquareMile => (SquareMilesInOneSquareMeter, SquareMilesTolerance), + AreaUnit.SquareMillimeter => (SquareMillimetersInOneSquareMeter, SquareMillimetersTolerance), + AreaUnit.SquareNauticalMile => (SquareNauticalMilesInOneSquareMeter, SquareNauticalMilesTolerance), + AreaUnit.SquareYard => (SquareYardsInOneSquareMeter, SquareYardsTolerance), + AreaUnit.UsSurveySquareFoot => (UsSurveySquareFeetInOneSquareMeter, UsSurveySquareFeetTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { AreaUnit.Acre }, + new object[] { AreaUnit.Hectare }, + new object[] { AreaUnit.SquareCentimeter }, + new object[] { AreaUnit.SquareDecimeter }, + new object[] { AreaUnit.SquareFoot }, + new object[] { AreaUnit.SquareInch }, + new object[] { AreaUnit.SquareKilometer }, + new object[] { AreaUnit.SquareMeter }, + new object[] { AreaUnit.SquareMicrometer }, + new object[] { AreaUnit.SquareMile }, + new object[] { AreaUnit.SquareMillimeter }, + new object[] { AreaUnit.SquareNauticalMile }, + new object[] { AreaUnit.SquareYard }, + new object[] { AreaUnit.UsSurveySquareFoot }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -268,73 +309,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(AreaUnit unit) { - var squaremeter = Area.FromSquareMeters(1); - - var acreQuantity = squaremeter.ToUnit(AreaUnit.Acre); - AssertEx.EqualTolerance(AcresInOneSquareMeter, (double)acreQuantity.Value, AcresTolerance); - Assert.Equal(AreaUnit.Acre, acreQuantity.Unit); - - var hectareQuantity = squaremeter.ToUnit(AreaUnit.Hectare); - AssertEx.EqualTolerance(HectaresInOneSquareMeter, (double)hectareQuantity.Value, HectaresTolerance); - Assert.Equal(AreaUnit.Hectare, hectareQuantity.Unit); - - var squarecentimeterQuantity = squaremeter.ToUnit(AreaUnit.SquareCentimeter); - AssertEx.EqualTolerance(SquareCentimetersInOneSquareMeter, (double)squarecentimeterQuantity.Value, SquareCentimetersTolerance); - Assert.Equal(AreaUnit.SquareCentimeter, squarecentimeterQuantity.Unit); - - var squaredecimeterQuantity = squaremeter.ToUnit(AreaUnit.SquareDecimeter); - AssertEx.EqualTolerance(SquareDecimetersInOneSquareMeter, (double)squaredecimeterQuantity.Value, SquareDecimetersTolerance); - Assert.Equal(AreaUnit.SquareDecimeter, squaredecimeterQuantity.Unit); - - var squarefootQuantity = squaremeter.ToUnit(AreaUnit.SquareFoot); - AssertEx.EqualTolerance(SquareFeetInOneSquareMeter, (double)squarefootQuantity.Value, SquareFeetTolerance); - Assert.Equal(AreaUnit.SquareFoot, squarefootQuantity.Unit); - - var squareinchQuantity = squaremeter.ToUnit(AreaUnit.SquareInch); - AssertEx.EqualTolerance(SquareInchesInOneSquareMeter, (double)squareinchQuantity.Value, SquareInchesTolerance); - Assert.Equal(AreaUnit.SquareInch, squareinchQuantity.Unit); - - var squarekilometerQuantity = squaremeter.ToUnit(AreaUnit.SquareKilometer); - AssertEx.EqualTolerance(SquareKilometersInOneSquareMeter, (double)squarekilometerQuantity.Value, SquareKilometersTolerance); - Assert.Equal(AreaUnit.SquareKilometer, squarekilometerQuantity.Unit); + var inBaseUnits = Area.From(1.0, Area.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var squaremeterQuantity = squaremeter.ToUnit(AreaUnit.SquareMeter); - AssertEx.EqualTolerance(SquareMetersInOneSquareMeter, (double)squaremeterQuantity.Value, SquareMetersTolerance); - Assert.Equal(AreaUnit.SquareMeter, squaremeterQuantity.Unit); - - var squaremicrometerQuantity = squaremeter.ToUnit(AreaUnit.SquareMicrometer); - AssertEx.EqualTolerance(SquareMicrometersInOneSquareMeter, (double)squaremicrometerQuantity.Value, SquareMicrometersTolerance); - Assert.Equal(AreaUnit.SquareMicrometer, squaremicrometerQuantity.Unit); - - var squaremileQuantity = squaremeter.ToUnit(AreaUnit.SquareMile); - AssertEx.EqualTolerance(SquareMilesInOneSquareMeter, (double)squaremileQuantity.Value, SquareMilesTolerance); - Assert.Equal(AreaUnit.SquareMile, squaremileQuantity.Unit); - - var squaremillimeterQuantity = squaremeter.ToUnit(AreaUnit.SquareMillimeter); - AssertEx.EqualTolerance(SquareMillimetersInOneSquareMeter, (double)squaremillimeterQuantity.Value, SquareMillimetersTolerance); - Assert.Equal(AreaUnit.SquareMillimeter, squaremillimeterQuantity.Unit); - - var squarenauticalmileQuantity = squaremeter.ToUnit(AreaUnit.SquareNauticalMile); - AssertEx.EqualTolerance(SquareNauticalMilesInOneSquareMeter, (double)squarenauticalmileQuantity.Value, SquareNauticalMilesTolerance); - Assert.Equal(AreaUnit.SquareNauticalMile, squarenauticalmileQuantity.Unit); - - var squareyardQuantity = squaremeter.ToUnit(AreaUnit.SquareYard); - AssertEx.EqualTolerance(SquareYardsInOneSquareMeter, (double)squareyardQuantity.Value, SquareYardsTolerance); - Assert.Equal(AreaUnit.SquareYard, squareyardQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var ussurveysquarefootQuantity = squaremeter.ToUnit(AreaUnit.UsSurveySquareFoot); - AssertEx.EqualTolerance(UsSurveySquareFeetInOneSquareMeter, (double)ussurveysquarefootQuantity.Value, UsSurveySquareFeetTolerance); - Assert.Equal(AreaUnit.UsSurveySquareFoot, ussurveysquarefootQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(AreaUnit unit) + { + var quantity = Area.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaUnit unit) { - var quantityInBaseUnit = Area.FromSquareMeters(1).ToBaseUnit(); - Assert.Equal(Area.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Area.Units.FirstOrDefault(u => u != Area.BaseUnit && u != AreaUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == AreaUnit.Undefined) + fromUnit = Area.BaseUnit; + + var quantity = Area.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs index dc91874b00..7b0d1ce275 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -93,6 +94,70 @@ public abstract partial class BitRateTestsBase : QuantityTestsBase protected virtual double TerabytesPerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(BitRateUnit unit) + { + return unit switch + { + BitRateUnit.BitPerSecond => (BitsPerSecondInOneBitPerSecond, BitsPerSecondTolerance), + BitRateUnit.BytePerSecond => (BytesPerSecondInOneBitPerSecond, BytesPerSecondTolerance), + BitRateUnit.ExabitPerSecond => (ExabitsPerSecondInOneBitPerSecond, ExabitsPerSecondTolerance), + BitRateUnit.ExabytePerSecond => (ExabytesPerSecondInOneBitPerSecond, ExabytesPerSecondTolerance), + BitRateUnit.ExbibitPerSecond => (ExbibitsPerSecondInOneBitPerSecond, ExbibitsPerSecondTolerance), + BitRateUnit.ExbibytePerSecond => (ExbibytesPerSecondInOneBitPerSecond, ExbibytesPerSecondTolerance), + BitRateUnit.GibibitPerSecond => (GibibitsPerSecondInOneBitPerSecond, GibibitsPerSecondTolerance), + BitRateUnit.GibibytePerSecond => (GibibytesPerSecondInOneBitPerSecond, GibibytesPerSecondTolerance), + BitRateUnit.GigabitPerSecond => (GigabitsPerSecondInOneBitPerSecond, GigabitsPerSecondTolerance), + BitRateUnit.GigabytePerSecond => (GigabytesPerSecondInOneBitPerSecond, GigabytesPerSecondTolerance), + BitRateUnit.KibibitPerSecond => (KibibitsPerSecondInOneBitPerSecond, KibibitsPerSecondTolerance), + BitRateUnit.KibibytePerSecond => (KibibytesPerSecondInOneBitPerSecond, KibibytesPerSecondTolerance), + BitRateUnit.KilobitPerSecond => (KilobitsPerSecondInOneBitPerSecond, KilobitsPerSecondTolerance), + BitRateUnit.KilobytePerSecond => (KilobytesPerSecondInOneBitPerSecond, KilobytesPerSecondTolerance), + BitRateUnit.MebibitPerSecond => (MebibitsPerSecondInOneBitPerSecond, MebibitsPerSecondTolerance), + BitRateUnit.MebibytePerSecond => (MebibytesPerSecondInOneBitPerSecond, MebibytesPerSecondTolerance), + BitRateUnit.MegabitPerSecond => (MegabitsPerSecondInOneBitPerSecond, MegabitsPerSecondTolerance), + BitRateUnit.MegabytePerSecond => (MegabytesPerSecondInOneBitPerSecond, MegabytesPerSecondTolerance), + BitRateUnit.PebibitPerSecond => (PebibitsPerSecondInOneBitPerSecond, PebibitsPerSecondTolerance), + BitRateUnit.PebibytePerSecond => (PebibytesPerSecondInOneBitPerSecond, PebibytesPerSecondTolerance), + BitRateUnit.PetabitPerSecond => (PetabitsPerSecondInOneBitPerSecond, PetabitsPerSecondTolerance), + BitRateUnit.PetabytePerSecond => (PetabytesPerSecondInOneBitPerSecond, PetabytesPerSecondTolerance), + BitRateUnit.TebibitPerSecond => (TebibitsPerSecondInOneBitPerSecond, TebibitsPerSecondTolerance), + BitRateUnit.TebibytePerSecond => (TebibytesPerSecondInOneBitPerSecond, TebibytesPerSecondTolerance), + BitRateUnit.TerabitPerSecond => (TerabitsPerSecondInOneBitPerSecond, TerabitsPerSecondTolerance), + BitRateUnit.TerabytePerSecond => (TerabytesPerSecondInOneBitPerSecond, TerabytesPerSecondTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { BitRateUnit.BitPerSecond }, + new object[] { BitRateUnit.BytePerSecond }, + new object[] { BitRateUnit.ExabitPerSecond }, + new object[] { BitRateUnit.ExabytePerSecond }, + new object[] { BitRateUnit.ExbibitPerSecond }, + new object[] { BitRateUnit.ExbibytePerSecond }, + new object[] { BitRateUnit.GibibitPerSecond }, + new object[] { BitRateUnit.GibibytePerSecond }, + new object[] { BitRateUnit.GigabitPerSecond }, + new object[] { BitRateUnit.GigabytePerSecond }, + new object[] { BitRateUnit.KibibitPerSecond }, + new object[] { BitRateUnit.KibibytePerSecond }, + new object[] { BitRateUnit.KilobitPerSecond }, + new object[] { BitRateUnit.KilobytePerSecond }, + new object[] { BitRateUnit.MebibitPerSecond }, + new object[] { BitRateUnit.MebibytePerSecond }, + new object[] { BitRateUnit.MegabitPerSecond }, + new object[] { BitRateUnit.MegabytePerSecond }, + new object[] { BitRateUnit.PebibitPerSecond }, + new object[] { BitRateUnit.PebibytePerSecond }, + new object[] { BitRateUnit.PetabitPerSecond }, + new object[] { BitRateUnit.PetabytePerSecond }, + new object[] { BitRateUnit.TebibitPerSecond }, + new object[] { BitRateUnit.TebibytePerSecond }, + new object[] { BitRateUnit.TerabitPerSecond }, + new object[] { BitRateUnit.TerabytePerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -339,121 +404,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(BitRateUnit unit) { - var bitpersecond = BitRate.FromBitsPerSecond(1); - - var bitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.BitPerSecond); - AssertEx.EqualTolerance(BitsPerSecondInOneBitPerSecond, (double)bitpersecondQuantity.Value, BitsPerSecondTolerance); - Assert.Equal(BitRateUnit.BitPerSecond, bitpersecondQuantity.Unit); - - var bytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.BytePerSecond); - AssertEx.EqualTolerance(BytesPerSecondInOneBitPerSecond, (double)bytepersecondQuantity.Value, BytesPerSecondTolerance); - Assert.Equal(BitRateUnit.BytePerSecond, bytepersecondQuantity.Unit); - - var exabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.ExabitPerSecond); - AssertEx.EqualTolerance(ExabitsPerSecondInOneBitPerSecond, (double)exabitpersecondQuantity.Value, ExabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabitPerSecond, exabitpersecondQuantity.Unit); - - var exabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.ExabytePerSecond); - AssertEx.EqualTolerance(ExabytesPerSecondInOneBitPerSecond, (double)exabytepersecondQuantity.Value, ExabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabytePerSecond, exabytepersecondQuantity.Unit); - - var exbibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.ExbibitPerSecond); - AssertEx.EqualTolerance(ExbibitsPerSecondInOneBitPerSecond, (double)exbibitpersecondQuantity.Value, ExbibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibitPerSecond, exbibitpersecondQuantity.Unit); - - var exbibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.ExbibytePerSecond); - AssertEx.EqualTolerance(ExbibytesPerSecondInOneBitPerSecond, (double)exbibytepersecondQuantity.Value, ExbibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibytePerSecond, exbibytepersecondQuantity.Unit); - - var gibibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.GibibitPerSecond); - AssertEx.EqualTolerance(GibibitsPerSecondInOneBitPerSecond, (double)gibibitpersecondQuantity.Value, GibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibitPerSecond, gibibitpersecondQuantity.Unit); - - var gibibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.GibibytePerSecond); - AssertEx.EqualTolerance(GibibytesPerSecondInOneBitPerSecond, (double)gibibytepersecondQuantity.Value, GibibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibytePerSecond, gibibytepersecondQuantity.Unit); - - var gigabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.GigabitPerSecond); - AssertEx.EqualTolerance(GigabitsPerSecondInOneBitPerSecond, (double)gigabitpersecondQuantity.Value, GigabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabitPerSecond, gigabitpersecondQuantity.Unit); - - var gigabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.GigabytePerSecond); - AssertEx.EqualTolerance(GigabytesPerSecondInOneBitPerSecond, (double)gigabytepersecondQuantity.Value, GigabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabytePerSecond, gigabytepersecondQuantity.Unit); - - var kibibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.KibibitPerSecond); - AssertEx.EqualTolerance(KibibitsPerSecondInOneBitPerSecond, (double)kibibitpersecondQuantity.Value, KibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibitPerSecond, kibibitpersecondQuantity.Unit); - - var kibibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.KibibytePerSecond); - AssertEx.EqualTolerance(KibibytesPerSecondInOneBitPerSecond, (double)kibibytepersecondQuantity.Value, KibibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibytePerSecond, kibibytepersecondQuantity.Unit); - - var kilobitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.KilobitPerSecond); - AssertEx.EqualTolerance(KilobitsPerSecondInOneBitPerSecond, (double)kilobitpersecondQuantity.Value, KilobitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobitPerSecond, kilobitpersecondQuantity.Unit); + var inBaseUnits = BitRate.From(1.0, BitRate.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilobytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.KilobytePerSecond); - AssertEx.EqualTolerance(KilobytesPerSecondInOneBitPerSecond, (double)kilobytepersecondQuantity.Value, KilobytesPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobytePerSecond, kilobytepersecondQuantity.Unit); - - var mebibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.MebibitPerSecond); - AssertEx.EqualTolerance(MebibitsPerSecondInOneBitPerSecond, (double)mebibitpersecondQuantity.Value, MebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibitPerSecond, mebibitpersecondQuantity.Unit); - - var mebibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.MebibytePerSecond); - AssertEx.EqualTolerance(MebibytesPerSecondInOneBitPerSecond, (double)mebibytepersecondQuantity.Value, MebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibytePerSecond, mebibytepersecondQuantity.Unit); - - var megabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.MegabitPerSecond); - AssertEx.EqualTolerance(MegabitsPerSecondInOneBitPerSecond, (double)megabitpersecondQuantity.Value, MegabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabitPerSecond, megabitpersecondQuantity.Unit); - - var megabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.MegabytePerSecond); - AssertEx.EqualTolerance(MegabytesPerSecondInOneBitPerSecond, (double)megabytepersecondQuantity.Value, MegabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabytePerSecond, megabytepersecondQuantity.Unit); - - var pebibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.PebibitPerSecond); - AssertEx.EqualTolerance(PebibitsPerSecondInOneBitPerSecond, (double)pebibitpersecondQuantity.Value, PebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibitPerSecond, pebibitpersecondQuantity.Unit); - - var pebibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.PebibytePerSecond); - AssertEx.EqualTolerance(PebibytesPerSecondInOneBitPerSecond, (double)pebibytepersecondQuantity.Value, PebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibytePerSecond, pebibytepersecondQuantity.Unit); - - var petabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.PetabitPerSecond); - AssertEx.EqualTolerance(PetabitsPerSecondInOneBitPerSecond, (double)petabitpersecondQuantity.Value, PetabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabitPerSecond, petabitpersecondQuantity.Unit); - - var petabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.PetabytePerSecond); - AssertEx.EqualTolerance(PetabytesPerSecondInOneBitPerSecond, (double)petabytepersecondQuantity.Value, PetabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabytePerSecond, petabytepersecondQuantity.Unit); - - var tebibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.TebibitPerSecond); - AssertEx.EqualTolerance(TebibitsPerSecondInOneBitPerSecond, (double)tebibitpersecondQuantity.Value, TebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibitPerSecond, tebibitpersecondQuantity.Unit); - - var tebibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.TebibytePerSecond); - AssertEx.EqualTolerance(TebibytesPerSecondInOneBitPerSecond, (double)tebibytepersecondQuantity.Value, TebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibytePerSecond, tebibytepersecondQuantity.Unit); - - var terabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.TerabitPerSecond); - AssertEx.EqualTolerance(TerabitsPerSecondInOneBitPerSecond, (double)terabitpersecondQuantity.Value, TerabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabitPerSecond, terabitpersecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var terabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.TerabytePerSecond); - AssertEx.EqualTolerance(TerabytesPerSecondInOneBitPerSecond, (double)terabytepersecondQuantity.Value, TerabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabytePerSecond, terabytepersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(BitRateUnit unit) + { + var quantity = BitRate.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(BitRateUnit unit) { - var quantityInBaseUnit = BitRate.FromBitsPerSecond(1).ToBaseUnit(); - Assert.Equal(BitRate.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = BitRate.Units.FirstOrDefault(u => u != BitRate.BaseUnit && u != BitRateUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == BitRateUnit.Undefined) + fromUnit = BitRate.BaseUnit; + + var quantity = BitRate.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs index e7f822ff7f..cdbd7f043f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class BrakeSpecificFuelConsumptionTestsBase : QuantityTe protected virtual double PoundsPerMechanicalHorsepowerHourTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(BrakeSpecificFuelConsumptionUnit unit) + { + return unit switch + { + BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour => (GramsPerKiloWattHourInOneKilogramPerJoule, GramsPerKiloWattHourTolerance), + BrakeSpecificFuelConsumptionUnit.KilogramPerJoule => (KilogramsPerJouleInOneKilogramPerJoule, KilogramsPerJouleTolerance), + BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour => (PoundsPerMechanicalHorsepowerHourInOneKilogramPerJoule, PoundsPerMechanicalHorsepowerHourTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour }, + new object[] { BrakeSpecificFuelConsumptionUnit.KilogramPerJoule }, + new object[] { BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(BrakeSpecificFuelConsumptionUnit unit) { - var kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); + var inBaseUnits = BrakeSpecificFuelConsumption.From(1.0, BrakeSpecificFuelConsumption.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var gramperkilowatthourQuantity = kilogramperjoule.ToUnit(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); - AssertEx.EqualTolerance(GramsPerKiloWattHourInOneKilogramPerJoule, (double)gramperkilowatthourQuantity.Value, GramsPerKiloWattHourTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, gramperkilowatthourQuantity.Unit); - - var kilogramperjouleQuantity = kilogramperjoule.ToUnit(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - AssertEx.EqualTolerance(KilogramsPerJouleInOneKilogramPerJoule, (double)kilogramperjouleQuantity.Value, KilogramsPerJouleTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, kilogramperjouleQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var poundpermechanicalhorsepowerhourQuantity = kilogramperjoule.ToUnit(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); - AssertEx.EqualTolerance(PoundsPerMechanicalHorsepowerHourInOneKilogramPerJoule, (double)poundpermechanicalhorsepowerhourQuantity.Value, PoundsPerMechanicalHorsepowerHourTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, poundpermechanicalhorsepowerhourQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(BrakeSpecificFuelConsumptionUnit unit) + { + var quantity = BrakeSpecificFuelConsumption.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(BrakeSpecificFuelConsumptionUnit unit) { - var quantityInBaseUnit = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1).ToBaseUnit(); - Assert.Equal(BrakeSpecificFuelConsumption.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = BrakeSpecificFuelConsumption.Units.FirstOrDefault(u => u != BrakeSpecificFuelConsumption.BaseUnit && u != BrakeSpecificFuelConsumptionUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == BrakeSpecificFuelConsumptionUnit.Undefined) + fromUnit = BrakeSpecificFuelConsumption.BaseUnit; + + var quantity = BrakeSpecificFuelConsumption.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs index 644c0edda3..d6dc3c5031 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -55,6 +56,32 @@ public abstract partial class CapacitanceTestsBase : QuantityTestsBase protected virtual double PicofaradsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(CapacitanceUnit unit) + { + return unit switch + { + CapacitanceUnit.Farad => (FaradsInOneFarad, FaradsTolerance), + CapacitanceUnit.Kilofarad => (KilofaradsInOneFarad, KilofaradsTolerance), + CapacitanceUnit.Megafarad => (MegafaradsInOneFarad, MegafaradsTolerance), + CapacitanceUnit.Microfarad => (MicrofaradsInOneFarad, MicrofaradsTolerance), + CapacitanceUnit.Millifarad => (MillifaradsInOneFarad, MillifaradsTolerance), + CapacitanceUnit.Nanofarad => (NanofaradsInOneFarad, NanofaradsTolerance), + CapacitanceUnit.Picofarad => (PicofaradsInOneFarad, PicofaradsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { CapacitanceUnit.Farad }, + new object[] { CapacitanceUnit.Kilofarad }, + new object[] { CapacitanceUnit.Megafarad }, + new object[] { CapacitanceUnit.Microfarad }, + new object[] { CapacitanceUnit.Millifarad }, + new object[] { CapacitanceUnit.Nanofarad }, + new object[] { CapacitanceUnit.Picofarad }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -212,45 +239,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(CapacitanceUnit unit) { - var farad = Capacitance.FromFarads(1); - - var faradQuantity = farad.ToUnit(CapacitanceUnit.Farad); - AssertEx.EqualTolerance(FaradsInOneFarad, (double)faradQuantity.Value, FaradsTolerance); - Assert.Equal(CapacitanceUnit.Farad, faradQuantity.Unit); - - var kilofaradQuantity = farad.ToUnit(CapacitanceUnit.Kilofarad); - AssertEx.EqualTolerance(KilofaradsInOneFarad, (double)kilofaradQuantity.Value, KilofaradsTolerance); - Assert.Equal(CapacitanceUnit.Kilofarad, kilofaradQuantity.Unit); + var inBaseUnits = Capacitance.From(1.0, Capacitance.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megafaradQuantity = farad.ToUnit(CapacitanceUnit.Megafarad); - AssertEx.EqualTolerance(MegafaradsInOneFarad, (double)megafaradQuantity.Value, MegafaradsTolerance); - Assert.Equal(CapacitanceUnit.Megafarad, megafaradQuantity.Unit); - - var microfaradQuantity = farad.ToUnit(CapacitanceUnit.Microfarad); - AssertEx.EqualTolerance(MicrofaradsInOneFarad, (double)microfaradQuantity.Value, MicrofaradsTolerance); - Assert.Equal(CapacitanceUnit.Microfarad, microfaradQuantity.Unit); - - var millifaradQuantity = farad.ToUnit(CapacitanceUnit.Millifarad); - AssertEx.EqualTolerance(MillifaradsInOneFarad, (double)millifaradQuantity.Value, MillifaradsTolerance); - Assert.Equal(CapacitanceUnit.Millifarad, millifaradQuantity.Unit); - - var nanofaradQuantity = farad.ToUnit(CapacitanceUnit.Nanofarad); - AssertEx.EqualTolerance(NanofaradsInOneFarad, (double)nanofaradQuantity.Value, NanofaradsTolerance); - Assert.Equal(CapacitanceUnit.Nanofarad, nanofaradQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var picofaradQuantity = farad.ToUnit(CapacitanceUnit.Picofarad); - AssertEx.EqualTolerance(PicofaradsInOneFarad, (double)picofaradQuantity.Value, PicofaradsTolerance); - Assert.Equal(CapacitanceUnit.Picofarad, picofaradQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(CapacitanceUnit unit) + { + var quantity = Capacitance.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CapacitanceUnit unit) { - var quantityInBaseUnit = Capacitance.FromFarads(1).ToBaseUnit(); - Assert.Equal(Capacitance.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Capacitance.Units.FirstOrDefault(u => u != Capacitance.BaseUnit && u != CapacitanceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == CapacitanceUnit.Undefined) + fromUnit = Capacitance.BaseUnit; + + var quantity = Capacitance.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs index a760f56fc7..b0ac487406 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class CoefficientOfThermalExpansionTestsBase : QuantityT protected virtual double InverseKelvinTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(CoefficientOfThermalExpansionUnit unit) + { + return unit switch + { + CoefficientOfThermalExpansionUnit.InverseDegreeCelsius => (InverseDegreeCelsiusInOneInverseKelvin, InverseDegreeCelsiusTolerance), + CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit => (InverseDegreeFahrenheitInOneInverseKelvin, InverseDegreeFahrenheitTolerance), + CoefficientOfThermalExpansionUnit.InverseKelvin => (InverseKelvinInOneInverseKelvin, InverseKelvinTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { CoefficientOfThermalExpansionUnit.InverseDegreeCelsius }, + new object[] { CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit }, + new object[] { CoefficientOfThermalExpansionUnit.InverseKelvin }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(CoefficientOfThermalExpansionUnit unit) { - var inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); + var inBaseUnits = CoefficientOfThermalExpansion.From(1.0, CoefficientOfThermalExpansion.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var inversedegreecelsiusQuantity = inversekelvin.ToUnit(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); - AssertEx.EqualTolerance(InverseDegreeCelsiusInOneInverseKelvin, (double)inversedegreecelsiusQuantity.Value, InverseDegreeCelsiusTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, inversedegreecelsiusQuantity.Unit); - - var inversedegreefahrenheitQuantity = inversekelvin.ToUnit(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); - AssertEx.EqualTolerance(InverseDegreeFahrenheitInOneInverseKelvin, (double)inversedegreefahrenheitQuantity.Value, InverseDegreeFahrenheitTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, inversedegreefahrenheitQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var inversekelvinQuantity = inversekelvin.ToUnit(CoefficientOfThermalExpansionUnit.InverseKelvin); - AssertEx.EqualTolerance(InverseKelvinInOneInverseKelvin, (double)inversekelvinQuantity.Value, InverseKelvinTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.InverseKelvin, inversekelvinQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(CoefficientOfThermalExpansionUnit unit) + { + var quantity = CoefficientOfThermalExpansion.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CoefficientOfThermalExpansionUnit unit) { - var quantityInBaseUnit = CoefficientOfThermalExpansion.FromInverseKelvin(1).ToBaseUnit(); - Assert.Equal(CoefficientOfThermalExpansion.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = CoefficientOfThermalExpansion.Units.FirstOrDefault(u => u != CoefficientOfThermalExpansion.BaseUnit && u != CoefficientOfThermalExpansionUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == CoefficientOfThermalExpansionUnit.Undefined) + fromUnit = CoefficientOfThermalExpansion.BaseUnit; + + var quantity = CoefficientOfThermalExpansion.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs index b7bc23a8f1..c7643f3540 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -143,6 +144,120 @@ public abstract partial class DensityTestsBase : QuantityTestsBase protected virtual double TonnesPerCubicMillimeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(DensityUnit unit) + { + return unit switch + { + DensityUnit.CentigramPerDeciliter => (CentigramsPerDeciLiterInOneKilogramPerCubicMeter, CentigramsPerDeciLiterTolerance), + DensityUnit.CentigramPerLiter => (CentigramsPerLiterInOneKilogramPerCubicMeter, CentigramsPerLiterTolerance), + DensityUnit.CentigramPerMilliliter => (CentigramsPerMilliliterInOneKilogramPerCubicMeter, CentigramsPerMilliliterTolerance), + DensityUnit.DecigramPerDeciliter => (DecigramsPerDeciLiterInOneKilogramPerCubicMeter, DecigramsPerDeciLiterTolerance), + DensityUnit.DecigramPerLiter => (DecigramsPerLiterInOneKilogramPerCubicMeter, DecigramsPerLiterTolerance), + DensityUnit.DecigramPerMilliliter => (DecigramsPerMilliliterInOneKilogramPerCubicMeter, DecigramsPerMilliliterTolerance), + DensityUnit.GramPerCubicCentimeter => (GramsPerCubicCentimeterInOneKilogramPerCubicMeter, GramsPerCubicCentimeterTolerance), + DensityUnit.GramPerCubicFoot => (GramsPerCubicFootInOneKilogramPerCubicMeter, GramsPerCubicFootTolerance), + DensityUnit.GramPerCubicInch => (GramsPerCubicInchInOneKilogramPerCubicMeter, GramsPerCubicInchTolerance), + DensityUnit.GramPerCubicMeter => (GramsPerCubicMeterInOneKilogramPerCubicMeter, GramsPerCubicMeterTolerance), + DensityUnit.GramPerCubicMillimeter => (GramsPerCubicMillimeterInOneKilogramPerCubicMeter, GramsPerCubicMillimeterTolerance), + DensityUnit.GramPerDeciliter => (GramsPerDeciLiterInOneKilogramPerCubicMeter, GramsPerDeciLiterTolerance), + DensityUnit.GramPerLiter => (GramsPerLiterInOneKilogramPerCubicMeter, GramsPerLiterTolerance), + DensityUnit.GramPerMilliliter => (GramsPerMilliliterInOneKilogramPerCubicMeter, GramsPerMilliliterTolerance), + DensityUnit.KilogramPerCubicCentimeter => (KilogramsPerCubicCentimeterInOneKilogramPerCubicMeter, KilogramsPerCubicCentimeterTolerance), + DensityUnit.KilogramPerCubicMeter => (KilogramsPerCubicMeterInOneKilogramPerCubicMeter, KilogramsPerCubicMeterTolerance), + DensityUnit.KilogramPerCubicMillimeter => (KilogramsPerCubicMillimeterInOneKilogramPerCubicMeter, KilogramsPerCubicMillimeterTolerance), + DensityUnit.KilogramPerLiter => (KilogramsPerLiterInOneKilogramPerCubicMeter, KilogramsPerLiterTolerance), + DensityUnit.KilopoundPerCubicFoot => (KilopoundsPerCubicFootInOneKilogramPerCubicMeter, KilopoundsPerCubicFootTolerance), + DensityUnit.KilopoundPerCubicInch => (KilopoundsPerCubicInchInOneKilogramPerCubicMeter, KilopoundsPerCubicInchTolerance), + DensityUnit.MicrogramPerCubicMeter => (MicrogramsPerCubicMeterInOneKilogramPerCubicMeter, MicrogramsPerCubicMeterTolerance), + DensityUnit.MicrogramPerDeciliter => (MicrogramsPerDeciLiterInOneKilogramPerCubicMeter, MicrogramsPerDeciLiterTolerance), + DensityUnit.MicrogramPerLiter => (MicrogramsPerLiterInOneKilogramPerCubicMeter, MicrogramsPerLiterTolerance), + DensityUnit.MicrogramPerMilliliter => (MicrogramsPerMilliliterInOneKilogramPerCubicMeter, MicrogramsPerMilliliterTolerance), + DensityUnit.MilligramPerCubicMeter => (MilligramsPerCubicMeterInOneKilogramPerCubicMeter, MilligramsPerCubicMeterTolerance), + DensityUnit.MilligramPerDeciliter => (MilligramsPerDeciLiterInOneKilogramPerCubicMeter, MilligramsPerDeciLiterTolerance), + DensityUnit.MilligramPerLiter => (MilligramsPerLiterInOneKilogramPerCubicMeter, MilligramsPerLiterTolerance), + DensityUnit.MilligramPerMilliliter => (MilligramsPerMilliliterInOneKilogramPerCubicMeter, MilligramsPerMilliliterTolerance), + DensityUnit.NanogramPerDeciliter => (NanogramsPerDeciLiterInOneKilogramPerCubicMeter, NanogramsPerDeciLiterTolerance), + DensityUnit.NanogramPerLiter => (NanogramsPerLiterInOneKilogramPerCubicMeter, NanogramsPerLiterTolerance), + DensityUnit.NanogramPerMilliliter => (NanogramsPerMilliliterInOneKilogramPerCubicMeter, NanogramsPerMilliliterTolerance), + DensityUnit.PicogramPerDeciliter => (PicogramsPerDeciLiterInOneKilogramPerCubicMeter, PicogramsPerDeciLiterTolerance), + DensityUnit.PicogramPerLiter => (PicogramsPerLiterInOneKilogramPerCubicMeter, PicogramsPerLiterTolerance), + DensityUnit.PicogramPerMilliliter => (PicogramsPerMilliliterInOneKilogramPerCubicMeter, PicogramsPerMilliliterTolerance), + DensityUnit.PoundPerCubicCentimeter => (PoundsPerCubicCentimeterInOneKilogramPerCubicMeter, PoundsPerCubicCentimeterTolerance), + DensityUnit.PoundPerCubicFoot => (PoundsPerCubicFootInOneKilogramPerCubicMeter, PoundsPerCubicFootTolerance), + DensityUnit.PoundPerCubicInch => (PoundsPerCubicInchInOneKilogramPerCubicMeter, PoundsPerCubicInchTolerance), + DensityUnit.PoundPerCubicMeter => (PoundsPerCubicMeterInOneKilogramPerCubicMeter, PoundsPerCubicMeterTolerance), + DensityUnit.PoundPerCubicMillimeter => (PoundsPerCubicMillimeterInOneKilogramPerCubicMeter, PoundsPerCubicMillimeterTolerance), + DensityUnit.PoundPerImperialGallon => (PoundsPerImperialGallonInOneKilogramPerCubicMeter, PoundsPerImperialGallonTolerance), + DensityUnit.PoundPerUSGallon => (PoundsPerUSGallonInOneKilogramPerCubicMeter, PoundsPerUSGallonTolerance), + DensityUnit.SlugPerCubicCentimeter => (SlugsPerCubicCentimeterInOneKilogramPerCubicMeter, SlugsPerCubicCentimeterTolerance), + DensityUnit.SlugPerCubicFoot => (SlugsPerCubicFootInOneKilogramPerCubicMeter, SlugsPerCubicFootTolerance), + DensityUnit.SlugPerCubicInch => (SlugsPerCubicInchInOneKilogramPerCubicMeter, SlugsPerCubicInchTolerance), + DensityUnit.SlugPerCubicMeter => (SlugsPerCubicMeterInOneKilogramPerCubicMeter, SlugsPerCubicMeterTolerance), + DensityUnit.SlugPerCubicMillimeter => (SlugsPerCubicMillimeterInOneKilogramPerCubicMeter, SlugsPerCubicMillimeterTolerance), + DensityUnit.TonnePerCubicCentimeter => (TonnesPerCubicCentimeterInOneKilogramPerCubicMeter, TonnesPerCubicCentimeterTolerance), + DensityUnit.TonnePerCubicFoot => (TonnesPerCubicFootInOneKilogramPerCubicMeter, TonnesPerCubicFootTolerance), + DensityUnit.TonnePerCubicInch => (TonnesPerCubicInchInOneKilogramPerCubicMeter, TonnesPerCubicInchTolerance), + DensityUnit.TonnePerCubicMeter => (TonnesPerCubicMeterInOneKilogramPerCubicMeter, TonnesPerCubicMeterTolerance), + DensityUnit.TonnePerCubicMillimeter => (TonnesPerCubicMillimeterInOneKilogramPerCubicMeter, TonnesPerCubicMillimeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { DensityUnit.CentigramPerDeciliter }, + new object[] { DensityUnit.CentigramPerLiter }, + new object[] { DensityUnit.CentigramPerMilliliter }, + new object[] { DensityUnit.DecigramPerDeciliter }, + new object[] { DensityUnit.DecigramPerLiter }, + new object[] { DensityUnit.DecigramPerMilliliter }, + new object[] { DensityUnit.GramPerCubicCentimeter }, + new object[] { DensityUnit.GramPerCubicFoot }, + new object[] { DensityUnit.GramPerCubicInch }, + new object[] { DensityUnit.GramPerCubicMeter }, + new object[] { DensityUnit.GramPerCubicMillimeter }, + new object[] { DensityUnit.GramPerDeciliter }, + new object[] { DensityUnit.GramPerLiter }, + new object[] { DensityUnit.GramPerMilliliter }, + new object[] { DensityUnit.KilogramPerCubicCentimeter }, + new object[] { DensityUnit.KilogramPerCubicMeter }, + new object[] { DensityUnit.KilogramPerCubicMillimeter }, + new object[] { DensityUnit.KilogramPerLiter }, + new object[] { DensityUnit.KilopoundPerCubicFoot }, + new object[] { DensityUnit.KilopoundPerCubicInch }, + new object[] { DensityUnit.MicrogramPerCubicMeter }, + new object[] { DensityUnit.MicrogramPerDeciliter }, + new object[] { DensityUnit.MicrogramPerLiter }, + new object[] { DensityUnit.MicrogramPerMilliliter }, + new object[] { DensityUnit.MilligramPerCubicMeter }, + new object[] { DensityUnit.MilligramPerDeciliter }, + new object[] { DensityUnit.MilligramPerLiter }, + new object[] { DensityUnit.MilligramPerMilliliter }, + new object[] { DensityUnit.NanogramPerDeciliter }, + new object[] { DensityUnit.NanogramPerLiter }, + new object[] { DensityUnit.NanogramPerMilliliter }, + new object[] { DensityUnit.PicogramPerDeciliter }, + new object[] { DensityUnit.PicogramPerLiter }, + new object[] { DensityUnit.PicogramPerMilliliter }, + new object[] { DensityUnit.PoundPerCubicCentimeter }, + new object[] { DensityUnit.PoundPerCubicFoot }, + new object[] { DensityUnit.PoundPerCubicInch }, + new object[] { DensityUnit.PoundPerCubicMeter }, + new object[] { DensityUnit.PoundPerCubicMillimeter }, + new object[] { DensityUnit.PoundPerImperialGallon }, + new object[] { DensityUnit.PoundPerUSGallon }, + new object[] { DensityUnit.SlugPerCubicCentimeter }, + new object[] { DensityUnit.SlugPerCubicFoot }, + new object[] { DensityUnit.SlugPerCubicInch }, + new object[] { DensityUnit.SlugPerCubicMeter }, + new object[] { DensityUnit.SlugPerCubicMillimeter }, + new object[] { DensityUnit.TonnePerCubicCentimeter }, + new object[] { DensityUnit.TonnePerCubicFoot }, + new object[] { DensityUnit.TonnePerCubicInch }, + new object[] { DensityUnit.TonnePerCubicMeter }, + new object[] { DensityUnit.TonnePerCubicMillimeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -564,221 +679,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(DensityUnit unit) { - var kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - - var centigramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.CentigramPerDeciliter); - AssertEx.EqualTolerance(CentigramsPerDeciLiterInOneKilogramPerCubicMeter, (double)centigramperdeciliterQuantity.Value, CentigramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.CentigramPerDeciliter, centigramperdeciliterQuantity.Unit); - - var centigramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.CentigramPerLiter); - AssertEx.EqualTolerance(CentigramsPerLiterInOneKilogramPerCubicMeter, (double)centigramperliterQuantity.Value, CentigramsPerLiterTolerance); - Assert.Equal(DensityUnit.CentigramPerLiter, centigramperliterQuantity.Unit); - - var centigrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.CentigramPerMilliliter); - AssertEx.EqualTolerance(CentigramsPerMilliliterInOneKilogramPerCubicMeter, (double)centigrampermilliliterQuantity.Value, CentigramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.CentigramPerMilliliter, centigrampermilliliterQuantity.Unit); - - var decigramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.DecigramPerDeciliter); - AssertEx.EqualTolerance(DecigramsPerDeciLiterInOneKilogramPerCubicMeter, (double)decigramperdeciliterQuantity.Value, DecigramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.DecigramPerDeciliter, decigramperdeciliterQuantity.Unit); - - var decigramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.DecigramPerLiter); - AssertEx.EqualTolerance(DecigramsPerLiterInOneKilogramPerCubicMeter, (double)decigramperliterQuantity.Value, DecigramsPerLiterTolerance); - Assert.Equal(DensityUnit.DecigramPerLiter, decigramperliterQuantity.Unit); - - var decigrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.DecigramPerMilliliter); - AssertEx.EqualTolerance(DecigramsPerMilliliterInOneKilogramPerCubicMeter, (double)decigrampermilliliterQuantity.Value, DecigramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.DecigramPerMilliliter, decigrampermilliliterQuantity.Unit); - - var grampercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerCubicCentimeter); - AssertEx.EqualTolerance(GramsPerCubicCentimeterInOneKilogramPerCubicMeter, (double)grampercubiccentimeterQuantity.Value, GramsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicCentimeter, grampercubiccentimeterQuantity.Unit); - - var grampercubicfootQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerCubicFoot); - AssertEx.EqualTolerance(GramsPerCubicFootInOneKilogramPerCubicMeter, (double)grampercubicfootQuantity.Value, GramsPerCubicFootTolerance); - Assert.Equal(DensityUnit.GramPerCubicFoot, grampercubicfootQuantity.Unit); - - var grampercubicinchQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerCubicInch); - AssertEx.EqualTolerance(GramsPerCubicInchInOneKilogramPerCubicMeter, (double)grampercubicinchQuantity.Value, GramsPerCubicInchTolerance); - Assert.Equal(DensityUnit.GramPerCubicInch, grampercubicinchQuantity.Unit); - - var grampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerCubicMeter); - AssertEx.EqualTolerance(GramsPerCubicMeterInOneKilogramPerCubicMeter, (double)grampercubicmeterQuantity.Value, GramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMeter, grampercubicmeterQuantity.Unit); - - var grampercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerCubicMillimeter); - AssertEx.EqualTolerance(GramsPerCubicMillimeterInOneKilogramPerCubicMeter, (double)grampercubicmillimeterQuantity.Value, GramsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMillimeter, grampercubicmillimeterQuantity.Unit); - - var gramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerDeciliter); - AssertEx.EqualTolerance(GramsPerDeciLiterInOneKilogramPerCubicMeter, (double)gramperdeciliterQuantity.Value, GramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.GramPerDeciliter, gramperdeciliterQuantity.Unit); - - var gramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerLiter); - AssertEx.EqualTolerance(GramsPerLiterInOneKilogramPerCubicMeter, (double)gramperliterQuantity.Value, GramsPerLiterTolerance); - Assert.Equal(DensityUnit.GramPerLiter, gramperliterQuantity.Unit); - - var grampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerMilliliter); - AssertEx.EqualTolerance(GramsPerMilliliterInOneKilogramPerCubicMeter, (double)grampermilliliterQuantity.Value, GramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.GramPerMilliliter, grampermilliliterQuantity.Unit); - - var kilogrampercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilogramPerCubicCentimeter); - AssertEx.EqualTolerance(KilogramsPerCubicCentimeterInOneKilogramPerCubicMeter, (double)kilogrampercubiccentimeterQuantity.Value, KilogramsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicCentimeter, kilogrampercubiccentimeterQuantity.Unit); - - var kilogrampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilogramPerCubicMeter); - AssertEx.EqualTolerance(KilogramsPerCubicMeterInOneKilogramPerCubicMeter, (double)kilogrampercubicmeterQuantity.Value, KilogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMeter, kilogrampercubicmeterQuantity.Unit); - - var kilogrampercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilogramPerCubicMillimeter); - AssertEx.EqualTolerance(KilogramsPerCubicMillimeterInOneKilogramPerCubicMeter, (double)kilogrampercubicmillimeterQuantity.Value, KilogramsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMillimeter, kilogrampercubicmillimeterQuantity.Unit); - - var kilogramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilogramPerLiter); - AssertEx.EqualTolerance(KilogramsPerLiterInOneKilogramPerCubicMeter, (double)kilogramperliterQuantity.Value, KilogramsPerLiterTolerance); - Assert.Equal(DensityUnit.KilogramPerLiter, kilogramperliterQuantity.Unit); - - var kilopoundpercubicfootQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilopoundPerCubicFoot); - AssertEx.EqualTolerance(KilopoundsPerCubicFootInOneKilogramPerCubicMeter, (double)kilopoundpercubicfootQuantity.Value, KilopoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicFoot, kilopoundpercubicfootQuantity.Unit); - - var kilopoundpercubicinchQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilopoundPerCubicInch); - AssertEx.EqualTolerance(KilopoundsPerCubicInchInOneKilogramPerCubicMeter, (double)kilopoundpercubicinchQuantity.Value, KilopoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicInch, kilopoundpercubicinchQuantity.Unit); - - var microgrampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MicrogramPerCubicMeter); - AssertEx.EqualTolerance(MicrogramsPerCubicMeterInOneKilogramPerCubicMeter, (double)microgrampercubicmeterQuantity.Value, MicrogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MicrogramPerCubicMeter, microgrampercubicmeterQuantity.Unit); - - var microgramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MicrogramPerDeciliter); - AssertEx.EqualTolerance(MicrogramsPerDeciLiterInOneKilogramPerCubicMeter, (double)microgramperdeciliterQuantity.Value, MicrogramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.MicrogramPerDeciliter, microgramperdeciliterQuantity.Unit); - - var microgramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MicrogramPerLiter); - AssertEx.EqualTolerance(MicrogramsPerLiterInOneKilogramPerCubicMeter, (double)microgramperliterQuantity.Value, MicrogramsPerLiterTolerance); - Assert.Equal(DensityUnit.MicrogramPerLiter, microgramperliterQuantity.Unit); - - var microgrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MicrogramPerMilliliter); - AssertEx.EqualTolerance(MicrogramsPerMilliliterInOneKilogramPerCubicMeter, (double)microgrampermilliliterQuantity.Value, MicrogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.MicrogramPerMilliliter, microgrampermilliliterQuantity.Unit); + var inBaseUnits = Density.From(1.0, Density.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var milligrampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MilligramPerCubicMeter); - AssertEx.EqualTolerance(MilligramsPerCubicMeterInOneKilogramPerCubicMeter, (double)milligrampercubicmeterQuantity.Value, MilligramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MilligramPerCubicMeter, milligrampercubicmeterQuantity.Unit); - - var milligramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MilligramPerDeciliter); - AssertEx.EqualTolerance(MilligramsPerDeciLiterInOneKilogramPerCubicMeter, (double)milligramperdeciliterQuantity.Value, MilligramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.MilligramPerDeciliter, milligramperdeciliterQuantity.Unit); - - var milligramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MilligramPerLiter); - AssertEx.EqualTolerance(MilligramsPerLiterInOneKilogramPerCubicMeter, (double)milligramperliterQuantity.Value, MilligramsPerLiterTolerance); - Assert.Equal(DensityUnit.MilligramPerLiter, milligramperliterQuantity.Unit); - - var milligrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MilligramPerMilliliter); - AssertEx.EqualTolerance(MilligramsPerMilliliterInOneKilogramPerCubicMeter, (double)milligrampermilliliterQuantity.Value, MilligramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.MilligramPerMilliliter, milligrampermilliliterQuantity.Unit); - - var nanogramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.NanogramPerDeciliter); - AssertEx.EqualTolerance(NanogramsPerDeciLiterInOneKilogramPerCubicMeter, (double)nanogramperdeciliterQuantity.Value, NanogramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.NanogramPerDeciliter, nanogramperdeciliterQuantity.Unit); - - var nanogramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.NanogramPerLiter); - AssertEx.EqualTolerance(NanogramsPerLiterInOneKilogramPerCubicMeter, (double)nanogramperliterQuantity.Value, NanogramsPerLiterTolerance); - Assert.Equal(DensityUnit.NanogramPerLiter, nanogramperliterQuantity.Unit); - - var nanogrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.NanogramPerMilliliter); - AssertEx.EqualTolerance(NanogramsPerMilliliterInOneKilogramPerCubicMeter, (double)nanogrampermilliliterQuantity.Value, NanogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.NanogramPerMilliliter, nanogrampermilliliterQuantity.Unit); - - var picogramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PicogramPerDeciliter); - AssertEx.EqualTolerance(PicogramsPerDeciLiterInOneKilogramPerCubicMeter, (double)picogramperdeciliterQuantity.Value, PicogramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.PicogramPerDeciliter, picogramperdeciliterQuantity.Unit); - - var picogramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PicogramPerLiter); - AssertEx.EqualTolerance(PicogramsPerLiterInOneKilogramPerCubicMeter, (double)picogramperliterQuantity.Value, PicogramsPerLiterTolerance); - Assert.Equal(DensityUnit.PicogramPerLiter, picogramperliterQuantity.Unit); - - var picogrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PicogramPerMilliliter); - AssertEx.EqualTolerance(PicogramsPerMilliliterInOneKilogramPerCubicMeter, (double)picogrampermilliliterQuantity.Value, PicogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.PicogramPerMilliliter, picogrampermilliliterQuantity.Unit); - - var poundpercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerCubicCentimeter); - AssertEx.EqualTolerance(PoundsPerCubicCentimeterInOneKilogramPerCubicMeter, (double)poundpercubiccentimeterQuantity.Value, PoundsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicCentimeter, poundpercubiccentimeterQuantity.Unit); - - var poundpercubicfootQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerCubicFoot); - AssertEx.EqualTolerance(PoundsPerCubicFootInOneKilogramPerCubicMeter, (double)poundpercubicfootQuantity.Value, PoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.PoundPerCubicFoot, poundpercubicfootQuantity.Unit); - - var poundpercubicinchQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerCubicInch); - AssertEx.EqualTolerance(PoundsPerCubicInchInOneKilogramPerCubicMeter, (double)poundpercubicinchQuantity.Value, PoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.PoundPerCubicInch, poundpercubicinchQuantity.Unit); - - var poundpercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerCubicMeter); - AssertEx.EqualTolerance(PoundsPerCubicMeterInOneKilogramPerCubicMeter, (double)poundpercubicmeterQuantity.Value, PoundsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMeter, poundpercubicmeterQuantity.Unit); - - var poundpercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerCubicMillimeter); - AssertEx.EqualTolerance(PoundsPerCubicMillimeterInOneKilogramPerCubicMeter, (double)poundpercubicmillimeterQuantity.Value, PoundsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMillimeter, poundpercubicmillimeterQuantity.Unit); - - var poundperimperialgallonQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerImperialGallon); - AssertEx.EqualTolerance(PoundsPerImperialGallonInOneKilogramPerCubicMeter, (double)poundperimperialgallonQuantity.Value, PoundsPerImperialGallonTolerance); - Assert.Equal(DensityUnit.PoundPerImperialGallon, poundperimperialgallonQuantity.Unit); - - var poundperusgallonQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerUSGallon); - AssertEx.EqualTolerance(PoundsPerUSGallonInOneKilogramPerCubicMeter, (double)poundperusgallonQuantity.Value, PoundsPerUSGallonTolerance); - Assert.Equal(DensityUnit.PoundPerUSGallon, poundperusgallonQuantity.Unit); - - var slugpercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.SlugPerCubicCentimeter); - AssertEx.EqualTolerance(SlugsPerCubicCentimeterInOneKilogramPerCubicMeter, (double)slugpercubiccentimeterQuantity.Value, SlugsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.SlugPerCubicCentimeter, slugpercubiccentimeterQuantity.Unit); - - var slugpercubicfootQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.SlugPerCubicFoot); - AssertEx.EqualTolerance(SlugsPerCubicFootInOneKilogramPerCubicMeter, (double)slugpercubicfootQuantity.Value, SlugsPerCubicFootTolerance); - Assert.Equal(DensityUnit.SlugPerCubicFoot, slugpercubicfootQuantity.Unit); - - var slugpercubicinchQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.SlugPerCubicInch); - AssertEx.EqualTolerance(SlugsPerCubicInchInOneKilogramPerCubicMeter, (double)slugpercubicinchQuantity.Value, SlugsPerCubicInchTolerance); - Assert.Equal(DensityUnit.SlugPerCubicInch, slugpercubicinchQuantity.Unit); - - var slugpercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.SlugPerCubicMeter); - AssertEx.EqualTolerance(SlugsPerCubicMeterInOneKilogramPerCubicMeter, (double)slugpercubicmeterQuantity.Value, SlugsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.SlugPerCubicMeter, slugpercubicmeterQuantity.Unit); - - var slugpercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.SlugPerCubicMillimeter); - AssertEx.EqualTolerance(SlugsPerCubicMillimeterInOneKilogramPerCubicMeter, (double)slugpercubicmillimeterQuantity.Value, SlugsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.SlugPerCubicMillimeter, slugpercubicmillimeterQuantity.Unit); - - var tonnepercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.TonnePerCubicCentimeter); - AssertEx.EqualTolerance(TonnesPerCubicCentimeterInOneKilogramPerCubicMeter, (double)tonnepercubiccentimeterQuantity.Value, TonnesPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicCentimeter, tonnepercubiccentimeterQuantity.Unit); - - var tonnepercubicfootQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.TonnePerCubicFoot); - AssertEx.EqualTolerance(TonnesPerCubicFootInOneKilogramPerCubicMeter, (double)tonnepercubicfootQuantity.Value, TonnesPerCubicFootTolerance); - Assert.Equal(DensityUnit.TonnePerCubicFoot, tonnepercubicfootQuantity.Unit); - - var tonnepercubicinchQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.TonnePerCubicInch); - AssertEx.EqualTolerance(TonnesPerCubicInchInOneKilogramPerCubicMeter, (double)tonnepercubicinchQuantity.Value, TonnesPerCubicInchTolerance); - Assert.Equal(DensityUnit.TonnePerCubicInch, tonnepercubicinchQuantity.Unit); - - var tonnepercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.TonnePerCubicMeter); - AssertEx.EqualTolerance(TonnesPerCubicMeterInOneKilogramPerCubicMeter, (double)tonnepercubicmeterQuantity.Value, TonnesPerCubicMeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicMeter, tonnepercubicmeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonnepercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.TonnePerCubicMillimeter); - AssertEx.EqualTolerance(TonnesPerCubicMillimeterInOneKilogramPerCubicMeter, (double)tonnepercubicmillimeterQuantity.Value, TonnesPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicMillimeter, tonnepercubicmillimeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(DensityUnit unit) + { + var quantity = Density.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DensityUnit unit) { - var quantityInBaseUnit = Density.FromKilogramsPerCubicMeter(1).ToBaseUnit(); - Assert.Equal(Density.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Density.Units.FirstOrDefault(u => u != Density.BaseUnit && u != DensityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == DensityUnit.Undefined) + fromUnit = Density.BaseUnit; + + var quantity = Density.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs index 35023e74cb..bb1ca8753d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -63,6 +64,40 @@ public abstract partial class DurationTestsBase : QuantityTestsBase protected virtual double Years365Tolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(DurationUnit unit) + { + return unit switch + { + DurationUnit.Day => (DaysInOneSecond, DaysTolerance), + DurationUnit.Hour => (HoursInOneSecond, HoursTolerance), + DurationUnit.JulianYear => (JulianYearsInOneSecond, JulianYearsTolerance), + DurationUnit.Microsecond => (MicrosecondsInOneSecond, MicrosecondsTolerance), + DurationUnit.Millisecond => (MillisecondsInOneSecond, MillisecondsTolerance), + DurationUnit.Minute => (MinutesInOneSecond, MinutesTolerance), + DurationUnit.Month30 => (Months30InOneSecond, Months30Tolerance), + DurationUnit.Nanosecond => (NanosecondsInOneSecond, NanosecondsTolerance), + DurationUnit.Second => (SecondsInOneSecond, SecondsTolerance), + DurationUnit.Week => (WeeksInOneSecond, WeeksTolerance), + DurationUnit.Year365 => (Years365InOneSecond, Years365Tolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { DurationUnit.Day }, + new object[] { DurationUnit.Hour }, + new object[] { DurationUnit.JulianYear }, + new object[] { DurationUnit.Microsecond }, + new object[] { DurationUnit.Millisecond }, + new object[] { DurationUnit.Minute }, + new object[] { DurationUnit.Month30 }, + new object[] { DurationUnit.Nanosecond }, + new object[] { DurationUnit.Second }, + new object[] { DurationUnit.Week }, + new object[] { DurationUnit.Year365 }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -244,61 +279,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(DurationUnit unit) { - var second = Duration.FromSeconds(1); - - var dayQuantity = second.ToUnit(DurationUnit.Day); - AssertEx.EqualTolerance(DaysInOneSecond, (double)dayQuantity.Value, DaysTolerance); - Assert.Equal(DurationUnit.Day, dayQuantity.Unit); - - var hourQuantity = second.ToUnit(DurationUnit.Hour); - AssertEx.EqualTolerance(HoursInOneSecond, (double)hourQuantity.Value, HoursTolerance); - Assert.Equal(DurationUnit.Hour, hourQuantity.Unit); - - var julianyearQuantity = second.ToUnit(DurationUnit.JulianYear); - AssertEx.EqualTolerance(JulianYearsInOneSecond, (double)julianyearQuantity.Value, JulianYearsTolerance); - Assert.Equal(DurationUnit.JulianYear, julianyearQuantity.Unit); - - var microsecondQuantity = second.ToUnit(DurationUnit.Microsecond); - AssertEx.EqualTolerance(MicrosecondsInOneSecond, (double)microsecondQuantity.Value, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, microsecondQuantity.Unit); - - var millisecondQuantity = second.ToUnit(DurationUnit.Millisecond); - AssertEx.EqualTolerance(MillisecondsInOneSecond, (double)millisecondQuantity.Value, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, millisecondQuantity.Unit); + var inBaseUnits = Duration.From(1.0, Duration.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var minuteQuantity = second.ToUnit(DurationUnit.Minute); - AssertEx.EqualTolerance(MinutesInOneSecond, (double)minuteQuantity.Value, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, minuteQuantity.Unit); - - var month30Quantity = second.ToUnit(DurationUnit.Month30); - AssertEx.EqualTolerance(Months30InOneSecond, (double)month30Quantity.Value, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, month30Quantity.Unit); - - var nanosecondQuantity = second.ToUnit(DurationUnit.Nanosecond); - AssertEx.EqualTolerance(NanosecondsInOneSecond, (double)nanosecondQuantity.Value, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, nanosecondQuantity.Unit); - - var secondQuantity = second.ToUnit(DurationUnit.Second); - AssertEx.EqualTolerance(SecondsInOneSecond, (double)secondQuantity.Value, SecondsTolerance); - Assert.Equal(DurationUnit.Second, secondQuantity.Unit); - - var weekQuantity = second.ToUnit(DurationUnit.Week); - AssertEx.EqualTolerance(WeeksInOneSecond, (double)weekQuantity.Value, WeeksTolerance); - Assert.Equal(DurationUnit.Week, weekQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var year365Quantity = second.ToUnit(DurationUnit.Year365); - AssertEx.EqualTolerance(Years365InOneSecond, (double)year365Quantity.Value, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, year365Quantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(DurationUnit unit) + { + var quantity = Duration.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DurationUnit unit) { - var quantityInBaseUnit = Duration.FromSeconds(1).ToBaseUnit(); - Assert.Equal(Duration.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Duration.Units.FirstOrDefault(u => u != Duration.BaseUnit && u != DurationUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == DurationUnit.Undefined) + fromUnit = Duration.BaseUnit; + + var quantity = Duration.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs index 47b7e6934f..743e6be92f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -61,6 +62,38 @@ public abstract partial class DynamicViscosityTestsBase : QuantityTestsBase protected virtual double ReynsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(DynamicViscosityUnit unit) + { + return unit switch + { + DynamicViscosityUnit.Centipoise => (CentipoiseInOneNewtonSecondPerMeterSquared, CentipoiseTolerance), + DynamicViscosityUnit.MicropascalSecond => (MicropascalSecondsInOneNewtonSecondPerMeterSquared, MicropascalSecondsTolerance), + DynamicViscosityUnit.MillipascalSecond => (MillipascalSecondsInOneNewtonSecondPerMeterSquared, MillipascalSecondsTolerance), + DynamicViscosityUnit.NewtonSecondPerMeterSquared => (NewtonSecondsPerMeterSquaredInOneNewtonSecondPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance), + DynamicViscosityUnit.PascalSecond => (PascalSecondsInOneNewtonSecondPerMeterSquared, PascalSecondsTolerance), + DynamicViscosityUnit.Poise => (PoiseInOneNewtonSecondPerMeterSquared, PoiseTolerance), + DynamicViscosityUnit.PoundForceSecondPerSquareFoot => (PoundsForceSecondPerSquareFootInOneNewtonSecondPerMeterSquared, PoundsForceSecondPerSquareFootTolerance), + DynamicViscosityUnit.PoundForceSecondPerSquareInch => (PoundsForceSecondPerSquareInchInOneNewtonSecondPerMeterSquared, PoundsForceSecondPerSquareInchTolerance), + DynamicViscosityUnit.PoundPerFootSecond => (PoundsPerFootSecondInOneNewtonSecondPerMeterSquared, PoundsPerFootSecondTolerance), + DynamicViscosityUnit.Reyn => (ReynsInOneNewtonSecondPerMeterSquared, ReynsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { DynamicViscosityUnit.Centipoise }, + new object[] { DynamicViscosityUnit.MicropascalSecond }, + new object[] { DynamicViscosityUnit.MillipascalSecond }, + new object[] { DynamicViscosityUnit.NewtonSecondPerMeterSquared }, + new object[] { DynamicViscosityUnit.PascalSecond }, + new object[] { DynamicViscosityUnit.Poise }, + new object[] { DynamicViscosityUnit.PoundForceSecondPerSquareFoot }, + new object[] { DynamicViscosityUnit.PoundForceSecondPerSquareInch }, + new object[] { DynamicViscosityUnit.PoundPerFootSecond }, + new object[] { DynamicViscosityUnit.Reyn }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -236,57 +269,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(DynamicViscosityUnit unit) { - var newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - - var centipoiseQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.Centipoise); - AssertEx.EqualTolerance(CentipoiseInOneNewtonSecondPerMeterSquared, (double)centipoiseQuantity.Value, CentipoiseTolerance); - Assert.Equal(DynamicViscosityUnit.Centipoise, centipoiseQuantity.Unit); - - var micropascalsecondQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.MicropascalSecond); - AssertEx.EqualTolerance(MicropascalSecondsInOneNewtonSecondPerMeterSquared, (double)micropascalsecondQuantity.Value, MicropascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MicropascalSecond, micropascalsecondQuantity.Unit); - - var millipascalsecondQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.MillipascalSecond); - AssertEx.EqualTolerance(MillipascalSecondsInOneNewtonSecondPerMeterSquared, (double)millipascalsecondQuantity.Value, MillipascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MillipascalSecond, millipascalsecondQuantity.Unit); - - var newtonsecondpermetersquaredQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared); - AssertEx.EqualTolerance(NewtonSecondsPerMeterSquaredInOneNewtonSecondPerMeterSquared, (double)newtonsecondpermetersquaredQuantity.Value, NewtonSecondsPerMeterSquaredTolerance); - Assert.Equal(DynamicViscosityUnit.NewtonSecondPerMeterSquared, newtonsecondpermetersquaredQuantity.Unit); - - var pascalsecondQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.PascalSecond); - AssertEx.EqualTolerance(PascalSecondsInOneNewtonSecondPerMeterSquared, (double)pascalsecondQuantity.Value, PascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.PascalSecond, pascalsecondQuantity.Unit); + var inBaseUnits = DynamicViscosity.From(1.0, DynamicViscosity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var poiseQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.Poise); - AssertEx.EqualTolerance(PoiseInOneNewtonSecondPerMeterSquared, (double)poiseQuantity.Value, PoiseTolerance); - Assert.Equal(DynamicViscosityUnit.Poise, poiseQuantity.Unit); - - var poundforcesecondpersquarefootQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.PoundForceSecondPerSquareFoot); - AssertEx.EqualTolerance(PoundsForceSecondPerSquareFootInOneNewtonSecondPerMeterSquared, (double)poundforcesecondpersquarefootQuantity.Value, PoundsForceSecondPerSquareFootTolerance); - Assert.Equal(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, poundforcesecondpersquarefootQuantity.Unit); - - var poundforcesecondpersquareinchQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.PoundForceSecondPerSquareInch); - AssertEx.EqualTolerance(PoundsForceSecondPerSquareInchInOneNewtonSecondPerMeterSquared, (double)poundforcesecondpersquareinchQuantity.Value, PoundsForceSecondPerSquareInchTolerance); - Assert.Equal(DynamicViscosityUnit.PoundForceSecondPerSquareInch, poundforcesecondpersquareinchQuantity.Unit); - - var poundperfootsecondQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.PoundPerFootSecond); - AssertEx.EqualTolerance(PoundsPerFootSecondInOneNewtonSecondPerMeterSquared, (double)poundperfootsecondQuantity.Value, PoundsPerFootSecondTolerance); - Assert.Equal(DynamicViscosityUnit.PoundPerFootSecond, poundperfootsecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var reynQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.Reyn); - AssertEx.EqualTolerance(ReynsInOneNewtonSecondPerMeterSquared, (double)reynQuantity.Value, ReynsTolerance); - Assert.Equal(DynamicViscosityUnit.Reyn, reynQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(DynamicViscosityUnit unit) + { + var quantity = DynamicViscosity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DynamicViscosityUnit unit) { - var quantityInBaseUnit = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1).ToBaseUnit(); - Assert.Equal(DynamicViscosity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = DynamicViscosity.Units.FirstOrDefault(u => u != DynamicViscosity.BaseUnit && u != DynamicViscosityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == DynamicViscosityUnit.Undefined) + fromUnit = DynamicViscosity.BaseUnit; + + var quantity = DynamicViscosity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs index d855cedc5c..b4c6557bde 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class ElectricAdmittanceTestsBase : QuantityTestsBase protected virtual double SiemensTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricAdmittanceUnit unit) + { + return unit switch + { + ElectricAdmittanceUnit.Microsiemens => (MicrosiemensInOneSiemens, MicrosiemensTolerance), + ElectricAdmittanceUnit.Millisiemens => (MillisiemensInOneSiemens, MillisiemensTolerance), + ElectricAdmittanceUnit.Nanosiemens => (NanosiemensInOneSiemens, NanosiemensTolerance), + ElectricAdmittanceUnit.Siemens => (SiemensInOneSiemens, SiemensTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricAdmittanceUnit.Microsiemens }, + new object[] { ElectricAdmittanceUnit.Millisiemens }, + new object[] { ElectricAdmittanceUnit.Nanosiemens }, + new object[] { ElectricAdmittanceUnit.Siemens }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricAdmittanceUnit unit) { - var siemens = ElectricAdmittance.FromSiemens(1); + var inBaseUnits = ElectricAdmittance.From(1.0, ElectricAdmittance.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var microsiemensQuantity = siemens.ToUnit(ElectricAdmittanceUnit.Microsiemens); - AssertEx.EqualTolerance(MicrosiemensInOneSiemens, (double)microsiemensQuantity.Value, MicrosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Microsiemens, microsiemensQuantity.Unit); - - var millisiemensQuantity = siemens.ToUnit(ElectricAdmittanceUnit.Millisiemens); - AssertEx.EqualTolerance(MillisiemensInOneSiemens, (double)millisiemensQuantity.Value, MillisiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Millisiemens, millisiemensQuantity.Unit); - - var nanosiemensQuantity = siemens.ToUnit(ElectricAdmittanceUnit.Nanosiemens); - AssertEx.EqualTolerance(NanosiemensInOneSiemens, (double)nanosiemensQuantity.Value, NanosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Nanosiemens, nanosiemensQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var siemensQuantity = siemens.ToUnit(ElectricAdmittanceUnit.Siemens); - AssertEx.EqualTolerance(SiemensInOneSiemens, (double)siemensQuantity.Value, SiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Siemens, siemensQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricAdmittanceUnit unit) + { + var quantity = ElectricAdmittance.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricAdmittanceUnit unit) { - var quantityInBaseUnit = ElectricAdmittance.FromSiemens(1).ToBaseUnit(); - Assert.Equal(ElectricAdmittance.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricAdmittance.Units.FirstOrDefault(u => u != ElectricAdmittance.BaseUnit && u != ElectricAdmittanceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricAdmittanceUnit.Undefined) + fromUnit = ElectricAdmittance.BaseUnit; + + var quantity = ElectricAdmittance.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs index c714108b47..17e05c7b60 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class ElectricChargeDensityTestsBase : QuantityTestsBase protected virtual double CoulombsPerCubicMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricChargeDensityUnit unit) + { + return unit switch + { + ElectricChargeDensityUnit.CoulombPerCubicMeter => (CoulombsPerCubicMeterInOneCoulombPerCubicMeter, CoulombsPerCubicMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricChargeDensityUnit.CoulombPerCubicMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricChargeDensityUnit unit) { - var coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); + var inBaseUnits = ElectricChargeDensity.From(1.0, ElectricChargeDensity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var coulombpercubicmeterQuantity = coulombpercubicmeter.ToUnit(ElectricChargeDensityUnit.CoulombPerCubicMeter); - AssertEx.EqualTolerance(CoulombsPerCubicMeterInOneCoulombPerCubicMeter, (double)coulombpercubicmeterQuantity.Value, CoulombsPerCubicMeterTolerance); - Assert.Equal(ElectricChargeDensityUnit.CoulombPerCubicMeter, coulombpercubicmeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricChargeDensityUnit unit) + { + var quantity = ElectricChargeDensity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricChargeDensityUnit unit) { - var quantityInBaseUnit = ElectricChargeDensity.FromCoulombsPerCubicMeter(1).ToBaseUnit(); - Assert.Equal(ElectricChargeDensity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricChargeDensity.Units.FirstOrDefault(u => u != ElectricChargeDensity.BaseUnit && u != ElectricChargeDensityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricChargeDensityUnit.Undefined) + fromUnit = ElectricChargeDensity.BaseUnit; + + var quantity = ElectricChargeDensity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs index ba6b76acbb..7fefdc564b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -51,6 +52,28 @@ public abstract partial class ElectricChargeTestsBase : QuantityTestsBase protected virtual double MilliampereHoursTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricChargeUnit unit) + { + return unit switch + { + ElectricChargeUnit.AmpereHour => (AmpereHoursInOneCoulomb, AmpereHoursTolerance), + ElectricChargeUnit.Coulomb => (CoulombsInOneCoulomb, CoulombsTolerance), + ElectricChargeUnit.KiloampereHour => (KiloampereHoursInOneCoulomb, KiloampereHoursTolerance), + ElectricChargeUnit.MegaampereHour => (MegaampereHoursInOneCoulomb, MegaampereHoursTolerance), + ElectricChargeUnit.MilliampereHour => (MilliampereHoursInOneCoulomb, MilliampereHoursTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricChargeUnit.AmpereHour }, + new object[] { ElectricChargeUnit.Coulomb }, + new object[] { ElectricChargeUnit.KiloampereHour }, + new object[] { ElectricChargeUnit.MegaampereHour }, + new object[] { ElectricChargeUnit.MilliampereHour }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -196,37 +219,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricChargeUnit unit) { - var coulomb = ElectricCharge.FromCoulombs(1); - - var amperehourQuantity = coulomb.ToUnit(ElectricChargeUnit.AmpereHour); - AssertEx.EqualTolerance(AmpereHoursInOneCoulomb, (double)amperehourQuantity.Value, AmpereHoursTolerance); - Assert.Equal(ElectricChargeUnit.AmpereHour, amperehourQuantity.Unit); + var inBaseUnits = ElectricCharge.From(1.0, ElectricCharge.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var coulombQuantity = coulomb.ToUnit(ElectricChargeUnit.Coulomb); - AssertEx.EqualTolerance(CoulombsInOneCoulomb, (double)coulombQuantity.Value, CoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Coulomb, coulombQuantity.Unit); - - var kiloamperehourQuantity = coulomb.ToUnit(ElectricChargeUnit.KiloampereHour); - AssertEx.EqualTolerance(KiloampereHoursInOneCoulomb, (double)kiloamperehourQuantity.Value, KiloampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.KiloampereHour, kiloamperehourQuantity.Unit); - - var megaamperehourQuantity = coulomb.ToUnit(ElectricChargeUnit.MegaampereHour); - AssertEx.EqualTolerance(MegaampereHoursInOneCoulomb, (double)megaamperehourQuantity.Value, MegaampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.MegaampereHour, megaamperehourQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var milliamperehourQuantity = coulomb.ToUnit(ElectricChargeUnit.MilliampereHour); - AssertEx.EqualTolerance(MilliampereHoursInOneCoulomb, (double)milliamperehourQuantity.Value, MilliampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.MilliampereHour, milliamperehourQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricChargeUnit unit) + { + var quantity = ElectricCharge.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricChargeUnit unit) { - var quantityInBaseUnit = ElectricCharge.FromCoulombs(1).ToBaseUnit(); - Assert.Equal(ElectricCharge.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricCharge.Units.FirstOrDefault(u => u != ElectricCharge.BaseUnit && u != ElectricChargeUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricChargeUnit.Undefined) + fromUnit = ElectricCharge.BaseUnit; + + var quantity = ElectricCharge.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs index 3b348ba006..1e4cd156e5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class ElectricConductanceTestsBase : QuantityTestsBase protected virtual double SiemensTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricConductanceUnit unit) + { + return unit switch + { + ElectricConductanceUnit.Microsiemens => (MicrosiemensInOneSiemens, MicrosiemensTolerance), + ElectricConductanceUnit.Millisiemens => (MillisiemensInOneSiemens, MillisiemensTolerance), + ElectricConductanceUnit.Siemens => (SiemensInOneSiemens, SiemensTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricConductanceUnit.Microsiemens }, + new object[] { ElectricConductanceUnit.Millisiemens }, + new object[] { ElectricConductanceUnit.Siemens }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricConductanceUnit unit) { - var siemens = ElectricConductance.FromSiemens(1); + var inBaseUnits = ElectricConductance.From(1.0, ElectricConductance.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var microsiemensQuantity = siemens.ToUnit(ElectricConductanceUnit.Microsiemens); - AssertEx.EqualTolerance(MicrosiemensInOneSiemens, (double)microsiemensQuantity.Value, MicrosiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Microsiemens, microsiemensQuantity.Unit); - - var millisiemensQuantity = siemens.ToUnit(ElectricConductanceUnit.Millisiemens); - AssertEx.EqualTolerance(MillisiemensInOneSiemens, (double)millisiemensQuantity.Value, MillisiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Millisiemens, millisiemensQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var siemensQuantity = siemens.ToUnit(ElectricConductanceUnit.Siemens); - AssertEx.EqualTolerance(SiemensInOneSiemens, (double)siemensQuantity.Value, SiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Siemens, siemensQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricConductanceUnit unit) + { + var quantity = ElectricConductance.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricConductanceUnit unit) { - var quantityInBaseUnit = ElectricConductance.FromSiemens(1).ToBaseUnit(); - Assert.Equal(ElectricConductance.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricConductance.Units.FirstOrDefault(u => u != ElectricConductance.BaseUnit && u != ElectricConductanceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricConductanceUnit.Undefined) + fromUnit = ElectricConductance.BaseUnit; + + var quantity = ElectricConductance.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs index 30fe721b4a..55a741771f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class ElectricConductivityTestsBase : QuantityTestsBase protected virtual double SiemensPerMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricConductivityUnit unit) + { + return unit switch + { + ElectricConductivityUnit.SiemensPerFoot => (SiemensPerFootInOneSiemensPerMeter, SiemensPerFootTolerance), + ElectricConductivityUnit.SiemensPerInch => (SiemensPerInchInOneSiemensPerMeter, SiemensPerInchTolerance), + ElectricConductivityUnit.SiemensPerMeter => (SiemensPerMeterInOneSiemensPerMeter, SiemensPerMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricConductivityUnit.SiemensPerFoot }, + new object[] { ElectricConductivityUnit.SiemensPerInch }, + new object[] { ElectricConductivityUnit.SiemensPerMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricConductivityUnit unit) { - var siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); + var inBaseUnits = ElectricConductivity.From(1.0, ElectricConductivity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var siemensperfootQuantity = siemenspermeter.ToUnit(ElectricConductivityUnit.SiemensPerFoot); - AssertEx.EqualTolerance(SiemensPerFootInOneSiemensPerMeter, (double)siemensperfootQuantity.Value, SiemensPerFootTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerFoot, siemensperfootQuantity.Unit); - - var siemensperinchQuantity = siemenspermeter.ToUnit(ElectricConductivityUnit.SiemensPerInch); - AssertEx.EqualTolerance(SiemensPerInchInOneSiemensPerMeter, (double)siemensperinchQuantity.Value, SiemensPerInchTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerInch, siemensperinchQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var siemenspermeterQuantity = siemenspermeter.ToUnit(ElectricConductivityUnit.SiemensPerMeter); - AssertEx.EqualTolerance(SiemensPerMeterInOneSiemensPerMeter, (double)siemenspermeterQuantity.Value, SiemensPerMeterTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerMeter, siemenspermeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricConductivityUnit unit) + { + var quantity = ElectricConductivity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricConductivityUnit unit) { - var quantityInBaseUnit = ElectricConductivity.FromSiemensPerMeter(1).ToBaseUnit(); - Assert.Equal(ElectricConductivity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricConductivity.Units.FirstOrDefault(u => u != ElectricConductivity.BaseUnit && u != ElectricConductivityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricConductivityUnit.Undefined) + fromUnit = ElectricConductivity.BaseUnit; + + var quantity = ElectricConductivity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs index 2b6a166eac..e3c7067ce5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class ElectricCurrentDensityTestsBase : QuantityTestsBas protected virtual double AmperesPerSquareMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricCurrentDensityUnit unit) + { + return unit switch + { + ElectricCurrentDensityUnit.AmperePerSquareFoot => (AmperesPerSquareFootInOneAmperePerSquareMeter, AmperesPerSquareFootTolerance), + ElectricCurrentDensityUnit.AmperePerSquareInch => (AmperesPerSquareInchInOneAmperePerSquareMeter, AmperesPerSquareInchTolerance), + ElectricCurrentDensityUnit.AmperePerSquareMeter => (AmperesPerSquareMeterInOneAmperePerSquareMeter, AmperesPerSquareMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricCurrentDensityUnit.AmperePerSquareFoot }, + new object[] { ElectricCurrentDensityUnit.AmperePerSquareInch }, + new object[] { ElectricCurrentDensityUnit.AmperePerSquareMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricCurrentDensityUnit unit) { - var amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); + var inBaseUnits = ElectricCurrentDensity.From(1.0, ElectricCurrentDensity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var amperepersquarefootQuantity = amperepersquaremeter.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareFoot); - AssertEx.EqualTolerance(AmperesPerSquareFootInOneAmperePerSquareMeter, (double)amperepersquarefootQuantity.Value, AmperesPerSquareFootTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareFoot, amperepersquarefootQuantity.Unit); - - var amperepersquareinchQuantity = amperepersquaremeter.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareInch); - AssertEx.EqualTolerance(AmperesPerSquareInchInOneAmperePerSquareMeter, (double)amperepersquareinchQuantity.Value, AmperesPerSquareInchTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareInch, amperepersquareinchQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var amperepersquaremeterQuantity = amperepersquaremeter.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareMeter); - AssertEx.EqualTolerance(AmperesPerSquareMeterInOneAmperePerSquareMeter, (double)amperepersquaremeterQuantity.Value, AmperesPerSquareMeterTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareMeter, amperepersquaremeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentDensityUnit unit) + { + var quantity = ElectricCurrentDensity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentDensityUnit unit) { - var quantityInBaseUnit = ElectricCurrentDensity.FromAmperesPerSquareMeter(1).ToBaseUnit(); - Assert.Equal(ElectricCurrentDensity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricCurrentDensity.Units.FirstOrDefault(u => u != ElectricCurrentDensity.BaseUnit && u != ElectricCurrentDensityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricCurrentDensityUnit.Undefined) + fromUnit = ElectricCurrentDensity.BaseUnit; + + var quantity = ElectricCurrentDensity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs index ab24e643a2..9663d96458 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class ElectricCurrentGradientTestsBase : QuantityTestsBa protected virtual double AmperesPerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricCurrentGradientUnit unit) + { + return unit switch + { + ElectricCurrentGradientUnit.AmperePerMicrosecond => (AmperesPerMicrosecondInOneAmperePerSecond, AmperesPerMicrosecondTolerance), + ElectricCurrentGradientUnit.AmperePerMillisecond => (AmperesPerMillisecondInOneAmperePerSecond, AmperesPerMillisecondTolerance), + ElectricCurrentGradientUnit.AmperePerNanosecond => (AmperesPerNanosecondInOneAmperePerSecond, AmperesPerNanosecondTolerance), + ElectricCurrentGradientUnit.AmperePerSecond => (AmperesPerSecondInOneAmperePerSecond, AmperesPerSecondTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricCurrentGradientUnit.AmperePerMicrosecond }, + new object[] { ElectricCurrentGradientUnit.AmperePerMillisecond }, + new object[] { ElectricCurrentGradientUnit.AmperePerNanosecond }, + new object[] { ElectricCurrentGradientUnit.AmperePerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricCurrentGradientUnit unit) { - var amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); + var inBaseUnits = ElectricCurrentGradient.From(1.0, ElectricCurrentGradient.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var amperepermicrosecondQuantity = amperepersecond.ToUnit(ElectricCurrentGradientUnit.AmperePerMicrosecond); - AssertEx.EqualTolerance(AmperesPerMicrosecondInOneAmperePerSecond, (double)amperepermicrosecondQuantity.Value, AmperesPerMicrosecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerMicrosecond, amperepermicrosecondQuantity.Unit); - - var amperepermillisecondQuantity = amperepersecond.ToUnit(ElectricCurrentGradientUnit.AmperePerMillisecond); - AssertEx.EqualTolerance(AmperesPerMillisecondInOneAmperePerSecond, (double)amperepermillisecondQuantity.Value, AmperesPerMillisecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerMillisecond, amperepermillisecondQuantity.Unit); - - var amperepernanosecondQuantity = amperepersecond.ToUnit(ElectricCurrentGradientUnit.AmperePerNanosecond); - AssertEx.EqualTolerance(AmperesPerNanosecondInOneAmperePerSecond, (double)amperepernanosecondQuantity.Value, AmperesPerNanosecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerNanosecond, amperepernanosecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var amperepersecondQuantity = amperepersecond.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond); - AssertEx.EqualTolerance(AmperesPerSecondInOneAmperePerSecond, (double)amperepersecondQuantity.Value, AmperesPerSecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerSecond, amperepersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentGradientUnit unit) + { + var quantity = ElectricCurrentGradient.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentGradientUnit unit) { - var quantityInBaseUnit = ElectricCurrentGradient.FromAmperesPerSecond(1).ToBaseUnit(); - Assert.Equal(ElectricCurrentGradient.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricCurrentGradient.Units.FirstOrDefault(u => u != ElectricCurrentGradient.BaseUnit && u != ElectricCurrentGradientUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricCurrentGradientUnit.Undefined) + fromUnit = ElectricCurrentGradient.BaseUnit; + + var quantity = ElectricCurrentGradient.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs index 633f32f1ff..3374cd2321 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -57,6 +58,34 @@ public abstract partial class ElectricCurrentTestsBase : QuantityTestsBase protected virtual double PicoamperesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricCurrentUnit unit) + { + return unit switch + { + ElectricCurrentUnit.Ampere => (AmperesInOneAmpere, AmperesTolerance), + ElectricCurrentUnit.Centiampere => (CentiamperesInOneAmpere, CentiamperesTolerance), + ElectricCurrentUnit.Kiloampere => (KiloamperesInOneAmpere, KiloamperesTolerance), + ElectricCurrentUnit.Megaampere => (MegaamperesInOneAmpere, MegaamperesTolerance), + ElectricCurrentUnit.Microampere => (MicroamperesInOneAmpere, MicroamperesTolerance), + ElectricCurrentUnit.Milliampere => (MilliamperesInOneAmpere, MilliamperesTolerance), + ElectricCurrentUnit.Nanoampere => (NanoamperesInOneAmpere, NanoamperesTolerance), + ElectricCurrentUnit.Picoampere => (PicoamperesInOneAmpere, PicoamperesTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricCurrentUnit.Ampere }, + new object[] { ElectricCurrentUnit.Centiampere }, + new object[] { ElectricCurrentUnit.Kiloampere }, + new object[] { ElectricCurrentUnit.Megaampere }, + new object[] { ElectricCurrentUnit.Microampere }, + new object[] { ElectricCurrentUnit.Milliampere }, + new object[] { ElectricCurrentUnit.Nanoampere }, + new object[] { ElectricCurrentUnit.Picoampere }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -220,49 +249,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricCurrentUnit unit) { - var ampere = ElectricCurrent.FromAmperes(1); - - var ampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Ampere); - AssertEx.EqualTolerance(AmperesInOneAmpere, (double)ampereQuantity.Value, AmperesTolerance); - Assert.Equal(ElectricCurrentUnit.Ampere, ampereQuantity.Unit); - - var centiampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Centiampere); - AssertEx.EqualTolerance(CentiamperesInOneAmpere, (double)centiampereQuantity.Value, CentiamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Centiampere, centiampereQuantity.Unit); - - var kiloampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Kiloampere); - AssertEx.EqualTolerance(KiloamperesInOneAmpere, (double)kiloampereQuantity.Value, KiloamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Kiloampere, kiloampereQuantity.Unit); - - var megaampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Megaampere); - AssertEx.EqualTolerance(MegaamperesInOneAmpere, (double)megaampereQuantity.Value, MegaamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Megaampere, megaampereQuantity.Unit); + var inBaseUnits = ElectricCurrent.From(1.0, ElectricCurrent.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var microampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Microampere); - AssertEx.EqualTolerance(MicroamperesInOneAmpere, (double)microampereQuantity.Value, MicroamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Microampere, microampereQuantity.Unit); - - var milliampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Milliampere); - AssertEx.EqualTolerance(MilliamperesInOneAmpere, (double)milliampereQuantity.Value, MilliamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Milliampere, milliampereQuantity.Unit); - - var nanoampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Nanoampere); - AssertEx.EqualTolerance(NanoamperesInOneAmpere, (double)nanoampereQuantity.Value, NanoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Nanoampere, nanoampereQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var picoampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Picoampere); - AssertEx.EqualTolerance(PicoamperesInOneAmpere, (double)picoampereQuantity.Value, PicoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Picoampere, picoampereQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentUnit unit) + { + var quantity = ElectricCurrent.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentUnit unit) { - var quantityInBaseUnit = ElectricCurrent.FromAmperes(1).ToBaseUnit(); - Assert.Equal(ElectricCurrent.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricCurrent.Units.FirstOrDefault(u => u != ElectricCurrent.BaseUnit && u != ElectricCurrentUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricCurrentUnit.Undefined) + fromUnit = ElectricCurrent.BaseUnit; + + var quantity = ElectricCurrent.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs index 79f369eae9..825ea88e65 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class ElectricFieldTestsBase : QuantityTestsBase protected virtual double VoltsPerMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricFieldUnit unit) + { + return unit switch + { + ElectricFieldUnit.VoltPerMeter => (VoltsPerMeterInOneVoltPerMeter, VoltsPerMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricFieldUnit.VoltPerMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricFieldUnit unit) { - var voltpermeter = ElectricField.FromVoltsPerMeter(1); + var inBaseUnits = ElectricField.From(1.0, ElectricField.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var voltpermeterQuantity = voltpermeter.ToUnit(ElectricFieldUnit.VoltPerMeter); - AssertEx.EqualTolerance(VoltsPerMeterInOneVoltPerMeter, (double)voltpermeterQuantity.Value, VoltsPerMeterTolerance); - Assert.Equal(ElectricFieldUnit.VoltPerMeter, voltpermeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricFieldUnit unit) + { + var quantity = ElectricField.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricFieldUnit unit) { - var quantityInBaseUnit = ElectricField.FromVoltsPerMeter(1).ToBaseUnit(); - Assert.Equal(ElectricField.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricField.Units.FirstOrDefault(u => u != ElectricField.BaseUnit && u != ElectricFieldUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricFieldUnit.Undefined) + fromUnit = ElectricField.BaseUnit; + + var quantity = ElectricField.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs index 4482b18fd5..8c7f0f8f83 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class ElectricInductanceTestsBase : QuantityTestsBase protected virtual double NanohenriesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricInductanceUnit unit) + { + return unit switch + { + ElectricInductanceUnit.Henry => (HenriesInOneHenry, HenriesTolerance), + ElectricInductanceUnit.Microhenry => (MicrohenriesInOneHenry, MicrohenriesTolerance), + ElectricInductanceUnit.Millihenry => (MillihenriesInOneHenry, MillihenriesTolerance), + ElectricInductanceUnit.Nanohenry => (NanohenriesInOneHenry, NanohenriesTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricInductanceUnit.Henry }, + new object[] { ElectricInductanceUnit.Microhenry }, + new object[] { ElectricInductanceUnit.Millihenry }, + new object[] { ElectricInductanceUnit.Nanohenry }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricInductanceUnit unit) { - var henry = ElectricInductance.FromHenries(1); + var inBaseUnits = ElectricInductance.From(1.0, ElectricInductance.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var henryQuantity = henry.ToUnit(ElectricInductanceUnit.Henry); - AssertEx.EqualTolerance(HenriesInOneHenry, (double)henryQuantity.Value, HenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Henry, henryQuantity.Unit); - - var microhenryQuantity = henry.ToUnit(ElectricInductanceUnit.Microhenry); - AssertEx.EqualTolerance(MicrohenriesInOneHenry, (double)microhenryQuantity.Value, MicrohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Microhenry, microhenryQuantity.Unit); - - var millihenryQuantity = henry.ToUnit(ElectricInductanceUnit.Millihenry); - AssertEx.EqualTolerance(MillihenriesInOneHenry, (double)millihenryQuantity.Value, MillihenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Millihenry, millihenryQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var nanohenryQuantity = henry.ToUnit(ElectricInductanceUnit.Nanohenry); - AssertEx.EqualTolerance(NanohenriesInOneHenry, (double)nanohenryQuantity.Value, NanohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Nanohenry, nanohenryQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricInductanceUnit unit) + { + var quantity = ElectricInductance.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricInductanceUnit unit) { - var quantityInBaseUnit = ElectricInductance.FromHenries(1).ToBaseUnit(); - Assert.Equal(ElectricInductance.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricInductance.Units.FirstOrDefault(u => u != ElectricInductance.BaseUnit && u != ElectricInductanceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricInductanceUnit.Undefined) + fromUnit = ElectricInductance.BaseUnit; + + var quantity = ElectricInductance.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs index ddc23fa2c6..dc62cb8d5d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -51,6 +52,28 @@ public abstract partial class ElectricPotentialAcTestsBase : QuantityTestsBase protected virtual double VoltsAcTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricPotentialAcUnit unit) + { + return unit switch + { + ElectricPotentialAcUnit.KilovoltAc => (KilovoltsAcInOneVoltAc, KilovoltsAcTolerance), + ElectricPotentialAcUnit.MegavoltAc => (MegavoltsAcInOneVoltAc, MegavoltsAcTolerance), + ElectricPotentialAcUnit.MicrovoltAc => (MicrovoltsAcInOneVoltAc, MicrovoltsAcTolerance), + ElectricPotentialAcUnit.MillivoltAc => (MillivoltsAcInOneVoltAc, MillivoltsAcTolerance), + ElectricPotentialAcUnit.VoltAc => (VoltsAcInOneVoltAc, VoltsAcTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricPotentialAcUnit.KilovoltAc }, + new object[] { ElectricPotentialAcUnit.MegavoltAc }, + new object[] { ElectricPotentialAcUnit.MicrovoltAc }, + new object[] { ElectricPotentialAcUnit.MillivoltAc }, + new object[] { ElectricPotentialAcUnit.VoltAc }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -196,37 +219,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricPotentialAcUnit unit) { - var voltac = ElectricPotentialAc.FromVoltsAc(1); - - var kilovoltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.KilovoltAc); - AssertEx.EqualTolerance(KilovoltsAcInOneVoltAc, (double)kilovoltacQuantity.Value, KilovoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.KilovoltAc, kilovoltacQuantity.Unit); + var inBaseUnits = ElectricPotentialAc.From(1.0, ElectricPotentialAc.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megavoltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.MegavoltAc); - AssertEx.EqualTolerance(MegavoltsAcInOneVoltAc, (double)megavoltacQuantity.Value, MegavoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.MegavoltAc, megavoltacQuantity.Unit); - - var microvoltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.MicrovoltAc); - AssertEx.EqualTolerance(MicrovoltsAcInOneVoltAc, (double)microvoltacQuantity.Value, MicrovoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.MicrovoltAc, microvoltacQuantity.Unit); - - var millivoltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.MillivoltAc); - AssertEx.EqualTolerance(MillivoltsAcInOneVoltAc, (double)millivoltacQuantity.Value, MillivoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.MillivoltAc, millivoltacQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var voltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.VoltAc); - AssertEx.EqualTolerance(VoltsAcInOneVoltAc, (double)voltacQuantity.Value, VoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.VoltAc, voltacQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialAcUnit unit) + { + var quantity = ElectricPotentialAc.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialAcUnit unit) { - var quantityInBaseUnit = ElectricPotentialAc.FromVoltsAc(1).ToBaseUnit(); - Assert.Equal(ElectricPotentialAc.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricPotentialAc.Units.FirstOrDefault(u => u != ElectricPotentialAc.BaseUnit && u != ElectricPotentialAcUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricPotentialAcUnit.Undefined) + fromUnit = ElectricPotentialAc.BaseUnit; + + var quantity = ElectricPotentialAc.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs index 987928a2cc..6cbe276aab 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -81,6 +82,58 @@ public abstract partial class ElectricPotentialChangeRateTestsBase : QuantityTes protected virtual double VoltsPerSecondsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricPotentialChangeRateUnit unit) + { + return unit switch + { + ElectricPotentialChangeRateUnit.KilovoltPerHour => (KilovoltsPerHoursInOneVoltPerSecond, KilovoltsPerHoursTolerance), + ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond => (KilovoltsPerMicrosecondsInOneVoltPerSecond, KilovoltsPerMicrosecondsTolerance), + ElectricPotentialChangeRateUnit.KilovoltPerMinute => (KilovoltsPerMinutesInOneVoltPerSecond, KilovoltsPerMinutesTolerance), + ElectricPotentialChangeRateUnit.KilovoltPerSecond => (KilovoltsPerSecondsInOneVoltPerSecond, KilovoltsPerSecondsTolerance), + ElectricPotentialChangeRateUnit.MegavoltPerHour => (MegavoltsPerHoursInOneVoltPerSecond, MegavoltsPerHoursTolerance), + ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond => (MegavoltsPerMicrosecondsInOneVoltPerSecond, MegavoltsPerMicrosecondsTolerance), + ElectricPotentialChangeRateUnit.MegavoltPerMinute => (MegavoltsPerMinutesInOneVoltPerSecond, MegavoltsPerMinutesTolerance), + ElectricPotentialChangeRateUnit.MegavoltPerSecond => (MegavoltsPerSecondsInOneVoltPerSecond, MegavoltsPerSecondsTolerance), + ElectricPotentialChangeRateUnit.MicrovoltPerHour => (MicrovoltsPerHoursInOneVoltPerSecond, MicrovoltsPerHoursTolerance), + ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond => (MicrovoltsPerMicrosecondsInOneVoltPerSecond, MicrovoltsPerMicrosecondsTolerance), + ElectricPotentialChangeRateUnit.MicrovoltPerMinute => (MicrovoltsPerMinutesInOneVoltPerSecond, MicrovoltsPerMinutesTolerance), + ElectricPotentialChangeRateUnit.MicrovoltPerSecond => (MicrovoltsPerSecondsInOneVoltPerSecond, MicrovoltsPerSecondsTolerance), + ElectricPotentialChangeRateUnit.MillivoltPerHour => (MillivoltsPerHoursInOneVoltPerSecond, MillivoltsPerHoursTolerance), + ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond => (MillivoltsPerMicrosecondsInOneVoltPerSecond, MillivoltsPerMicrosecondsTolerance), + ElectricPotentialChangeRateUnit.MillivoltPerMinute => (MillivoltsPerMinutesInOneVoltPerSecond, MillivoltsPerMinutesTolerance), + ElectricPotentialChangeRateUnit.MillivoltPerSecond => (MillivoltsPerSecondsInOneVoltPerSecond, MillivoltsPerSecondsTolerance), + ElectricPotentialChangeRateUnit.VoltPerHour => (VoltsPerHoursInOneVoltPerSecond, VoltsPerHoursTolerance), + ElectricPotentialChangeRateUnit.VoltPerMicrosecond => (VoltsPerMicrosecondsInOneVoltPerSecond, VoltsPerMicrosecondsTolerance), + ElectricPotentialChangeRateUnit.VoltPerMinute => (VoltsPerMinutesInOneVoltPerSecond, VoltsPerMinutesTolerance), + ElectricPotentialChangeRateUnit.VoltPerSecond => (VoltsPerSecondsInOneVoltPerSecond, VoltsPerSecondsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricPotentialChangeRateUnit.KilovoltPerHour }, + new object[] { ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond }, + new object[] { ElectricPotentialChangeRateUnit.KilovoltPerMinute }, + new object[] { ElectricPotentialChangeRateUnit.KilovoltPerSecond }, + new object[] { ElectricPotentialChangeRateUnit.MegavoltPerHour }, + new object[] { ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond }, + new object[] { ElectricPotentialChangeRateUnit.MegavoltPerMinute }, + new object[] { ElectricPotentialChangeRateUnit.MegavoltPerSecond }, + new object[] { ElectricPotentialChangeRateUnit.MicrovoltPerHour }, + new object[] { ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond }, + new object[] { ElectricPotentialChangeRateUnit.MicrovoltPerMinute }, + new object[] { ElectricPotentialChangeRateUnit.MicrovoltPerSecond }, + new object[] { ElectricPotentialChangeRateUnit.MillivoltPerHour }, + new object[] { ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond }, + new object[] { ElectricPotentialChangeRateUnit.MillivoltPerMinute }, + new object[] { ElectricPotentialChangeRateUnit.MillivoltPerSecond }, + new object[] { ElectricPotentialChangeRateUnit.VoltPerHour }, + new object[] { ElectricPotentialChangeRateUnit.VoltPerMicrosecond }, + new object[] { ElectricPotentialChangeRateUnit.VoltPerMinute }, + new object[] { ElectricPotentialChangeRateUnit.VoltPerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -316,97 +369,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricPotentialChangeRateUnit unit) { - var voltpersecond = ElectricPotentialChangeRate.FromVoltsPerSeconds(1); - - var kilovoltperhourQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerHour); - AssertEx.EqualTolerance(KilovoltsPerHoursInOneVoltPerSecond, (double)kilovoltperhourQuantity.Value, KilovoltsPerHoursTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerHour, kilovoltperhourQuantity.Unit); - - var kilovoltpermicrosecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); - AssertEx.EqualTolerance(KilovoltsPerMicrosecondsInOneVoltPerSecond, (double)kilovoltpermicrosecondQuantity.Value, KilovoltsPerMicrosecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, kilovoltpermicrosecondQuantity.Unit); - - var kilovoltperminuteQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerMinute); - AssertEx.EqualTolerance(KilovoltsPerMinutesInOneVoltPerSecond, (double)kilovoltperminuteQuantity.Value, KilovoltsPerMinutesTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerMinute, kilovoltperminuteQuantity.Unit); - - var kilovoltpersecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerSecond); - AssertEx.EqualTolerance(KilovoltsPerSecondsInOneVoltPerSecond, (double)kilovoltpersecondQuantity.Value, KilovoltsPerSecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerSecond, kilovoltpersecondQuantity.Unit); - - var megavoltperhourQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerHour); - AssertEx.EqualTolerance(MegavoltsPerHoursInOneVoltPerSecond, (double)megavoltperhourQuantity.Value, MegavoltsPerHoursTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerHour, megavoltperhourQuantity.Unit); - - var megavoltpermicrosecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); - AssertEx.EqualTolerance(MegavoltsPerMicrosecondsInOneVoltPerSecond, (double)megavoltpermicrosecondQuantity.Value, MegavoltsPerMicrosecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, megavoltpermicrosecondQuantity.Unit); - - var megavoltperminuteQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerMinute); - AssertEx.EqualTolerance(MegavoltsPerMinutesInOneVoltPerSecond, (double)megavoltperminuteQuantity.Value, MegavoltsPerMinutesTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerMinute, megavoltperminuteQuantity.Unit); - - var megavoltpersecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerSecond); - AssertEx.EqualTolerance(MegavoltsPerSecondsInOneVoltPerSecond, (double)megavoltpersecondQuantity.Value, MegavoltsPerSecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerSecond, megavoltpersecondQuantity.Unit); - - var microvoltperhourQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerHour); - AssertEx.EqualTolerance(MicrovoltsPerHoursInOneVoltPerSecond, (double)microvoltperhourQuantity.Value, MicrovoltsPerHoursTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerHour, microvoltperhourQuantity.Unit); - - var microvoltpermicrosecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); - AssertEx.EqualTolerance(MicrovoltsPerMicrosecondsInOneVoltPerSecond, (double)microvoltpermicrosecondQuantity.Value, MicrovoltsPerMicrosecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, microvoltpermicrosecondQuantity.Unit); + var inBaseUnits = ElectricPotentialChangeRate.From(1.0, ElectricPotentialChangeRate.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var microvoltperminuteQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerMinute); - AssertEx.EqualTolerance(MicrovoltsPerMinutesInOneVoltPerSecond, (double)microvoltperminuteQuantity.Value, MicrovoltsPerMinutesTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, microvoltperminuteQuantity.Unit); - - var microvoltpersecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerSecond); - AssertEx.EqualTolerance(MicrovoltsPerSecondsInOneVoltPerSecond, (double)microvoltpersecondQuantity.Value, MicrovoltsPerSecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, microvoltpersecondQuantity.Unit); - - var millivoltperhourQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerHour); - AssertEx.EqualTolerance(MillivoltsPerHoursInOneVoltPerSecond, (double)millivoltperhourQuantity.Value, MillivoltsPerHoursTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerHour, millivoltperhourQuantity.Unit); - - var millivoltpermicrosecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); - AssertEx.EqualTolerance(MillivoltsPerMicrosecondsInOneVoltPerSecond, (double)millivoltpermicrosecondQuantity.Value, MillivoltsPerMicrosecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, millivoltpermicrosecondQuantity.Unit); - - var millivoltperminuteQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerMinute); - AssertEx.EqualTolerance(MillivoltsPerMinutesInOneVoltPerSecond, (double)millivoltperminuteQuantity.Value, MillivoltsPerMinutesTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerMinute, millivoltperminuteQuantity.Unit); - - var millivoltpersecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerSecond); - AssertEx.EqualTolerance(MillivoltsPerSecondsInOneVoltPerSecond, (double)millivoltpersecondQuantity.Value, MillivoltsPerSecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerSecond, millivoltpersecondQuantity.Unit); - - var voltperhourQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.VoltPerHour); - AssertEx.EqualTolerance(VoltsPerHoursInOneVoltPerSecond, (double)voltperhourQuantity.Value, VoltsPerHoursTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerHour, voltperhourQuantity.Unit); - - var voltpermicrosecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.VoltPerMicrosecond); - AssertEx.EqualTolerance(VoltsPerMicrosecondsInOneVoltPerSecond, (double)voltpermicrosecondQuantity.Value, VoltsPerMicrosecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, voltpermicrosecondQuantity.Unit); - - var voltperminuteQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.VoltPerMinute); - AssertEx.EqualTolerance(VoltsPerMinutesInOneVoltPerSecond, (double)voltperminuteQuantity.Value, VoltsPerMinutesTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerMinute, voltperminuteQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var voltpersecondQuantity = voltpersecond.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond); - AssertEx.EqualTolerance(VoltsPerSecondsInOneVoltPerSecond, (double)voltpersecondQuantity.Value, VoltsPerSecondsTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerSecond, voltpersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialChangeRateUnit unit) + { + var quantity = ElectricPotentialChangeRate.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialChangeRateUnit unit) { - var quantityInBaseUnit = ElectricPotentialChangeRate.FromVoltsPerSeconds(1).ToBaseUnit(); - Assert.Equal(ElectricPotentialChangeRate.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricPotentialChangeRate.Units.FirstOrDefault(u => u != ElectricPotentialChangeRate.BaseUnit && u != ElectricPotentialChangeRateUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricPotentialChangeRateUnit.Undefined) + fromUnit = ElectricPotentialChangeRate.BaseUnit; + + var quantity = ElectricPotentialChangeRate.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs index 9028ea50e2..df1cfbd31f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -51,6 +52,28 @@ public abstract partial class ElectricPotentialDcTestsBase : QuantityTestsBase protected virtual double VoltsDcTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricPotentialDcUnit unit) + { + return unit switch + { + ElectricPotentialDcUnit.KilovoltDc => (KilovoltsDcInOneVoltDc, KilovoltsDcTolerance), + ElectricPotentialDcUnit.MegavoltDc => (MegavoltsDcInOneVoltDc, MegavoltsDcTolerance), + ElectricPotentialDcUnit.MicrovoltDc => (MicrovoltsDcInOneVoltDc, MicrovoltsDcTolerance), + ElectricPotentialDcUnit.MillivoltDc => (MillivoltsDcInOneVoltDc, MillivoltsDcTolerance), + ElectricPotentialDcUnit.VoltDc => (VoltsDcInOneVoltDc, VoltsDcTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricPotentialDcUnit.KilovoltDc }, + new object[] { ElectricPotentialDcUnit.MegavoltDc }, + new object[] { ElectricPotentialDcUnit.MicrovoltDc }, + new object[] { ElectricPotentialDcUnit.MillivoltDc }, + new object[] { ElectricPotentialDcUnit.VoltDc }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -196,37 +219,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricPotentialDcUnit unit) { - var voltdc = ElectricPotentialDc.FromVoltsDc(1); - - var kilovoltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.KilovoltDc); - AssertEx.EqualTolerance(KilovoltsDcInOneVoltDc, (double)kilovoltdcQuantity.Value, KilovoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.KilovoltDc, kilovoltdcQuantity.Unit); + var inBaseUnits = ElectricPotentialDc.From(1.0, ElectricPotentialDc.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megavoltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.MegavoltDc); - AssertEx.EqualTolerance(MegavoltsDcInOneVoltDc, (double)megavoltdcQuantity.Value, MegavoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.MegavoltDc, megavoltdcQuantity.Unit); - - var microvoltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.MicrovoltDc); - AssertEx.EqualTolerance(MicrovoltsDcInOneVoltDc, (double)microvoltdcQuantity.Value, MicrovoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.MicrovoltDc, microvoltdcQuantity.Unit); - - var millivoltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.MillivoltDc); - AssertEx.EqualTolerance(MillivoltsDcInOneVoltDc, (double)millivoltdcQuantity.Value, MillivoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.MillivoltDc, millivoltdcQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var voltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.VoltDc); - AssertEx.EqualTolerance(VoltsDcInOneVoltDc, (double)voltdcQuantity.Value, VoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.VoltDc, voltdcQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialDcUnit unit) + { + var quantity = ElectricPotentialDc.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialDcUnit unit) { - var quantityInBaseUnit = ElectricPotentialDc.FromVoltsDc(1).ToBaseUnit(); - Assert.Equal(ElectricPotentialDc.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricPotentialDc.Units.FirstOrDefault(u => u != ElectricPotentialDc.BaseUnit && u != ElectricPotentialDcUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricPotentialDcUnit.Undefined) + fromUnit = ElectricPotentialDc.BaseUnit; + + var quantity = ElectricPotentialDc.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs index 5c519932bd..89742b883c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -51,6 +52,28 @@ public abstract partial class ElectricPotentialTestsBase : QuantityTestsBase protected virtual double VoltsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricPotentialUnit unit) + { + return unit switch + { + ElectricPotentialUnit.Kilovolt => (KilovoltsInOneVolt, KilovoltsTolerance), + ElectricPotentialUnit.Megavolt => (MegavoltsInOneVolt, MegavoltsTolerance), + ElectricPotentialUnit.Microvolt => (MicrovoltsInOneVolt, MicrovoltsTolerance), + ElectricPotentialUnit.Millivolt => (MillivoltsInOneVolt, MillivoltsTolerance), + ElectricPotentialUnit.Volt => (VoltsInOneVolt, VoltsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricPotentialUnit.Kilovolt }, + new object[] { ElectricPotentialUnit.Megavolt }, + new object[] { ElectricPotentialUnit.Microvolt }, + new object[] { ElectricPotentialUnit.Millivolt }, + new object[] { ElectricPotentialUnit.Volt }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -196,37 +219,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricPotentialUnit unit) { - var volt = ElectricPotential.FromVolts(1); - - var kilovoltQuantity = volt.ToUnit(ElectricPotentialUnit.Kilovolt); - AssertEx.EqualTolerance(KilovoltsInOneVolt, (double)kilovoltQuantity.Value, KilovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Kilovolt, kilovoltQuantity.Unit); + var inBaseUnits = ElectricPotential.From(1.0, ElectricPotential.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megavoltQuantity = volt.ToUnit(ElectricPotentialUnit.Megavolt); - AssertEx.EqualTolerance(MegavoltsInOneVolt, (double)megavoltQuantity.Value, MegavoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Megavolt, megavoltQuantity.Unit); - - var microvoltQuantity = volt.ToUnit(ElectricPotentialUnit.Microvolt); - AssertEx.EqualTolerance(MicrovoltsInOneVolt, (double)microvoltQuantity.Value, MicrovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Microvolt, microvoltQuantity.Unit); - - var millivoltQuantity = volt.ToUnit(ElectricPotentialUnit.Millivolt); - AssertEx.EqualTolerance(MillivoltsInOneVolt, (double)millivoltQuantity.Value, MillivoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Millivolt, millivoltQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var voltQuantity = volt.ToUnit(ElectricPotentialUnit.Volt); - AssertEx.EqualTolerance(VoltsInOneVolt, (double)voltQuantity.Value, VoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Volt, voltQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialUnit unit) + { + var quantity = ElectricPotential.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialUnit unit) { - var quantityInBaseUnit = ElectricPotential.FromVolts(1).ToBaseUnit(); - Assert.Equal(ElectricPotential.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricPotential.Units.FirstOrDefault(u => u != ElectricPotential.BaseUnit && u != ElectricPotentialUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricPotentialUnit.Undefined) + fromUnit = ElectricPotential.BaseUnit; + + var quantity = ElectricPotential.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs index 7a656c484d..fedf7e6908 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -53,6 +54,30 @@ public abstract partial class ElectricResistanceTestsBase : QuantityTestsBase protected virtual double OhmsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricResistanceUnit unit) + { + return unit switch + { + ElectricResistanceUnit.Gigaohm => (GigaohmsInOneOhm, GigaohmsTolerance), + ElectricResistanceUnit.Kiloohm => (KiloohmsInOneOhm, KiloohmsTolerance), + ElectricResistanceUnit.Megaohm => (MegaohmsInOneOhm, MegaohmsTolerance), + ElectricResistanceUnit.Microohm => (MicroohmsInOneOhm, MicroohmsTolerance), + ElectricResistanceUnit.Milliohm => (MilliohmsInOneOhm, MilliohmsTolerance), + ElectricResistanceUnit.Ohm => (OhmsInOneOhm, OhmsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricResistanceUnit.Gigaohm }, + new object[] { ElectricResistanceUnit.Kiloohm }, + new object[] { ElectricResistanceUnit.Megaohm }, + new object[] { ElectricResistanceUnit.Microohm }, + new object[] { ElectricResistanceUnit.Milliohm }, + new object[] { ElectricResistanceUnit.Ohm }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -204,41 +229,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricResistanceUnit unit) { - var ohm = ElectricResistance.FromOhms(1); - - var gigaohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Gigaohm); - AssertEx.EqualTolerance(GigaohmsInOneOhm, (double)gigaohmQuantity.Value, GigaohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Gigaohm, gigaohmQuantity.Unit); + var inBaseUnits = ElectricResistance.From(1.0, ElectricResistance.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kiloohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Kiloohm); - AssertEx.EqualTolerance(KiloohmsInOneOhm, (double)kiloohmQuantity.Value, KiloohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Kiloohm, kiloohmQuantity.Unit); - - var megaohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Megaohm); - AssertEx.EqualTolerance(MegaohmsInOneOhm, (double)megaohmQuantity.Value, MegaohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Megaohm, megaohmQuantity.Unit); - - var microohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Microohm); - AssertEx.EqualTolerance(MicroohmsInOneOhm, (double)microohmQuantity.Value, MicroohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Microohm, microohmQuantity.Unit); - - var milliohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Milliohm); - AssertEx.EqualTolerance(MilliohmsInOneOhm, (double)milliohmQuantity.Value, MilliohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Milliohm, milliohmQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var ohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Ohm); - AssertEx.EqualTolerance(OhmsInOneOhm, (double)ohmQuantity.Value, OhmsTolerance); - Assert.Equal(ElectricResistanceUnit.Ohm, ohmQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricResistanceUnit unit) + { + var quantity = ElectricResistance.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricResistanceUnit unit) { - var quantityInBaseUnit = ElectricResistance.FromOhms(1).ToBaseUnit(); - Assert.Equal(ElectricResistance.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricResistance.Units.FirstOrDefault(u => u != ElectricResistance.BaseUnit && u != ElectricResistanceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricResistanceUnit.Undefined) + fromUnit = ElectricResistance.BaseUnit; + + var quantity = ElectricResistance.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs index 6bdd2c7cd0..3c9463fa71 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -69,6 +70,46 @@ public abstract partial class ElectricResistivityTestsBase : QuantityTestsBase protected virtual double PicoohmMetersTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricResistivityUnit unit) + { + return unit switch + { + ElectricResistivityUnit.KiloohmCentimeter => (KiloohmsCentimeterInOneOhmMeter, KiloohmsCentimeterTolerance), + ElectricResistivityUnit.KiloohmMeter => (KiloohmMetersInOneOhmMeter, KiloohmMetersTolerance), + ElectricResistivityUnit.MegaohmCentimeter => (MegaohmsCentimeterInOneOhmMeter, MegaohmsCentimeterTolerance), + ElectricResistivityUnit.MegaohmMeter => (MegaohmMetersInOneOhmMeter, MegaohmMetersTolerance), + ElectricResistivityUnit.MicroohmCentimeter => (MicroohmsCentimeterInOneOhmMeter, MicroohmsCentimeterTolerance), + ElectricResistivityUnit.MicroohmMeter => (MicroohmMetersInOneOhmMeter, MicroohmMetersTolerance), + ElectricResistivityUnit.MilliohmCentimeter => (MilliohmsCentimeterInOneOhmMeter, MilliohmsCentimeterTolerance), + ElectricResistivityUnit.MilliohmMeter => (MilliohmMetersInOneOhmMeter, MilliohmMetersTolerance), + ElectricResistivityUnit.NanoohmCentimeter => (NanoohmsCentimeterInOneOhmMeter, NanoohmsCentimeterTolerance), + ElectricResistivityUnit.NanoohmMeter => (NanoohmMetersInOneOhmMeter, NanoohmMetersTolerance), + ElectricResistivityUnit.OhmCentimeter => (OhmsCentimeterInOneOhmMeter, OhmsCentimeterTolerance), + ElectricResistivityUnit.OhmMeter => (OhmMetersInOneOhmMeter, OhmMetersTolerance), + ElectricResistivityUnit.PicoohmCentimeter => (PicoohmsCentimeterInOneOhmMeter, PicoohmsCentimeterTolerance), + ElectricResistivityUnit.PicoohmMeter => (PicoohmMetersInOneOhmMeter, PicoohmMetersTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricResistivityUnit.KiloohmCentimeter }, + new object[] { ElectricResistivityUnit.KiloohmMeter }, + new object[] { ElectricResistivityUnit.MegaohmCentimeter }, + new object[] { ElectricResistivityUnit.MegaohmMeter }, + new object[] { ElectricResistivityUnit.MicroohmCentimeter }, + new object[] { ElectricResistivityUnit.MicroohmMeter }, + new object[] { ElectricResistivityUnit.MilliohmCentimeter }, + new object[] { ElectricResistivityUnit.MilliohmMeter }, + new object[] { ElectricResistivityUnit.NanoohmCentimeter }, + new object[] { ElectricResistivityUnit.NanoohmMeter }, + new object[] { ElectricResistivityUnit.OhmCentimeter }, + new object[] { ElectricResistivityUnit.OhmMeter }, + new object[] { ElectricResistivityUnit.PicoohmCentimeter }, + new object[] { ElectricResistivityUnit.PicoohmMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -268,73 +309,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricResistivityUnit unit) { - var ohmmeter = ElectricResistivity.FromOhmMeters(1); - - var kiloohmcentimeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.KiloohmCentimeter); - AssertEx.EqualTolerance(KiloohmsCentimeterInOneOhmMeter, (double)kiloohmcentimeterQuantity.Value, KiloohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.KiloohmCentimeter, kiloohmcentimeterQuantity.Unit); - - var kiloohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.KiloohmMeter); - AssertEx.EqualTolerance(KiloohmMetersInOneOhmMeter, (double)kiloohmmeterQuantity.Value, KiloohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.KiloohmMeter, kiloohmmeterQuantity.Unit); - - var megaohmcentimeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.MegaohmCentimeter); - AssertEx.EqualTolerance(MegaohmsCentimeterInOneOhmMeter, (double)megaohmcentimeterQuantity.Value, MegaohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.MegaohmCentimeter, megaohmcentimeterQuantity.Unit); - - var megaohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.MegaohmMeter); - AssertEx.EqualTolerance(MegaohmMetersInOneOhmMeter, (double)megaohmmeterQuantity.Value, MegaohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.MegaohmMeter, megaohmmeterQuantity.Unit); - - var microohmcentimeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.MicroohmCentimeter); - AssertEx.EqualTolerance(MicroohmsCentimeterInOneOhmMeter, (double)microohmcentimeterQuantity.Value, MicroohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.MicroohmCentimeter, microohmcentimeterQuantity.Unit); - - var microohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.MicroohmMeter); - AssertEx.EqualTolerance(MicroohmMetersInOneOhmMeter, (double)microohmmeterQuantity.Value, MicroohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.MicroohmMeter, microohmmeterQuantity.Unit); - - var milliohmcentimeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.MilliohmCentimeter); - AssertEx.EqualTolerance(MilliohmsCentimeterInOneOhmMeter, (double)milliohmcentimeterQuantity.Value, MilliohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.MilliohmCentimeter, milliohmcentimeterQuantity.Unit); + var inBaseUnits = ElectricResistivity.From(1.0, ElectricResistivity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var milliohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.MilliohmMeter); - AssertEx.EqualTolerance(MilliohmMetersInOneOhmMeter, (double)milliohmmeterQuantity.Value, MilliohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.MilliohmMeter, milliohmmeterQuantity.Unit); - - var nanoohmcentimeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.NanoohmCentimeter); - AssertEx.EqualTolerance(NanoohmsCentimeterInOneOhmMeter, (double)nanoohmcentimeterQuantity.Value, NanoohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.NanoohmCentimeter, nanoohmcentimeterQuantity.Unit); - - var nanoohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.NanoohmMeter); - AssertEx.EqualTolerance(NanoohmMetersInOneOhmMeter, (double)nanoohmmeterQuantity.Value, NanoohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.NanoohmMeter, nanoohmmeterQuantity.Unit); - - var ohmcentimeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.OhmCentimeter); - AssertEx.EqualTolerance(OhmsCentimeterInOneOhmMeter, (double)ohmcentimeterQuantity.Value, OhmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.OhmCentimeter, ohmcentimeterQuantity.Unit); - - var ohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.OhmMeter); - AssertEx.EqualTolerance(OhmMetersInOneOhmMeter, (double)ohmmeterQuantity.Value, OhmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.OhmMeter, ohmmeterQuantity.Unit); - - var picoohmcentimeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.PicoohmCentimeter); - AssertEx.EqualTolerance(PicoohmsCentimeterInOneOhmMeter, (double)picoohmcentimeterQuantity.Value, PicoohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.PicoohmCentimeter, picoohmcentimeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var picoohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.PicoohmMeter); - AssertEx.EqualTolerance(PicoohmMetersInOneOhmMeter, (double)picoohmmeterQuantity.Value, PicoohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.PicoohmMeter, picoohmmeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricResistivityUnit unit) + { + var quantity = ElectricResistivity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricResistivityUnit unit) { - var quantityInBaseUnit = ElectricResistivity.FromOhmMeters(1).ToBaseUnit(); - Assert.Equal(ElectricResistivity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricResistivity.Units.FirstOrDefault(u => u != ElectricResistivity.BaseUnit && u != ElectricResistivityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricResistivityUnit.Undefined) + fromUnit = ElectricResistivity.BaseUnit; + + var quantity = ElectricResistivity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs index efb9b9f710..baf69ed89a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class ElectricSurfaceChargeDensityTestsBase : QuantityTe protected virtual double CoulombsPerSquareMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricSurfaceChargeDensityUnit unit) + { + return unit switch + { + ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter => (CoulombsPerSquareCentimeterInOneCoulombPerSquareMeter, CoulombsPerSquareCentimeterTolerance), + ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch => (CoulombsPerSquareInchInOneCoulombPerSquareMeter, CoulombsPerSquareInchTolerance), + ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter => (CoulombsPerSquareMeterInOneCoulombPerSquareMeter, CoulombsPerSquareMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter }, + new object[] { ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch }, + new object[] { ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ElectricSurfaceChargeDensityUnit unit) { - var coulombpersquaremeter = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); + var inBaseUnits = ElectricSurfaceChargeDensity.From(1.0, ElectricSurfaceChargeDensity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var coulombpersquarecentimeterQuantity = coulombpersquaremeter.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); - AssertEx.EqualTolerance(CoulombsPerSquareCentimeterInOneCoulombPerSquareMeter, (double)coulombpersquarecentimeterQuantity.Value, CoulombsPerSquareCentimeterTolerance); - Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, coulombpersquarecentimeterQuantity.Unit); - - var coulombpersquareinchQuantity = coulombpersquaremeter.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); - AssertEx.EqualTolerance(CoulombsPerSquareInchInOneCoulombPerSquareMeter, (double)coulombpersquareinchQuantity.Value, CoulombsPerSquareInchTolerance); - Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, coulombpersquareinchQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var coulombpersquaremeterQuantity = coulombpersquaremeter.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); - AssertEx.EqualTolerance(CoulombsPerSquareMeterInOneCoulombPerSquareMeter, (double)coulombpersquaremeterQuantity.Value, CoulombsPerSquareMeterTolerance); - Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, coulombpersquaremeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ElectricSurfaceChargeDensityUnit unit) + { + var quantity = ElectricSurfaceChargeDensity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricSurfaceChargeDensityUnit unit) { - var quantityInBaseUnit = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1).ToBaseUnit(); - Assert.Equal(ElectricSurfaceChargeDensity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ElectricSurfaceChargeDensity.Units.FirstOrDefault(u => u != ElectricSurfaceChargeDensity.BaseUnit && u != ElectricSurfaceChargeDensityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ElectricSurfaceChargeDensityUnit.Undefined) + fromUnit = ElectricSurfaceChargeDensity.BaseUnit; + + var quantity = ElectricSurfaceChargeDensity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs index 18f4ef6623..4f31580566 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -113,6 +114,90 @@ public abstract partial class EnergyTestsBase : QuantityTestsBase protected virtual double WattHoursTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(EnergyUnit unit) + { + return unit switch + { + EnergyUnit.BritishThermalUnit => (BritishThermalUnitsInOneJoule, BritishThermalUnitsTolerance), + EnergyUnit.Calorie => (CaloriesInOneJoule, CaloriesTolerance), + EnergyUnit.DecathermEc => (DecathermsEcInOneJoule, DecathermsEcTolerance), + EnergyUnit.DecathermImperial => (DecathermsImperialInOneJoule, DecathermsImperialTolerance), + EnergyUnit.DecathermUs => (DecathermsUsInOneJoule, DecathermsUsTolerance), + EnergyUnit.ElectronVolt => (ElectronVoltsInOneJoule, ElectronVoltsTolerance), + EnergyUnit.Erg => (ErgsInOneJoule, ErgsTolerance), + EnergyUnit.FootPound => (FootPoundsInOneJoule, FootPoundsTolerance), + EnergyUnit.GigabritishThermalUnit => (GigabritishThermalUnitsInOneJoule, GigabritishThermalUnitsTolerance), + EnergyUnit.GigaelectronVolt => (GigaelectronVoltsInOneJoule, GigaelectronVoltsTolerance), + EnergyUnit.Gigajoule => (GigajoulesInOneJoule, GigajoulesTolerance), + EnergyUnit.GigawattDay => (GigawattDaysInOneJoule, GigawattDaysTolerance), + EnergyUnit.GigawattHour => (GigawattHoursInOneJoule, GigawattHoursTolerance), + EnergyUnit.HorsepowerHour => (HorsepowerHoursInOneJoule, HorsepowerHoursTolerance), + EnergyUnit.Joule => (JoulesInOneJoule, JoulesTolerance), + EnergyUnit.KilobritishThermalUnit => (KilobritishThermalUnitsInOneJoule, KilobritishThermalUnitsTolerance), + EnergyUnit.Kilocalorie => (KilocaloriesInOneJoule, KilocaloriesTolerance), + EnergyUnit.KiloelectronVolt => (KiloelectronVoltsInOneJoule, KiloelectronVoltsTolerance), + EnergyUnit.Kilojoule => (KilojoulesInOneJoule, KilojoulesTolerance), + EnergyUnit.KilowattDay => (KilowattDaysInOneJoule, KilowattDaysTolerance), + EnergyUnit.KilowattHour => (KilowattHoursInOneJoule, KilowattHoursTolerance), + EnergyUnit.MegabritishThermalUnit => (MegabritishThermalUnitsInOneJoule, MegabritishThermalUnitsTolerance), + EnergyUnit.Megacalorie => (MegacaloriesInOneJoule, MegacaloriesTolerance), + EnergyUnit.MegaelectronVolt => (MegaelectronVoltsInOneJoule, MegaelectronVoltsTolerance), + EnergyUnit.Megajoule => (MegajoulesInOneJoule, MegajoulesTolerance), + EnergyUnit.MegawattDay => (MegawattDaysInOneJoule, MegawattDaysTolerance), + EnergyUnit.MegawattHour => (MegawattHoursInOneJoule, MegawattHoursTolerance), + EnergyUnit.Millijoule => (MillijoulesInOneJoule, MillijoulesTolerance), + EnergyUnit.TeraelectronVolt => (TeraelectronVoltsInOneJoule, TeraelectronVoltsTolerance), + EnergyUnit.TerawattDay => (TerawattDaysInOneJoule, TerawattDaysTolerance), + EnergyUnit.TerawattHour => (TerawattHoursInOneJoule, TerawattHoursTolerance), + EnergyUnit.ThermEc => (ThermsEcInOneJoule, ThermsEcTolerance), + EnergyUnit.ThermImperial => (ThermsImperialInOneJoule, ThermsImperialTolerance), + EnergyUnit.ThermUs => (ThermsUsInOneJoule, ThermsUsTolerance), + EnergyUnit.WattDay => (WattDaysInOneJoule, WattDaysTolerance), + EnergyUnit.WattHour => (WattHoursInOneJoule, WattHoursTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { EnergyUnit.BritishThermalUnit }, + new object[] { EnergyUnit.Calorie }, + new object[] { EnergyUnit.DecathermEc }, + new object[] { EnergyUnit.DecathermImperial }, + new object[] { EnergyUnit.DecathermUs }, + new object[] { EnergyUnit.ElectronVolt }, + new object[] { EnergyUnit.Erg }, + new object[] { EnergyUnit.FootPound }, + new object[] { EnergyUnit.GigabritishThermalUnit }, + new object[] { EnergyUnit.GigaelectronVolt }, + new object[] { EnergyUnit.Gigajoule }, + new object[] { EnergyUnit.GigawattDay }, + new object[] { EnergyUnit.GigawattHour }, + new object[] { EnergyUnit.HorsepowerHour }, + new object[] { EnergyUnit.Joule }, + new object[] { EnergyUnit.KilobritishThermalUnit }, + new object[] { EnergyUnit.Kilocalorie }, + new object[] { EnergyUnit.KiloelectronVolt }, + new object[] { EnergyUnit.Kilojoule }, + new object[] { EnergyUnit.KilowattDay }, + new object[] { EnergyUnit.KilowattHour }, + new object[] { EnergyUnit.MegabritishThermalUnit }, + new object[] { EnergyUnit.Megacalorie }, + new object[] { EnergyUnit.MegaelectronVolt }, + new object[] { EnergyUnit.Megajoule }, + new object[] { EnergyUnit.MegawattDay }, + new object[] { EnergyUnit.MegawattHour }, + new object[] { EnergyUnit.Millijoule }, + new object[] { EnergyUnit.TeraelectronVolt }, + new object[] { EnergyUnit.TerawattDay }, + new object[] { EnergyUnit.TerawattHour }, + new object[] { EnergyUnit.ThermEc }, + new object[] { EnergyUnit.ThermImperial }, + new object[] { EnergyUnit.ThermUs }, + new object[] { EnergyUnit.WattDay }, + new object[] { EnergyUnit.WattHour }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -444,161 +529,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(EnergyUnit unit) { - var joule = Energy.FromJoules(1); - - var britishthermalunitQuantity = joule.ToUnit(EnergyUnit.BritishThermalUnit); - AssertEx.EqualTolerance(BritishThermalUnitsInOneJoule, (double)britishthermalunitQuantity.Value, BritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.BritishThermalUnit, britishthermalunitQuantity.Unit); - - var calorieQuantity = joule.ToUnit(EnergyUnit.Calorie); - AssertEx.EqualTolerance(CaloriesInOneJoule, (double)calorieQuantity.Value, CaloriesTolerance); - Assert.Equal(EnergyUnit.Calorie, calorieQuantity.Unit); - - var decathermecQuantity = joule.ToUnit(EnergyUnit.DecathermEc); - AssertEx.EqualTolerance(DecathermsEcInOneJoule, (double)decathermecQuantity.Value, DecathermsEcTolerance); - Assert.Equal(EnergyUnit.DecathermEc, decathermecQuantity.Unit); - - var decathermimperialQuantity = joule.ToUnit(EnergyUnit.DecathermImperial); - AssertEx.EqualTolerance(DecathermsImperialInOneJoule, (double)decathermimperialQuantity.Value, DecathermsImperialTolerance); - Assert.Equal(EnergyUnit.DecathermImperial, decathermimperialQuantity.Unit); - - var decathermusQuantity = joule.ToUnit(EnergyUnit.DecathermUs); - AssertEx.EqualTolerance(DecathermsUsInOneJoule, (double)decathermusQuantity.Value, DecathermsUsTolerance); - Assert.Equal(EnergyUnit.DecathermUs, decathermusQuantity.Unit); - - var electronvoltQuantity = joule.ToUnit(EnergyUnit.ElectronVolt); - AssertEx.EqualTolerance(ElectronVoltsInOneJoule, (double)electronvoltQuantity.Value, ElectronVoltsTolerance); - Assert.Equal(EnergyUnit.ElectronVolt, electronvoltQuantity.Unit); - - var ergQuantity = joule.ToUnit(EnergyUnit.Erg); - AssertEx.EqualTolerance(ErgsInOneJoule, (double)ergQuantity.Value, ErgsTolerance); - Assert.Equal(EnergyUnit.Erg, ergQuantity.Unit); - - var footpoundQuantity = joule.ToUnit(EnergyUnit.FootPound); - AssertEx.EqualTolerance(FootPoundsInOneJoule, (double)footpoundQuantity.Value, FootPoundsTolerance); - Assert.Equal(EnergyUnit.FootPound, footpoundQuantity.Unit); - - var gigabritishthermalunitQuantity = joule.ToUnit(EnergyUnit.GigabritishThermalUnit); - AssertEx.EqualTolerance(GigabritishThermalUnitsInOneJoule, (double)gigabritishthermalunitQuantity.Value, GigabritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.GigabritishThermalUnit, gigabritishthermalunitQuantity.Unit); - - var gigaelectronvoltQuantity = joule.ToUnit(EnergyUnit.GigaelectronVolt); - AssertEx.EqualTolerance(GigaelectronVoltsInOneJoule, (double)gigaelectronvoltQuantity.Value, GigaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.GigaelectronVolt, gigaelectronvoltQuantity.Unit); - - var gigajouleQuantity = joule.ToUnit(EnergyUnit.Gigajoule); - AssertEx.EqualTolerance(GigajoulesInOneJoule, (double)gigajouleQuantity.Value, GigajoulesTolerance); - Assert.Equal(EnergyUnit.Gigajoule, gigajouleQuantity.Unit); - - var gigawattdayQuantity = joule.ToUnit(EnergyUnit.GigawattDay); - AssertEx.EqualTolerance(GigawattDaysInOneJoule, (double)gigawattdayQuantity.Value, GigawattDaysTolerance); - Assert.Equal(EnergyUnit.GigawattDay, gigawattdayQuantity.Unit); - - var gigawatthourQuantity = joule.ToUnit(EnergyUnit.GigawattHour); - AssertEx.EqualTolerance(GigawattHoursInOneJoule, (double)gigawatthourQuantity.Value, GigawattHoursTolerance); - Assert.Equal(EnergyUnit.GigawattHour, gigawatthourQuantity.Unit); - - var horsepowerhourQuantity = joule.ToUnit(EnergyUnit.HorsepowerHour); - AssertEx.EqualTolerance(HorsepowerHoursInOneJoule, (double)horsepowerhourQuantity.Value, HorsepowerHoursTolerance); - Assert.Equal(EnergyUnit.HorsepowerHour, horsepowerhourQuantity.Unit); - - var jouleQuantity = joule.ToUnit(EnergyUnit.Joule); - AssertEx.EqualTolerance(JoulesInOneJoule, (double)jouleQuantity.Value, JoulesTolerance); - Assert.Equal(EnergyUnit.Joule, jouleQuantity.Unit); - - var kilobritishthermalunitQuantity = joule.ToUnit(EnergyUnit.KilobritishThermalUnit); - AssertEx.EqualTolerance(KilobritishThermalUnitsInOneJoule, (double)kilobritishthermalunitQuantity.Value, KilobritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.KilobritishThermalUnit, kilobritishthermalunitQuantity.Unit); + var inBaseUnits = Energy.From(1.0, Energy.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilocalorieQuantity = joule.ToUnit(EnergyUnit.Kilocalorie); - AssertEx.EqualTolerance(KilocaloriesInOneJoule, (double)kilocalorieQuantity.Value, KilocaloriesTolerance); - Assert.Equal(EnergyUnit.Kilocalorie, kilocalorieQuantity.Unit); - - var kiloelectronvoltQuantity = joule.ToUnit(EnergyUnit.KiloelectronVolt); - AssertEx.EqualTolerance(KiloelectronVoltsInOneJoule, (double)kiloelectronvoltQuantity.Value, KiloelectronVoltsTolerance); - Assert.Equal(EnergyUnit.KiloelectronVolt, kiloelectronvoltQuantity.Unit); - - var kilojouleQuantity = joule.ToUnit(EnergyUnit.Kilojoule); - AssertEx.EqualTolerance(KilojoulesInOneJoule, (double)kilojouleQuantity.Value, KilojoulesTolerance); - Assert.Equal(EnergyUnit.Kilojoule, kilojouleQuantity.Unit); - - var kilowattdayQuantity = joule.ToUnit(EnergyUnit.KilowattDay); - AssertEx.EqualTolerance(KilowattDaysInOneJoule, (double)kilowattdayQuantity.Value, KilowattDaysTolerance); - Assert.Equal(EnergyUnit.KilowattDay, kilowattdayQuantity.Unit); - - var kilowatthourQuantity = joule.ToUnit(EnergyUnit.KilowattHour); - AssertEx.EqualTolerance(KilowattHoursInOneJoule, (double)kilowatthourQuantity.Value, KilowattHoursTolerance); - Assert.Equal(EnergyUnit.KilowattHour, kilowatthourQuantity.Unit); - - var megabritishthermalunitQuantity = joule.ToUnit(EnergyUnit.MegabritishThermalUnit); - AssertEx.EqualTolerance(MegabritishThermalUnitsInOneJoule, (double)megabritishthermalunitQuantity.Value, MegabritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.MegabritishThermalUnit, megabritishthermalunitQuantity.Unit); - - var megacalorieQuantity = joule.ToUnit(EnergyUnit.Megacalorie); - AssertEx.EqualTolerance(MegacaloriesInOneJoule, (double)megacalorieQuantity.Value, MegacaloriesTolerance); - Assert.Equal(EnergyUnit.Megacalorie, megacalorieQuantity.Unit); - - var megaelectronvoltQuantity = joule.ToUnit(EnergyUnit.MegaelectronVolt); - AssertEx.EqualTolerance(MegaelectronVoltsInOneJoule, (double)megaelectronvoltQuantity.Value, MegaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.MegaelectronVolt, megaelectronvoltQuantity.Unit); - - var megajouleQuantity = joule.ToUnit(EnergyUnit.Megajoule); - AssertEx.EqualTolerance(MegajoulesInOneJoule, (double)megajouleQuantity.Value, MegajoulesTolerance); - Assert.Equal(EnergyUnit.Megajoule, megajouleQuantity.Unit); - - var megawattdayQuantity = joule.ToUnit(EnergyUnit.MegawattDay); - AssertEx.EqualTolerance(MegawattDaysInOneJoule, (double)megawattdayQuantity.Value, MegawattDaysTolerance); - Assert.Equal(EnergyUnit.MegawattDay, megawattdayQuantity.Unit); - - var megawatthourQuantity = joule.ToUnit(EnergyUnit.MegawattHour); - AssertEx.EqualTolerance(MegawattHoursInOneJoule, (double)megawatthourQuantity.Value, MegawattHoursTolerance); - Assert.Equal(EnergyUnit.MegawattHour, megawatthourQuantity.Unit); - - var millijouleQuantity = joule.ToUnit(EnergyUnit.Millijoule); - AssertEx.EqualTolerance(MillijoulesInOneJoule, (double)millijouleQuantity.Value, MillijoulesTolerance); - Assert.Equal(EnergyUnit.Millijoule, millijouleQuantity.Unit); - - var teraelectronvoltQuantity = joule.ToUnit(EnergyUnit.TeraelectronVolt); - AssertEx.EqualTolerance(TeraelectronVoltsInOneJoule, (double)teraelectronvoltQuantity.Value, TeraelectronVoltsTolerance); - Assert.Equal(EnergyUnit.TeraelectronVolt, teraelectronvoltQuantity.Unit); - - var terawattdayQuantity = joule.ToUnit(EnergyUnit.TerawattDay); - AssertEx.EqualTolerance(TerawattDaysInOneJoule, (double)terawattdayQuantity.Value, TerawattDaysTolerance); - Assert.Equal(EnergyUnit.TerawattDay, terawattdayQuantity.Unit); - - var terawatthourQuantity = joule.ToUnit(EnergyUnit.TerawattHour); - AssertEx.EqualTolerance(TerawattHoursInOneJoule, (double)terawatthourQuantity.Value, TerawattHoursTolerance); - Assert.Equal(EnergyUnit.TerawattHour, terawatthourQuantity.Unit); - - var thermecQuantity = joule.ToUnit(EnergyUnit.ThermEc); - AssertEx.EqualTolerance(ThermsEcInOneJoule, (double)thermecQuantity.Value, ThermsEcTolerance); - Assert.Equal(EnergyUnit.ThermEc, thermecQuantity.Unit); - - var thermimperialQuantity = joule.ToUnit(EnergyUnit.ThermImperial); - AssertEx.EqualTolerance(ThermsImperialInOneJoule, (double)thermimperialQuantity.Value, ThermsImperialTolerance); - Assert.Equal(EnergyUnit.ThermImperial, thermimperialQuantity.Unit); - - var thermusQuantity = joule.ToUnit(EnergyUnit.ThermUs); - AssertEx.EqualTolerance(ThermsUsInOneJoule, (double)thermusQuantity.Value, ThermsUsTolerance); - Assert.Equal(EnergyUnit.ThermUs, thermusQuantity.Unit); - - var wattdayQuantity = joule.ToUnit(EnergyUnit.WattDay); - AssertEx.EqualTolerance(WattDaysInOneJoule, (double)wattdayQuantity.Value, WattDaysTolerance); - Assert.Equal(EnergyUnit.WattDay, wattdayQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var watthourQuantity = joule.ToUnit(EnergyUnit.WattHour); - AssertEx.EqualTolerance(WattHoursInOneJoule, (double)watthourQuantity.Value, WattHoursTolerance); - Assert.Equal(EnergyUnit.WattHour, watthourQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(EnergyUnit unit) + { + var quantity = Energy.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EnergyUnit unit) { - var quantityInBaseUnit = Energy.FromJoules(1).ToBaseUnit(); - Assert.Equal(Energy.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Energy.Units.FirstOrDefault(u => u != Energy.BaseUnit && u != EnergyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == EnergyUnit.Undefined) + fromUnit = Energy.BaseUnit; + + var quantity = Energy.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs index 5e44a83900..55859a487e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -55,6 +56,32 @@ public abstract partial class EntropyTestsBase : QuantityTestsBase protected virtual double MegajoulesPerKelvinTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(EntropyUnit unit) + { + return unit switch + { + EntropyUnit.CaloriePerKelvin => (CaloriesPerKelvinInOneJoulePerKelvin, CaloriesPerKelvinTolerance), + EntropyUnit.JoulePerDegreeCelsius => (JoulesPerDegreeCelsiusInOneJoulePerKelvin, JoulesPerDegreeCelsiusTolerance), + EntropyUnit.JoulePerKelvin => (JoulesPerKelvinInOneJoulePerKelvin, JoulesPerKelvinTolerance), + EntropyUnit.KilocaloriePerKelvin => (KilocaloriesPerKelvinInOneJoulePerKelvin, KilocaloriesPerKelvinTolerance), + EntropyUnit.KilojoulePerDegreeCelsius => (KilojoulesPerDegreeCelsiusInOneJoulePerKelvin, KilojoulesPerDegreeCelsiusTolerance), + EntropyUnit.KilojoulePerKelvin => (KilojoulesPerKelvinInOneJoulePerKelvin, KilojoulesPerKelvinTolerance), + EntropyUnit.MegajoulePerKelvin => (MegajoulesPerKelvinInOneJoulePerKelvin, MegajoulesPerKelvinTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { EntropyUnit.CaloriePerKelvin }, + new object[] { EntropyUnit.JoulePerDegreeCelsius }, + new object[] { EntropyUnit.JoulePerKelvin }, + new object[] { EntropyUnit.KilocaloriePerKelvin }, + new object[] { EntropyUnit.KilojoulePerDegreeCelsius }, + new object[] { EntropyUnit.KilojoulePerKelvin }, + new object[] { EntropyUnit.MegajoulePerKelvin }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -212,45 +239,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(EntropyUnit unit) { - var jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - - var calorieperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.CaloriePerKelvin); - AssertEx.EqualTolerance(CaloriesPerKelvinInOneJoulePerKelvin, (double)calorieperkelvinQuantity.Value, CaloriesPerKelvinTolerance); - Assert.Equal(EntropyUnit.CaloriePerKelvin, calorieperkelvinQuantity.Unit); - - var jouleperdegreecelsiusQuantity = jouleperkelvin.ToUnit(EntropyUnit.JoulePerDegreeCelsius); - AssertEx.EqualTolerance(JoulesPerDegreeCelsiusInOneJoulePerKelvin, (double)jouleperdegreecelsiusQuantity.Value, JoulesPerDegreeCelsiusTolerance); - Assert.Equal(EntropyUnit.JoulePerDegreeCelsius, jouleperdegreecelsiusQuantity.Unit); + var inBaseUnits = Entropy.From(1.0, Entropy.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var jouleperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.JoulePerKelvin); - AssertEx.EqualTolerance(JoulesPerKelvinInOneJoulePerKelvin, (double)jouleperkelvinQuantity.Value, JoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.JoulePerKelvin, jouleperkelvinQuantity.Unit); - - var kilocalorieperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.KilocaloriePerKelvin); - AssertEx.EqualTolerance(KilocaloriesPerKelvinInOneJoulePerKelvin, (double)kilocalorieperkelvinQuantity.Value, KilocaloriesPerKelvinTolerance); - Assert.Equal(EntropyUnit.KilocaloriePerKelvin, kilocalorieperkelvinQuantity.Unit); - - var kilojouleperdegreecelsiusQuantity = jouleperkelvin.ToUnit(EntropyUnit.KilojoulePerDegreeCelsius); - AssertEx.EqualTolerance(KilojoulesPerDegreeCelsiusInOneJoulePerKelvin, (double)kilojouleperdegreecelsiusQuantity.Value, KilojoulesPerDegreeCelsiusTolerance); - Assert.Equal(EntropyUnit.KilojoulePerDegreeCelsius, kilojouleperdegreecelsiusQuantity.Unit); - - var kilojouleperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.KilojoulePerKelvin); - AssertEx.EqualTolerance(KilojoulesPerKelvinInOneJoulePerKelvin, (double)kilojouleperkelvinQuantity.Value, KilojoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.KilojoulePerKelvin, kilojouleperkelvinQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var megajouleperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.MegajoulePerKelvin); - AssertEx.EqualTolerance(MegajoulesPerKelvinInOneJoulePerKelvin, (double)megajouleperkelvinQuantity.Value, MegajoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.MegajoulePerKelvin, megajouleperkelvinQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(EntropyUnit unit) + { + var quantity = Entropy.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EntropyUnit unit) { - var quantityInBaseUnit = Entropy.FromJoulesPerKelvin(1).ToBaseUnit(); - Assert.Equal(Entropy.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Entropy.Units.FirstOrDefault(u => u != Entropy.BaseUnit && u != EntropyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == EntropyUnit.Undefined) + fromUnit = Entropy.BaseUnit; + + var quantity = Entropy.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs index ebdfab01de..fe9203fc90 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -71,6 +72,48 @@ public abstract partial class ForceChangeRateTestsBase : QuantityTestsBase protected virtual double PoundsForcePerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ForceChangeRateUnit unit) + { + return unit switch + { + ForceChangeRateUnit.CentinewtonPerSecond => (CentinewtonsPerSecondInOneNewtonPerSecond, CentinewtonsPerSecondTolerance), + ForceChangeRateUnit.DecanewtonPerMinute => (DecanewtonsPerMinuteInOneNewtonPerSecond, DecanewtonsPerMinuteTolerance), + ForceChangeRateUnit.DecanewtonPerSecond => (DecanewtonsPerSecondInOneNewtonPerSecond, DecanewtonsPerSecondTolerance), + ForceChangeRateUnit.DecinewtonPerSecond => (DecinewtonsPerSecondInOneNewtonPerSecond, DecinewtonsPerSecondTolerance), + ForceChangeRateUnit.KilonewtonPerMinute => (KilonewtonsPerMinuteInOneNewtonPerSecond, KilonewtonsPerMinuteTolerance), + ForceChangeRateUnit.KilonewtonPerSecond => (KilonewtonsPerSecondInOneNewtonPerSecond, KilonewtonsPerSecondTolerance), + ForceChangeRateUnit.KilopoundForcePerMinute => (KilopoundsForcePerMinuteInOneNewtonPerSecond, KilopoundsForcePerMinuteTolerance), + ForceChangeRateUnit.KilopoundForcePerSecond => (KilopoundsForcePerSecondInOneNewtonPerSecond, KilopoundsForcePerSecondTolerance), + ForceChangeRateUnit.MicronewtonPerSecond => (MicronewtonsPerSecondInOneNewtonPerSecond, MicronewtonsPerSecondTolerance), + ForceChangeRateUnit.MillinewtonPerSecond => (MillinewtonsPerSecondInOneNewtonPerSecond, MillinewtonsPerSecondTolerance), + ForceChangeRateUnit.NanonewtonPerSecond => (NanonewtonsPerSecondInOneNewtonPerSecond, NanonewtonsPerSecondTolerance), + ForceChangeRateUnit.NewtonPerMinute => (NewtonsPerMinuteInOneNewtonPerSecond, NewtonsPerMinuteTolerance), + ForceChangeRateUnit.NewtonPerSecond => (NewtonsPerSecondInOneNewtonPerSecond, NewtonsPerSecondTolerance), + ForceChangeRateUnit.PoundForcePerMinute => (PoundsForcePerMinuteInOneNewtonPerSecond, PoundsForcePerMinuteTolerance), + ForceChangeRateUnit.PoundForcePerSecond => (PoundsForcePerSecondInOneNewtonPerSecond, PoundsForcePerSecondTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ForceChangeRateUnit.CentinewtonPerSecond }, + new object[] { ForceChangeRateUnit.DecanewtonPerMinute }, + new object[] { ForceChangeRateUnit.DecanewtonPerSecond }, + new object[] { ForceChangeRateUnit.DecinewtonPerSecond }, + new object[] { ForceChangeRateUnit.KilonewtonPerMinute }, + new object[] { ForceChangeRateUnit.KilonewtonPerSecond }, + new object[] { ForceChangeRateUnit.KilopoundForcePerMinute }, + new object[] { ForceChangeRateUnit.KilopoundForcePerSecond }, + new object[] { ForceChangeRateUnit.MicronewtonPerSecond }, + new object[] { ForceChangeRateUnit.MillinewtonPerSecond }, + new object[] { ForceChangeRateUnit.NanonewtonPerSecond }, + new object[] { ForceChangeRateUnit.NewtonPerMinute }, + new object[] { ForceChangeRateUnit.NewtonPerSecond }, + new object[] { ForceChangeRateUnit.PoundForcePerMinute }, + new object[] { ForceChangeRateUnit.PoundForcePerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -276,77 +319,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ForceChangeRateUnit unit) { - var newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - - var centinewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.CentinewtonPerSecond); - AssertEx.EqualTolerance(CentinewtonsPerSecondInOneNewtonPerSecond, (double)centinewtonpersecondQuantity.Value, CentinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.CentinewtonPerSecond, centinewtonpersecondQuantity.Unit); - - var decanewtonperminuteQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.DecanewtonPerMinute); - AssertEx.EqualTolerance(DecanewtonsPerMinuteInOneNewtonPerSecond, (double)decanewtonperminuteQuantity.Value, DecanewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.DecanewtonPerMinute, decanewtonperminuteQuantity.Unit); - - var decanewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.DecanewtonPerSecond); - AssertEx.EqualTolerance(DecanewtonsPerSecondInOneNewtonPerSecond, (double)decanewtonpersecondQuantity.Value, DecanewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.DecanewtonPerSecond, decanewtonpersecondQuantity.Unit); - - var decinewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.DecinewtonPerSecond); - AssertEx.EqualTolerance(DecinewtonsPerSecondInOneNewtonPerSecond, (double)decinewtonpersecondQuantity.Value, DecinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.DecinewtonPerSecond, decinewtonpersecondQuantity.Unit); - - var kilonewtonperminuteQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.KilonewtonPerMinute); - AssertEx.EqualTolerance(KilonewtonsPerMinuteInOneNewtonPerSecond, (double)kilonewtonperminuteQuantity.Value, KilonewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilonewtonPerMinute, kilonewtonperminuteQuantity.Unit); - - var kilonewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.KilonewtonPerSecond); - AssertEx.EqualTolerance(KilonewtonsPerSecondInOneNewtonPerSecond, (double)kilonewtonpersecondQuantity.Value, KilonewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilonewtonPerSecond, kilonewtonpersecondQuantity.Unit); - - var kilopoundforceperminuteQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.KilopoundForcePerMinute); - AssertEx.EqualTolerance(KilopoundsForcePerMinuteInOneNewtonPerSecond, (double)kilopoundforceperminuteQuantity.Value, KilopoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerMinute, kilopoundforceperminuteQuantity.Unit); + var inBaseUnits = ForceChangeRate.From(1.0, ForceChangeRate.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilopoundforcepersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.KilopoundForcePerSecond); - AssertEx.EqualTolerance(KilopoundsForcePerSecondInOneNewtonPerSecond, (double)kilopoundforcepersecondQuantity.Value, KilopoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerSecond, kilopoundforcepersecondQuantity.Unit); - - var micronewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.MicronewtonPerSecond); - AssertEx.EqualTolerance(MicronewtonsPerSecondInOneNewtonPerSecond, (double)micronewtonpersecondQuantity.Value, MicronewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.MicronewtonPerSecond, micronewtonpersecondQuantity.Unit); - - var millinewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.MillinewtonPerSecond); - AssertEx.EqualTolerance(MillinewtonsPerSecondInOneNewtonPerSecond, (double)millinewtonpersecondQuantity.Value, MillinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.MillinewtonPerSecond, millinewtonpersecondQuantity.Unit); - - var nanonewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.NanonewtonPerSecond); - AssertEx.EqualTolerance(NanonewtonsPerSecondInOneNewtonPerSecond, (double)nanonewtonpersecondQuantity.Value, NanonewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.NanonewtonPerSecond, nanonewtonpersecondQuantity.Unit); - - var newtonperminuteQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.NewtonPerMinute); - AssertEx.EqualTolerance(NewtonsPerMinuteInOneNewtonPerSecond, (double)newtonperminuteQuantity.Value, NewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.NewtonPerMinute, newtonperminuteQuantity.Unit); - - var newtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.NewtonPerSecond); - AssertEx.EqualTolerance(NewtonsPerSecondInOneNewtonPerSecond, (double)newtonpersecondQuantity.Value, NewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.NewtonPerSecond, newtonpersecondQuantity.Unit); - - var poundforceperminuteQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.PoundForcePerMinute); - AssertEx.EqualTolerance(PoundsForcePerMinuteInOneNewtonPerSecond, (double)poundforceperminuteQuantity.Value, PoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.PoundForcePerMinute, poundforceperminuteQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var poundforcepersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.PoundForcePerSecond); - AssertEx.EqualTolerance(PoundsForcePerSecondInOneNewtonPerSecond, (double)poundforcepersecondQuantity.Value, PoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.PoundForcePerSecond, poundforcepersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ForceChangeRateUnit unit) + { + var quantity = ForceChangeRate.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForceChangeRateUnit unit) { - var quantityInBaseUnit = ForceChangeRate.FromNewtonsPerSecond(1).ToBaseUnit(); - Assert.Equal(ForceChangeRate.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ForceChangeRate.Units.FirstOrDefault(u => u != ForceChangeRate.BaseUnit && u != ForceChangeRateUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ForceChangeRateUnit.Undefined) + fromUnit = ForceChangeRate.BaseUnit; + + var quantity = ForceChangeRate.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs index 1ba699c782..7ddeacc15a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -117,6 +118,94 @@ public abstract partial class ForcePerLengthTestsBase : QuantityTestsBase protected virtual double TonnesForcePerMillimeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ForcePerLengthUnit unit) + { + return unit switch + { + ForcePerLengthUnit.CentinewtonPerCentimeter => (CentinewtonsPerCentimeterInOneNewtonPerMeter, CentinewtonsPerCentimeterTolerance), + ForcePerLengthUnit.CentinewtonPerMeter => (CentinewtonsPerMeterInOneNewtonPerMeter, CentinewtonsPerMeterTolerance), + ForcePerLengthUnit.CentinewtonPerMillimeter => (CentinewtonsPerMillimeterInOneNewtonPerMeter, CentinewtonsPerMillimeterTolerance), + ForcePerLengthUnit.DecanewtonPerCentimeter => (DecanewtonsPerCentimeterInOneNewtonPerMeter, DecanewtonsPerCentimeterTolerance), + ForcePerLengthUnit.DecanewtonPerMeter => (DecanewtonsPerMeterInOneNewtonPerMeter, DecanewtonsPerMeterTolerance), + ForcePerLengthUnit.DecanewtonPerMillimeter => (DecanewtonsPerMillimeterInOneNewtonPerMeter, DecanewtonsPerMillimeterTolerance), + ForcePerLengthUnit.DecinewtonPerCentimeter => (DecinewtonsPerCentimeterInOneNewtonPerMeter, DecinewtonsPerCentimeterTolerance), + ForcePerLengthUnit.DecinewtonPerMeter => (DecinewtonsPerMeterInOneNewtonPerMeter, DecinewtonsPerMeterTolerance), + ForcePerLengthUnit.DecinewtonPerMillimeter => (DecinewtonsPerMillimeterInOneNewtonPerMeter, DecinewtonsPerMillimeterTolerance), + ForcePerLengthUnit.KilogramForcePerCentimeter => (KilogramsForcePerCentimeterInOneNewtonPerMeter, KilogramsForcePerCentimeterTolerance), + ForcePerLengthUnit.KilogramForcePerMeter => (KilogramsForcePerMeterInOneNewtonPerMeter, KilogramsForcePerMeterTolerance), + ForcePerLengthUnit.KilogramForcePerMillimeter => (KilogramsForcePerMillimeterInOneNewtonPerMeter, KilogramsForcePerMillimeterTolerance), + ForcePerLengthUnit.KilonewtonPerCentimeter => (KilonewtonsPerCentimeterInOneNewtonPerMeter, KilonewtonsPerCentimeterTolerance), + ForcePerLengthUnit.KilonewtonPerMeter => (KilonewtonsPerMeterInOneNewtonPerMeter, KilonewtonsPerMeterTolerance), + ForcePerLengthUnit.KilonewtonPerMillimeter => (KilonewtonsPerMillimeterInOneNewtonPerMeter, KilonewtonsPerMillimeterTolerance), + ForcePerLengthUnit.KilopoundForcePerFoot => (KilopoundsForcePerFootInOneNewtonPerMeter, KilopoundsForcePerFootTolerance), + ForcePerLengthUnit.KilopoundForcePerInch => (KilopoundsForcePerInchInOneNewtonPerMeter, KilopoundsForcePerInchTolerance), + ForcePerLengthUnit.MeganewtonPerCentimeter => (MeganewtonsPerCentimeterInOneNewtonPerMeter, MeganewtonsPerCentimeterTolerance), + ForcePerLengthUnit.MeganewtonPerMeter => (MeganewtonsPerMeterInOneNewtonPerMeter, MeganewtonsPerMeterTolerance), + ForcePerLengthUnit.MeganewtonPerMillimeter => (MeganewtonsPerMillimeterInOneNewtonPerMeter, MeganewtonsPerMillimeterTolerance), + ForcePerLengthUnit.MicronewtonPerCentimeter => (MicronewtonsPerCentimeterInOneNewtonPerMeter, MicronewtonsPerCentimeterTolerance), + ForcePerLengthUnit.MicronewtonPerMeter => (MicronewtonsPerMeterInOneNewtonPerMeter, MicronewtonsPerMeterTolerance), + ForcePerLengthUnit.MicronewtonPerMillimeter => (MicronewtonsPerMillimeterInOneNewtonPerMeter, MicronewtonsPerMillimeterTolerance), + ForcePerLengthUnit.MillinewtonPerCentimeter => (MillinewtonsPerCentimeterInOneNewtonPerMeter, MillinewtonsPerCentimeterTolerance), + ForcePerLengthUnit.MillinewtonPerMeter => (MillinewtonsPerMeterInOneNewtonPerMeter, MillinewtonsPerMeterTolerance), + ForcePerLengthUnit.MillinewtonPerMillimeter => (MillinewtonsPerMillimeterInOneNewtonPerMeter, MillinewtonsPerMillimeterTolerance), + ForcePerLengthUnit.NanonewtonPerCentimeter => (NanonewtonsPerCentimeterInOneNewtonPerMeter, NanonewtonsPerCentimeterTolerance), + ForcePerLengthUnit.NanonewtonPerMeter => (NanonewtonsPerMeterInOneNewtonPerMeter, NanonewtonsPerMeterTolerance), + ForcePerLengthUnit.NanonewtonPerMillimeter => (NanonewtonsPerMillimeterInOneNewtonPerMeter, NanonewtonsPerMillimeterTolerance), + ForcePerLengthUnit.NewtonPerCentimeter => (NewtonsPerCentimeterInOneNewtonPerMeter, NewtonsPerCentimeterTolerance), + ForcePerLengthUnit.NewtonPerMeter => (NewtonsPerMeterInOneNewtonPerMeter, NewtonsPerMeterTolerance), + ForcePerLengthUnit.NewtonPerMillimeter => (NewtonsPerMillimeterInOneNewtonPerMeter, NewtonsPerMillimeterTolerance), + ForcePerLengthUnit.PoundForcePerFoot => (PoundsForcePerFootInOneNewtonPerMeter, PoundsForcePerFootTolerance), + ForcePerLengthUnit.PoundForcePerInch => (PoundsForcePerInchInOneNewtonPerMeter, PoundsForcePerInchTolerance), + ForcePerLengthUnit.PoundForcePerYard => (PoundsForcePerYardInOneNewtonPerMeter, PoundsForcePerYardTolerance), + ForcePerLengthUnit.TonneForcePerCentimeter => (TonnesForcePerCentimeterInOneNewtonPerMeter, TonnesForcePerCentimeterTolerance), + ForcePerLengthUnit.TonneForcePerMeter => (TonnesForcePerMeterInOneNewtonPerMeter, TonnesForcePerMeterTolerance), + ForcePerLengthUnit.TonneForcePerMillimeter => (TonnesForcePerMillimeterInOneNewtonPerMeter, TonnesForcePerMillimeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ForcePerLengthUnit.CentinewtonPerCentimeter }, + new object[] { ForcePerLengthUnit.CentinewtonPerMeter }, + new object[] { ForcePerLengthUnit.CentinewtonPerMillimeter }, + new object[] { ForcePerLengthUnit.DecanewtonPerCentimeter }, + new object[] { ForcePerLengthUnit.DecanewtonPerMeter }, + new object[] { ForcePerLengthUnit.DecanewtonPerMillimeter }, + new object[] { ForcePerLengthUnit.DecinewtonPerCentimeter }, + new object[] { ForcePerLengthUnit.DecinewtonPerMeter }, + new object[] { ForcePerLengthUnit.DecinewtonPerMillimeter }, + new object[] { ForcePerLengthUnit.KilogramForcePerCentimeter }, + new object[] { ForcePerLengthUnit.KilogramForcePerMeter }, + new object[] { ForcePerLengthUnit.KilogramForcePerMillimeter }, + new object[] { ForcePerLengthUnit.KilonewtonPerCentimeter }, + new object[] { ForcePerLengthUnit.KilonewtonPerMeter }, + new object[] { ForcePerLengthUnit.KilonewtonPerMillimeter }, + new object[] { ForcePerLengthUnit.KilopoundForcePerFoot }, + new object[] { ForcePerLengthUnit.KilopoundForcePerInch }, + new object[] { ForcePerLengthUnit.MeganewtonPerCentimeter }, + new object[] { ForcePerLengthUnit.MeganewtonPerMeter }, + new object[] { ForcePerLengthUnit.MeganewtonPerMillimeter }, + new object[] { ForcePerLengthUnit.MicronewtonPerCentimeter }, + new object[] { ForcePerLengthUnit.MicronewtonPerMeter }, + new object[] { ForcePerLengthUnit.MicronewtonPerMillimeter }, + new object[] { ForcePerLengthUnit.MillinewtonPerCentimeter }, + new object[] { ForcePerLengthUnit.MillinewtonPerMeter }, + new object[] { ForcePerLengthUnit.MillinewtonPerMillimeter }, + new object[] { ForcePerLengthUnit.NanonewtonPerCentimeter }, + new object[] { ForcePerLengthUnit.NanonewtonPerMeter }, + new object[] { ForcePerLengthUnit.NanonewtonPerMillimeter }, + new object[] { ForcePerLengthUnit.NewtonPerCentimeter }, + new object[] { ForcePerLengthUnit.NewtonPerMeter }, + new object[] { ForcePerLengthUnit.NewtonPerMillimeter }, + new object[] { ForcePerLengthUnit.PoundForcePerFoot }, + new object[] { ForcePerLengthUnit.PoundForcePerInch }, + new object[] { ForcePerLengthUnit.PoundForcePerYard }, + new object[] { ForcePerLengthUnit.TonneForcePerCentimeter }, + new object[] { ForcePerLengthUnit.TonneForcePerMeter }, + new object[] { ForcePerLengthUnit.TonneForcePerMillimeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -460,169 +549,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ForcePerLengthUnit unit) { - var newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - - var centinewtonpercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.CentinewtonPerCentimeter); - AssertEx.EqualTolerance(CentinewtonsPerCentimeterInOneNewtonPerMeter, (double)centinewtonpercentimeterQuantity.Value, CentinewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerCentimeter, centinewtonpercentimeterQuantity.Unit); - - var centinewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.CentinewtonPerMeter); - AssertEx.EqualTolerance(CentinewtonsPerMeterInOneNewtonPerMeter, (double)centinewtonpermeterQuantity.Value, CentinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerMeter, centinewtonpermeterQuantity.Unit); - - var centinewtonpermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.CentinewtonPerMillimeter); - AssertEx.EqualTolerance(CentinewtonsPerMillimeterInOneNewtonPerMeter, (double)centinewtonpermillimeterQuantity.Value, CentinewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerMillimeter, centinewtonpermillimeterQuantity.Unit); - - var decanewtonpercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.DecanewtonPerCentimeter); - AssertEx.EqualTolerance(DecanewtonsPerCentimeterInOneNewtonPerMeter, (double)decanewtonpercentimeterQuantity.Value, DecanewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecanewtonPerCentimeter, decanewtonpercentimeterQuantity.Unit); - - var decanewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.DecanewtonPerMeter); - AssertEx.EqualTolerance(DecanewtonsPerMeterInOneNewtonPerMeter, (double)decanewtonpermeterQuantity.Value, DecanewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecanewtonPerMeter, decanewtonpermeterQuantity.Unit); - - var decanewtonpermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.DecanewtonPerMillimeter); - AssertEx.EqualTolerance(DecanewtonsPerMillimeterInOneNewtonPerMeter, (double)decanewtonpermillimeterQuantity.Value, DecanewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecanewtonPerMillimeter, decanewtonpermillimeterQuantity.Unit); - - var decinewtonpercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.DecinewtonPerCentimeter); - AssertEx.EqualTolerance(DecinewtonsPerCentimeterInOneNewtonPerMeter, (double)decinewtonpercentimeterQuantity.Value, DecinewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerCentimeter, decinewtonpercentimeterQuantity.Unit); - - var decinewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.DecinewtonPerMeter); - AssertEx.EqualTolerance(DecinewtonsPerMeterInOneNewtonPerMeter, (double)decinewtonpermeterQuantity.Value, DecinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerMeter, decinewtonpermeterQuantity.Unit); - - var decinewtonpermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.DecinewtonPerMillimeter); - AssertEx.EqualTolerance(DecinewtonsPerMillimeterInOneNewtonPerMeter, (double)decinewtonpermillimeterQuantity.Value, DecinewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerMillimeter, decinewtonpermillimeterQuantity.Unit); - - var kilogramforcepercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilogramForcePerCentimeter); - AssertEx.EqualTolerance(KilogramsForcePerCentimeterInOneNewtonPerMeter, (double)kilogramforcepercentimeterQuantity.Value, KilogramsForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerCentimeter, kilogramforcepercentimeterQuantity.Unit); - - var kilogramforcepermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilogramForcePerMeter); - AssertEx.EqualTolerance(KilogramsForcePerMeterInOneNewtonPerMeter, (double)kilogramforcepermeterQuantity.Value, KilogramsForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMeter, kilogramforcepermeterQuantity.Unit); - - var kilogramforcepermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilogramForcePerMillimeter); - AssertEx.EqualTolerance(KilogramsForcePerMillimeterInOneNewtonPerMeter, (double)kilogramforcepermillimeterQuantity.Value, KilogramsForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMillimeter, kilogramforcepermillimeterQuantity.Unit); - - var kilonewtonpercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilonewtonPerCentimeter); - AssertEx.EqualTolerance(KilonewtonsPerCentimeterInOneNewtonPerMeter, (double)kilonewtonpercentimeterQuantity.Value, KilonewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerCentimeter, kilonewtonpercentimeterQuantity.Unit); - - var kilonewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilonewtonPerMeter); - AssertEx.EqualTolerance(KilonewtonsPerMeterInOneNewtonPerMeter, (double)kilonewtonpermeterQuantity.Value, KilonewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerMeter, kilonewtonpermeterQuantity.Unit); - - var kilonewtonpermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilonewtonPerMillimeter); - AssertEx.EqualTolerance(KilonewtonsPerMillimeterInOneNewtonPerMeter, (double)kilonewtonpermillimeterQuantity.Value, KilonewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerMillimeter, kilonewtonpermillimeterQuantity.Unit); - - var kilopoundforceperfootQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilopoundForcePerFoot); - AssertEx.EqualTolerance(KilopoundsForcePerFootInOneNewtonPerMeter, (double)kilopoundforceperfootQuantity.Value, KilopoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerFoot, kilopoundforceperfootQuantity.Unit); - - var kilopoundforceperinchQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilopoundForcePerInch); - AssertEx.EqualTolerance(KilopoundsForcePerInchInOneNewtonPerMeter, (double)kilopoundforceperinchQuantity.Value, KilopoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerInch, kilopoundforceperinchQuantity.Unit); + var inBaseUnits = ForcePerLength.From(1.0, ForcePerLength.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var meganewtonpercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MeganewtonPerCentimeter); - AssertEx.EqualTolerance(MeganewtonsPerCentimeterInOneNewtonPerMeter, (double)meganewtonpercentimeterQuantity.Value, MeganewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MeganewtonPerCentimeter, meganewtonpercentimeterQuantity.Unit); - - var meganewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MeganewtonPerMeter); - AssertEx.EqualTolerance(MeganewtonsPerMeterInOneNewtonPerMeter, (double)meganewtonpermeterQuantity.Value, MeganewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MeganewtonPerMeter, meganewtonpermeterQuantity.Unit); - - var meganewtonpermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MeganewtonPerMillimeter); - AssertEx.EqualTolerance(MeganewtonsPerMillimeterInOneNewtonPerMeter, (double)meganewtonpermillimeterQuantity.Value, MeganewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MeganewtonPerMillimeter, meganewtonpermillimeterQuantity.Unit); - - var micronewtonpercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MicronewtonPerCentimeter); - AssertEx.EqualTolerance(MicronewtonsPerCentimeterInOneNewtonPerMeter, (double)micronewtonpercentimeterQuantity.Value, MicronewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerCentimeter, micronewtonpercentimeterQuantity.Unit); - - var micronewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MicronewtonPerMeter); - AssertEx.EqualTolerance(MicronewtonsPerMeterInOneNewtonPerMeter, (double)micronewtonpermeterQuantity.Value, MicronewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerMeter, micronewtonpermeterQuantity.Unit); - - var micronewtonpermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MicronewtonPerMillimeter); - AssertEx.EqualTolerance(MicronewtonsPerMillimeterInOneNewtonPerMeter, (double)micronewtonpermillimeterQuantity.Value, MicronewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerMillimeter, micronewtonpermillimeterQuantity.Unit); - - var millinewtonpercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MillinewtonPerCentimeter); - AssertEx.EqualTolerance(MillinewtonsPerCentimeterInOneNewtonPerMeter, (double)millinewtonpercentimeterQuantity.Value, MillinewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MillinewtonPerCentimeter, millinewtonpercentimeterQuantity.Unit); - - var millinewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MillinewtonPerMeter); - AssertEx.EqualTolerance(MillinewtonsPerMeterInOneNewtonPerMeter, (double)millinewtonpermeterQuantity.Value, MillinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MillinewtonPerMeter, millinewtonpermeterQuantity.Unit); - - var millinewtonpermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MillinewtonPerMillimeter); - AssertEx.EqualTolerance(MillinewtonsPerMillimeterInOneNewtonPerMeter, (double)millinewtonpermillimeterQuantity.Value, MillinewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MillinewtonPerMillimeter, millinewtonpermillimeterQuantity.Unit); - - var nanonewtonpercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.NanonewtonPerCentimeter); - AssertEx.EqualTolerance(NanonewtonsPerCentimeterInOneNewtonPerMeter, (double)nanonewtonpercentimeterQuantity.Value, NanonewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerCentimeter, nanonewtonpercentimeterQuantity.Unit); - - var nanonewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.NanonewtonPerMeter); - AssertEx.EqualTolerance(NanonewtonsPerMeterInOneNewtonPerMeter, (double)nanonewtonpermeterQuantity.Value, NanonewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerMeter, nanonewtonpermeterQuantity.Unit); - - var nanonewtonpermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.NanonewtonPerMillimeter); - AssertEx.EqualTolerance(NanonewtonsPerMillimeterInOneNewtonPerMeter, (double)nanonewtonpermillimeterQuantity.Value, NanonewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerMillimeter, nanonewtonpermillimeterQuantity.Unit); - - var newtonpercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.NewtonPerCentimeter); - AssertEx.EqualTolerance(NewtonsPerCentimeterInOneNewtonPerMeter, (double)newtonpercentimeterQuantity.Value, NewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerCentimeter, newtonpercentimeterQuantity.Unit); - - var newtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.NewtonPerMeter); - AssertEx.EqualTolerance(NewtonsPerMeterInOneNewtonPerMeter, (double)newtonpermeterQuantity.Value, NewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerMeter, newtonpermeterQuantity.Unit); - - var newtonpermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.NewtonPerMillimeter); - AssertEx.EqualTolerance(NewtonsPerMillimeterInOneNewtonPerMeter, (double)newtonpermillimeterQuantity.Value, NewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerMillimeter, newtonpermillimeterQuantity.Unit); - - var poundforceperfootQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.PoundForcePerFoot); - AssertEx.EqualTolerance(PoundsForcePerFootInOneNewtonPerMeter, (double)poundforceperfootQuantity.Value, PoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.PoundForcePerFoot, poundforceperfootQuantity.Unit); - - var poundforceperinchQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.PoundForcePerInch); - AssertEx.EqualTolerance(PoundsForcePerInchInOneNewtonPerMeter, (double)poundforceperinchQuantity.Value, PoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.PoundForcePerInch, poundforceperinchQuantity.Unit); - - var poundforceperyardQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.PoundForcePerYard); - AssertEx.EqualTolerance(PoundsForcePerYardInOneNewtonPerMeter, (double)poundforceperyardQuantity.Value, PoundsForcePerYardTolerance); - Assert.Equal(ForcePerLengthUnit.PoundForcePerYard, poundforceperyardQuantity.Unit); - - var tonneforcepercentimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.TonneForcePerCentimeter); - AssertEx.EqualTolerance(TonnesForcePerCentimeterInOneNewtonPerMeter, (double)tonneforcepercentimeterQuantity.Value, TonnesForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerCentimeter, tonneforcepercentimeterQuantity.Unit); - - var tonneforcepermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.TonneForcePerMeter); - AssertEx.EqualTolerance(TonnesForcePerMeterInOneNewtonPerMeter, (double)tonneforcepermeterQuantity.Value, TonnesForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMeter, tonneforcepermeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonneforcepermillimeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.TonneForcePerMillimeter); - AssertEx.EqualTolerance(TonnesForcePerMillimeterInOneNewtonPerMeter, (double)tonneforcepermillimeterQuantity.Value, TonnesForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMillimeter, tonneforcepermillimeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ForcePerLengthUnit unit) + { + var quantity = ForcePerLength.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForcePerLengthUnit unit) { - var quantityInBaseUnit = ForcePerLength.FromNewtonsPerMeter(1).ToBaseUnit(); - Assert.Equal(ForcePerLength.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ForcePerLength.Units.FirstOrDefault(u => u != ForcePerLength.BaseUnit && u != ForcePerLengthUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ForcePerLengthUnit.Undefined) + fromUnit = ForcePerLength.BaseUnit; + + var quantity = ForcePerLength.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs index e99f00c8e2..38541fa42f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -71,6 +72,48 @@ public abstract partial class ForceTestsBase : QuantityTestsBase protected virtual double TonnesForceTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ForceUnit unit) + { + return unit switch + { + ForceUnit.Decanewton => (DecanewtonsInOneNewton, DecanewtonsTolerance), + ForceUnit.Dyn => (DyneInOneNewton, DyneTolerance), + ForceUnit.KilogramForce => (KilogramsForceInOneNewton, KilogramsForceTolerance), + ForceUnit.Kilonewton => (KilonewtonsInOneNewton, KilonewtonsTolerance), + ForceUnit.KiloPond => (KiloPondsInOneNewton, KiloPondsTolerance), + ForceUnit.KilopoundForce => (KilopoundsForceInOneNewton, KilopoundsForceTolerance), + ForceUnit.Meganewton => (MeganewtonsInOneNewton, MeganewtonsTolerance), + ForceUnit.Micronewton => (MicronewtonsInOneNewton, MicronewtonsTolerance), + ForceUnit.Millinewton => (MillinewtonsInOneNewton, MillinewtonsTolerance), + ForceUnit.Newton => (NewtonsInOneNewton, NewtonsTolerance), + ForceUnit.OunceForce => (OunceForceInOneNewton, OunceForceTolerance), + ForceUnit.Poundal => (PoundalsInOneNewton, PoundalsTolerance), + ForceUnit.PoundForce => (PoundsForceInOneNewton, PoundsForceTolerance), + ForceUnit.ShortTonForce => (ShortTonsForceInOneNewton, ShortTonsForceTolerance), + ForceUnit.TonneForce => (TonnesForceInOneNewton, TonnesForceTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ForceUnit.Decanewton }, + new object[] { ForceUnit.Dyn }, + new object[] { ForceUnit.KilogramForce }, + new object[] { ForceUnit.Kilonewton }, + new object[] { ForceUnit.KiloPond }, + new object[] { ForceUnit.KilopoundForce }, + new object[] { ForceUnit.Meganewton }, + new object[] { ForceUnit.Micronewton }, + new object[] { ForceUnit.Millinewton }, + new object[] { ForceUnit.Newton }, + new object[] { ForceUnit.OunceForce }, + new object[] { ForceUnit.Poundal }, + new object[] { ForceUnit.PoundForce }, + new object[] { ForceUnit.ShortTonForce }, + new object[] { ForceUnit.TonneForce }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -276,77 +319,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ForceUnit unit) { - var newton = Force.FromNewtons(1); - - var decanewtonQuantity = newton.ToUnit(ForceUnit.Decanewton); - AssertEx.EqualTolerance(DecanewtonsInOneNewton, (double)decanewtonQuantity.Value, DecanewtonsTolerance); - Assert.Equal(ForceUnit.Decanewton, decanewtonQuantity.Unit); - - var dynQuantity = newton.ToUnit(ForceUnit.Dyn); - AssertEx.EqualTolerance(DyneInOneNewton, (double)dynQuantity.Value, DyneTolerance); - Assert.Equal(ForceUnit.Dyn, dynQuantity.Unit); - - var kilogramforceQuantity = newton.ToUnit(ForceUnit.KilogramForce); - AssertEx.EqualTolerance(KilogramsForceInOneNewton, (double)kilogramforceQuantity.Value, KilogramsForceTolerance); - Assert.Equal(ForceUnit.KilogramForce, kilogramforceQuantity.Unit); - - var kilonewtonQuantity = newton.ToUnit(ForceUnit.Kilonewton); - AssertEx.EqualTolerance(KilonewtonsInOneNewton, (double)kilonewtonQuantity.Value, KilonewtonsTolerance); - Assert.Equal(ForceUnit.Kilonewton, kilonewtonQuantity.Unit); - - var kilopondQuantity = newton.ToUnit(ForceUnit.KiloPond); - AssertEx.EqualTolerance(KiloPondsInOneNewton, (double)kilopondQuantity.Value, KiloPondsTolerance); - Assert.Equal(ForceUnit.KiloPond, kilopondQuantity.Unit); - - var kilopoundforceQuantity = newton.ToUnit(ForceUnit.KilopoundForce); - AssertEx.EqualTolerance(KilopoundsForceInOneNewton, (double)kilopoundforceQuantity.Value, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, kilopoundforceQuantity.Unit); - - var meganewtonQuantity = newton.ToUnit(ForceUnit.Meganewton); - AssertEx.EqualTolerance(MeganewtonsInOneNewton, (double)meganewtonQuantity.Value, MeganewtonsTolerance); - Assert.Equal(ForceUnit.Meganewton, meganewtonQuantity.Unit); + var inBaseUnits = Force.From(1.0, Force.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var micronewtonQuantity = newton.ToUnit(ForceUnit.Micronewton); - AssertEx.EqualTolerance(MicronewtonsInOneNewton, (double)micronewtonQuantity.Value, MicronewtonsTolerance); - Assert.Equal(ForceUnit.Micronewton, micronewtonQuantity.Unit); - - var millinewtonQuantity = newton.ToUnit(ForceUnit.Millinewton); - AssertEx.EqualTolerance(MillinewtonsInOneNewton, (double)millinewtonQuantity.Value, MillinewtonsTolerance); - Assert.Equal(ForceUnit.Millinewton, millinewtonQuantity.Unit); - - var newtonQuantity = newton.ToUnit(ForceUnit.Newton); - AssertEx.EqualTolerance(NewtonsInOneNewton, (double)newtonQuantity.Value, NewtonsTolerance); - Assert.Equal(ForceUnit.Newton, newtonQuantity.Unit); - - var ounceforceQuantity = newton.ToUnit(ForceUnit.OunceForce); - AssertEx.EqualTolerance(OunceForceInOneNewton, (double)ounceforceQuantity.Value, OunceForceTolerance); - Assert.Equal(ForceUnit.OunceForce, ounceforceQuantity.Unit); - - var poundalQuantity = newton.ToUnit(ForceUnit.Poundal); - AssertEx.EqualTolerance(PoundalsInOneNewton, (double)poundalQuantity.Value, PoundalsTolerance); - Assert.Equal(ForceUnit.Poundal, poundalQuantity.Unit); - - var poundforceQuantity = newton.ToUnit(ForceUnit.PoundForce); - AssertEx.EqualTolerance(PoundsForceInOneNewton, (double)poundforceQuantity.Value, PoundsForceTolerance); - Assert.Equal(ForceUnit.PoundForce, poundforceQuantity.Unit); - - var shorttonforceQuantity = newton.ToUnit(ForceUnit.ShortTonForce); - AssertEx.EqualTolerance(ShortTonsForceInOneNewton, (double)shorttonforceQuantity.Value, ShortTonsForceTolerance); - Assert.Equal(ForceUnit.ShortTonForce, shorttonforceQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonneforceQuantity = newton.ToUnit(ForceUnit.TonneForce); - AssertEx.EqualTolerance(TonnesForceInOneNewton, (double)tonneforceQuantity.Value, TonnesForceTolerance); - Assert.Equal(ForceUnit.TonneForce, tonneforceQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ForceUnit unit) + { + var quantity = Force.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForceUnit unit) { - var quantityInBaseUnit = Force.FromNewtons(1).ToBaseUnit(); - Assert.Equal(Force.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Force.Units.FirstOrDefault(u => u != Force.BaseUnit && u != ForceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ForceUnit.Undefined) + fromUnit = Force.BaseUnit; + + var quantity = Force.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs index 80d4ed8863..b98ac9dc61 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -63,6 +64,40 @@ public abstract partial class FrequencyTestsBase : QuantityTestsBase protected virtual double TerahertzTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(FrequencyUnit unit) + { + return unit switch + { + FrequencyUnit.BeatPerMinute => (BeatsPerMinuteInOneHertz, BeatsPerMinuteTolerance), + FrequencyUnit.BUnit => (BUnitsInOneHertz, BUnitsTolerance), + FrequencyUnit.CyclePerHour => (CyclesPerHourInOneHertz, CyclesPerHourTolerance), + FrequencyUnit.CyclePerMinute => (CyclesPerMinuteInOneHertz, CyclesPerMinuteTolerance), + FrequencyUnit.Gigahertz => (GigahertzInOneHertz, GigahertzTolerance), + FrequencyUnit.Hertz => (HertzInOneHertz, HertzTolerance), + FrequencyUnit.Kilohertz => (KilohertzInOneHertz, KilohertzTolerance), + FrequencyUnit.Megahertz => (MegahertzInOneHertz, MegahertzTolerance), + FrequencyUnit.PerSecond => (PerSecondInOneHertz, PerSecondTolerance), + FrequencyUnit.RadianPerSecond => (RadiansPerSecondInOneHertz, RadiansPerSecondTolerance), + FrequencyUnit.Terahertz => (TerahertzInOneHertz, TerahertzTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { FrequencyUnit.BeatPerMinute }, + new object[] { FrequencyUnit.BUnit }, + new object[] { FrequencyUnit.CyclePerHour }, + new object[] { FrequencyUnit.CyclePerMinute }, + new object[] { FrequencyUnit.Gigahertz }, + new object[] { FrequencyUnit.Hertz }, + new object[] { FrequencyUnit.Kilohertz }, + new object[] { FrequencyUnit.Megahertz }, + new object[] { FrequencyUnit.PerSecond }, + new object[] { FrequencyUnit.RadianPerSecond }, + new object[] { FrequencyUnit.Terahertz }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -244,61 +279,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(FrequencyUnit unit) { - var hertz = Frequency.FromHertz(1); - - var beatperminuteQuantity = hertz.ToUnit(FrequencyUnit.BeatPerMinute); - AssertEx.EqualTolerance(BeatsPerMinuteInOneHertz, (double)beatperminuteQuantity.Value, BeatsPerMinuteTolerance); - Assert.Equal(FrequencyUnit.BeatPerMinute, beatperminuteQuantity.Unit); - - var bunitQuantity = hertz.ToUnit(FrequencyUnit.BUnit); - AssertEx.EqualTolerance(BUnitsInOneHertz, (double)bunitQuantity.Value, BUnitsTolerance); - Assert.Equal(FrequencyUnit.BUnit, bunitQuantity.Unit); - - var cycleperhourQuantity = hertz.ToUnit(FrequencyUnit.CyclePerHour); - AssertEx.EqualTolerance(CyclesPerHourInOneHertz, (double)cycleperhourQuantity.Value, CyclesPerHourTolerance); - Assert.Equal(FrequencyUnit.CyclePerHour, cycleperhourQuantity.Unit); - - var cycleperminuteQuantity = hertz.ToUnit(FrequencyUnit.CyclePerMinute); - AssertEx.EqualTolerance(CyclesPerMinuteInOneHertz, (double)cycleperminuteQuantity.Value, CyclesPerMinuteTolerance); - Assert.Equal(FrequencyUnit.CyclePerMinute, cycleperminuteQuantity.Unit); - - var gigahertzQuantity = hertz.ToUnit(FrequencyUnit.Gigahertz); - AssertEx.EqualTolerance(GigahertzInOneHertz, (double)gigahertzQuantity.Value, GigahertzTolerance); - Assert.Equal(FrequencyUnit.Gigahertz, gigahertzQuantity.Unit); + var inBaseUnits = Frequency.From(1.0, Frequency.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var hertzQuantity = hertz.ToUnit(FrequencyUnit.Hertz); - AssertEx.EqualTolerance(HertzInOneHertz, (double)hertzQuantity.Value, HertzTolerance); - Assert.Equal(FrequencyUnit.Hertz, hertzQuantity.Unit); - - var kilohertzQuantity = hertz.ToUnit(FrequencyUnit.Kilohertz); - AssertEx.EqualTolerance(KilohertzInOneHertz, (double)kilohertzQuantity.Value, KilohertzTolerance); - Assert.Equal(FrequencyUnit.Kilohertz, kilohertzQuantity.Unit); - - var megahertzQuantity = hertz.ToUnit(FrequencyUnit.Megahertz); - AssertEx.EqualTolerance(MegahertzInOneHertz, (double)megahertzQuantity.Value, MegahertzTolerance); - Assert.Equal(FrequencyUnit.Megahertz, megahertzQuantity.Unit); - - var persecondQuantity = hertz.ToUnit(FrequencyUnit.PerSecond); - AssertEx.EqualTolerance(PerSecondInOneHertz, (double)persecondQuantity.Value, PerSecondTolerance); - Assert.Equal(FrequencyUnit.PerSecond, persecondQuantity.Unit); - - var radianpersecondQuantity = hertz.ToUnit(FrequencyUnit.RadianPerSecond); - AssertEx.EqualTolerance(RadiansPerSecondInOneHertz, (double)radianpersecondQuantity.Value, RadiansPerSecondTolerance); - Assert.Equal(FrequencyUnit.RadianPerSecond, radianpersecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var terahertzQuantity = hertz.ToUnit(FrequencyUnit.Terahertz); - AssertEx.EqualTolerance(TerahertzInOneHertz, (double)terahertzQuantity.Value, TerahertzTolerance); - Assert.Equal(FrequencyUnit.Terahertz, terahertzQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(FrequencyUnit unit) + { + var quantity = Frequency.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FrequencyUnit unit) { - var quantityInBaseUnit = Frequency.FromHertz(1).ToBaseUnit(); - Assert.Equal(Frequency.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Frequency.Units.FirstOrDefault(u => u != Frequency.BaseUnit && u != FrequencyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == FrequencyUnit.Undefined) + fromUnit = Frequency.BaseUnit; + + var quantity = Frequency.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs index 1c989ea4b2..3cb1885b6f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class FuelEfficiencyTestsBase : QuantityTestsBase protected virtual double MilesPerUsGallonTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(FuelEfficiencyUnit unit) + { + return unit switch + { + FuelEfficiencyUnit.KilometerPerLiter => (KilometersPerLitersInOneLiterPer100Kilometers, KilometersPerLitersTolerance), + FuelEfficiencyUnit.LiterPer100Kilometers => (LitersPer100KilometersInOneLiterPer100Kilometers, LitersPer100KilometersTolerance), + FuelEfficiencyUnit.MilePerUkGallon => (MilesPerUkGallonInOneLiterPer100Kilometers, MilesPerUkGallonTolerance), + FuelEfficiencyUnit.MilePerUsGallon => (MilesPerUsGallonInOneLiterPer100Kilometers, MilesPerUsGallonTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { FuelEfficiencyUnit.KilometerPerLiter }, + new object[] { FuelEfficiencyUnit.LiterPer100Kilometers }, + new object[] { FuelEfficiencyUnit.MilePerUkGallon }, + new object[] { FuelEfficiencyUnit.MilePerUsGallon }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(FuelEfficiencyUnit unit) { - var literper100kilometers = FuelEfficiency.FromLitersPer100Kilometers(1); + var inBaseUnits = FuelEfficiency.From(1.0, FuelEfficiency.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilometerperliterQuantity = literper100kilometers.ToUnit(FuelEfficiencyUnit.KilometerPerLiter); - AssertEx.EqualTolerance(KilometersPerLitersInOneLiterPer100Kilometers, (double)kilometerperliterQuantity.Value, KilometersPerLitersTolerance); - Assert.Equal(FuelEfficiencyUnit.KilometerPerLiter, kilometerperliterQuantity.Unit); - - var literper100kilometersQuantity = literper100kilometers.ToUnit(FuelEfficiencyUnit.LiterPer100Kilometers); - AssertEx.EqualTolerance(LitersPer100KilometersInOneLiterPer100Kilometers, (double)literper100kilometersQuantity.Value, LitersPer100KilometersTolerance); - Assert.Equal(FuelEfficiencyUnit.LiterPer100Kilometers, literper100kilometersQuantity.Unit); - - var mileperukgallonQuantity = literper100kilometers.ToUnit(FuelEfficiencyUnit.MilePerUkGallon); - AssertEx.EqualTolerance(MilesPerUkGallonInOneLiterPer100Kilometers, (double)mileperukgallonQuantity.Value, MilesPerUkGallonTolerance); - Assert.Equal(FuelEfficiencyUnit.MilePerUkGallon, mileperukgallonQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var mileperusgallonQuantity = literper100kilometers.ToUnit(FuelEfficiencyUnit.MilePerUsGallon); - AssertEx.EqualTolerance(MilesPerUsGallonInOneLiterPer100Kilometers, (double)mileperusgallonQuantity.Value, MilesPerUsGallonTolerance); - Assert.Equal(FuelEfficiencyUnit.MilePerUsGallon, mileperusgallonQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(FuelEfficiencyUnit unit) + { + var quantity = FuelEfficiency.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FuelEfficiencyUnit unit) { - var quantityInBaseUnit = FuelEfficiency.FromLitersPer100Kilometers(1).ToBaseUnit(); - Assert.Equal(FuelEfficiency.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = FuelEfficiency.Units.FirstOrDefault(u => u != FuelEfficiency.BaseUnit && u != FuelEfficiencyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == FuelEfficiencyUnit.Undefined) + fromUnit = FuelEfficiency.BaseUnit; + + var quantity = FuelEfficiency.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs index ef5b021573..327cc30781 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -77,6 +78,54 @@ public abstract partial class HeatFluxTestsBase : QuantityTestsBase protected virtual double WattsPerSquareMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(HeatFluxUnit unit) + { + return unit switch + { + HeatFluxUnit.BtuPerHourSquareFoot => (BtusPerHourSquareFootInOneWattPerSquareMeter, BtusPerHourSquareFootTolerance), + HeatFluxUnit.BtuPerMinuteSquareFoot => (BtusPerMinuteSquareFootInOneWattPerSquareMeter, BtusPerMinuteSquareFootTolerance), + HeatFluxUnit.BtuPerSecondSquareFoot => (BtusPerSecondSquareFootInOneWattPerSquareMeter, BtusPerSecondSquareFootTolerance), + HeatFluxUnit.BtuPerSecondSquareInch => (BtusPerSecondSquareInchInOneWattPerSquareMeter, BtusPerSecondSquareInchTolerance), + HeatFluxUnit.CaloriePerSecondSquareCentimeter => (CaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, CaloriesPerSecondSquareCentimeterTolerance), + HeatFluxUnit.CentiwattPerSquareMeter => (CentiwattsPerSquareMeterInOneWattPerSquareMeter, CentiwattsPerSquareMeterTolerance), + HeatFluxUnit.DeciwattPerSquareMeter => (DeciwattsPerSquareMeterInOneWattPerSquareMeter, DeciwattsPerSquareMeterTolerance), + HeatFluxUnit.KilocaloriePerHourSquareMeter => (KilocaloriesPerHourSquareMeterInOneWattPerSquareMeter, KilocaloriesPerHourSquareMeterTolerance), + HeatFluxUnit.KilocaloriePerSecondSquareCentimeter => (KilocaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, KilocaloriesPerSecondSquareCentimeterTolerance), + HeatFluxUnit.KilowattPerSquareMeter => (KilowattsPerSquareMeterInOneWattPerSquareMeter, KilowattsPerSquareMeterTolerance), + HeatFluxUnit.MicrowattPerSquareMeter => (MicrowattsPerSquareMeterInOneWattPerSquareMeter, MicrowattsPerSquareMeterTolerance), + HeatFluxUnit.MilliwattPerSquareMeter => (MilliwattsPerSquareMeterInOneWattPerSquareMeter, MilliwattsPerSquareMeterTolerance), + HeatFluxUnit.NanowattPerSquareMeter => (NanowattsPerSquareMeterInOneWattPerSquareMeter, NanowattsPerSquareMeterTolerance), + HeatFluxUnit.PoundForcePerFootSecond => (PoundsForcePerFootSecondInOneWattPerSquareMeter, PoundsForcePerFootSecondTolerance), + HeatFluxUnit.PoundPerSecondCubed => (PoundsPerSecondCubedInOneWattPerSquareMeter, PoundsPerSecondCubedTolerance), + HeatFluxUnit.WattPerSquareFoot => (WattsPerSquareFootInOneWattPerSquareMeter, WattsPerSquareFootTolerance), + HeatFluxUnit.WattPerSquareInch => (WattsPerSquareInchInOneWattPerSquareMeter, WattsPerSquareInchTolerance), + HeatFluxUnit.WattPerSquareMeter => (WattsPerSquareMeterInOneWattPerSquareMeter, WattsPerSquareMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { HeatFluxUnit.BtuPerHourSquareFoot }, + new object[] { HeatFluxUnit.BtuPerMinuteSquareFoot }, + new object[] { HeatFluxUnit.BtuPerSecondSquareFoot }, + new object[] { HeatFluxUnit.BtuPerSecondSquareInch }, + new object[] { HeatFluxUnit.CaloriePerSecondSquareCentimeter }, + new object[] { HeatFluxUnit.CentiwattPerSquareMeter }, + new object[] { HeatFluxUnit.DeciwattPerSquareMeter }, + new object[] { HeatFluxUnit.KilocaloriePerHourSquareMeter }, + new object[] { HeatFluxUnit.KilocaloriePerSecondSquareCentimeter }, + new object[] { HeatFluxUnit.KilowattPerSquareMeter }, + new object[] { HeatFluxUnit.MicrowattPerSquareMeter }, + new object[] { HeatFluxUnit.MilliwattPerSquareMeter }, + new object[] { HeatFluxUnit.NanowattPerSquareMeter }, + new object[] { HeatFluxUnit.PoundForcePerFootSecond }, + new object[] { HeatFluxUnit.PoundPerSecondCubed }, + new object[] { HeatFluxUnit.WattPerSquareFoot }, + new object[] { HeatFluxUnit.WattPerSquareInch }, + new object[] { HeatFluxUnit.WattPerSquareMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -300,89 +349,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(HeatFluxUnit unit) { - var wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - - var btuperhoursquarefootQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.BtuPerHourSquareFoot); - AssertEx.EqualTolerance(BtusPerHourSquareFootInOneWattPerSquareMeter, (double)btuperhoursquarefootQuantity.Value, BtusPerHourSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerHourSquareFoot, btuperhoursquarefootQuantity.Unit); - - var btuperminutesquarefootQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.BtuPerMinuteSquareFoot); - AssertEx.EqualTolerance(BtusPerMinuteSquareFootInOneWattPerSquareMeter, (double)btuperminutesquarefootQuantity.Value, BtusPerMinuteSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerMinuteSquareFoot, btuperminutesquarefootQuantity.Unit); - - var btupersecondsquarefootQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.BtuPerSecondSquareFoot); - AssertEx.EqualTolerance(BtusPerSecondSquareFootInOneWattPerSquareMeter, (double)btupersecondsquarefootQuantity.Value, BtusPerSecondSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerSecondSquareFoot, btupersecondsquarefootQuantity.Unit); - - var btupersecondsquareinchQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.BtuPerSecondSquareInch); - AssertEx.EqualTolerance(BtusPerSecondSquareInchInOneWattPerSquareMeter, (double)btupersecondsquareinchQuantity.Value, BtusPerSecondSquareInchTolerance); - Assert.Equal(HeatFluxUnit.BtuPerSecondSquareInch, btupersecondsquareinchQuantity.Unit); - - var caloriepersecondsquarecentimeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.CaloriePerSecondSquareCentimeter); - AssertEx.EqualTolerance(CaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, (double)caloriepersecondsquarecentimeterQuantity.Value, CaloriesPerSecondSquareCentimeterTolerance); - Assert.Equal(HeatFluxUnit.CaloriePerSecondSquareCentimeter, caloriepersecondsquarecentimeterQuantity.Unit); - - var centiwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.CentiwattPerSquareMeter); - AssertEx.EqualTolerance(CentiwattsPerSquareMeterInOneWattPerSquareMeter, (double)centiwattpersquaremeterQuantity.Value, CentiwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.CentiwattPerSquareMeter, centiwattpersquaremeterQuantity.Unit); - - var deciwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.DeciwattPerSquareMeter); - AssertEx.EqualTolerance(DeciwattsPerSquareMeterInOneWattPerSquareMeter, (double)deciwattpersquaremeterQuantity.Value, DeciwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.DeciwattPerSquareMeter, deciwattpersquaremeterQuantity.Unit); - - var kilocalorieperhoursquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.KilocaloriePerHourSquareMeter); - AssertEx.EqualTolerance(KilocaloriesPerHourSquareMeterInOneWattPerSquareMeter, (double)kilocalorieperhoursquaremeterQuantity.Value, KilocaloriesPerHourSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.KilocaloriePerHourSquareMeter, kilocalorieperhoursquaremeterQuantity.Unit); - - var kilocaloriepersecondsquarecentimeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); - AssertEx.EqualTolerance(KilocaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, (double)kilocaloriepersecondsquarecentimeterQuantity.Value, KilocaloriesPerSecondSquareCentimeterTolerance); - Assert.Equal(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, kilocaloriepersecondsquarecentimeterQuantity.Unit); + var inBaseUnits = HeatFlux.From(1.0, HeatFlux.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilowattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.KilowattPerSquareMeter); - AssertEx.EqualTolerance(KilowattsPerSquareMeterInOneWattPerSquareMeter, (double)kilowattpersquaremeterQuantity.Value, KilowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.KilowattPerSquareMeter, kilowattpersquaremeterQuantity.Unit); - - var microwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.MicrowattPerSquareMeter); - AssertEx.EqualTolerance(MicrowattsPerSquareMeterInOneWattPerSquareMeter, (double)microwattpersquaremeterQuantity.Value, MicrowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.MicrowattPerSquareMeter, microwattpersquaremeterQuantity.Unit); - - var milliwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.MilliwattPerSquareMeter); - AssertEx.EqualTolerance(MilliwattsPerSquareMeterInOneWattPerSquareMeter, (double)milliwattpersquaremeterQuantity.Value, MilliwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.MilliwattPerSquareMeter, milliwattpersquaremeterQuantity.Unit); - - var nanowattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.NanowattPerSquareMeter); - AssertEx.EqualTolerance(NanowattsPerSquareMeterInOneWattPerSquareMeter, (double)nanowattpersquaremeterQuantity.Value, NanowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.NanowattPerSquareMeter, nanowattpersquaremeterQuantity.Unit); - - var poundforceperfootsecondQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.PoundForcePerFootSecond); - AssertEx.EqualTolerance(PoundsForcePerFootSecondInOneWattPerSquareMeter, (double)poundforceperfootsecondQuantity.Value, PoundsForcePerFootSecondTolerance); - Assert.Equal(HeatFluxUnit.PoundForcePerFootSecond, poundforceperfootsecondQuantity.Unit); - - var poundpersecondcubedQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.PoundPerSecondCubed); - AssertEx.EqualTolerance(PoundsPerSecondCubedInOneWattPerSquareMeter, (double)poundpersecondcubedQuantity.Value, PoundsPerSecondCubedTolerance); - Assert.Equal(HeatFluxUnit.PoundPerSecondCubed, poundpersecondcubedQuantity.Unit); - - var wattpersquarefootQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.WattPerSquareFoot); - AssertEx.EqualTolerance(WattsPerSquareFootInOneWattPerSquareMeter, (double)wattpersquarefootQuantity.Value, WattsPerSquareFootTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareFoot, wattpersquarefootQuantity.Unit); - - var wattpersquareinchQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.WattPerSquareInch); - AssertEx.EqualTolerance(WattsPerSquareInchInOneWattPerSquareMeter, (double)wattpersquareinchQuantity.Value, WattsPerSquareInchTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareInch, wattpersquareinchQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var wattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.WattPerSquareMeter); - AssertEx.EqualTolerance(WattsPerSquareMeterInOneWattPerSquareMeter, (double)wattpersquaremeterQuantity.Value, WattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareMeter, wattpersquaremeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(HeatFluxUnit unit) + { + var quantity = HeatFlux.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(HeatFluxUnit unit) { - var quantityInBaseUnit = HeatFlux.FromWattsPerSquareMeter(1).ToBaseUnit(); - Assert.Equal(HeatFlux.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = HeatFlux.Units.FirstOrDefault(u => u != HeatFlux.BaseUnit && u != HeatFluxUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == HeatFluxUnit.Undefined) + fromUnit = HeatFlux.BaseUnit; + + var quantity = HeatFlux.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs index b0ed942d4c..5688e459b1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class HeatTransferCoefficientTestsBase : QuantityTestsBa protected virtual double WattsPerSquareMeterKelvinTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(HeatTransferCoefficientUnit unit) + { + return unit switch + { + HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit => (BtusPerSquareFootDegreeFahrenheitInOneWattPerSquareMeterKelvin, BtusPerSquareFootDegreeFahrenheitTolerance), + HeatTransferCoefficientUnit.WattPerSquareMeterCelsius => (WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin, WattsPerSquareMeterCelsiusTolerance), + HeatTransferCoefficientUnit.WattPerSquareMeterKelvin => (WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit }, + new object[] { HeatTransferCoefficientUnit.WattPerSquareMeterCelsius }, + new object[] { HeatTransferCoefficientUnit.WattPerSquareMeterKelvin }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(HeatTransferCoefficientUnit unit) { - var wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); + var inBaseUnits = HeatTransferCoefficient.From(1.0, HeatTransferCoefficient.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var btupersquarefootdegreefahrenheitQuantity = wattpersquaremeterkelvin.ToUnit(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit); - AssertEx.EqualTolerance(BtusPerSquareFootDegreeFahrenheitInOneWattPerSquareMeterKelvin, (double)btupersquarefootdegreefahrenheitQuantity.Value, BtusPerSquareFootDegreeFahrenheitTolerance); - Assert.Equal(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, btupersquarefootdegreefahrenheitQuantity.Unit); - - var wattpersquaremetercelsiusQuantity = wattpersquaremeterkelvin.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); - AssertEx.EqualTolerance(WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin, (double)wattpersquaremetercelsiusQuantity.Value, WattsPerSquareMeterCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, wattpersquaremetercelsiusQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var wattpersquaremeterkelvinQuantity = wattpersquaremeterkelvin.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - AssertEx.EqualTolerance(WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin, (double)wattpersquaremeterkelvinQuantity.Value, WattsPerSquareMeterKelvinTolerance); - Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, wattpersquaremeterkelvinQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(HeatTransferCoefficientUnit unit) + { + var quantity = HeatTransferCoefficient.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(HeatTransferCoefficientUnit unit) { - var quantityInBaseUnit = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1).ToBaseUnit(); - Assert.Equal(HeatTransferCoefficient.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = HeatTransferCoefficient.Units.FirstOrDefault(u => u != HeatTransferCoefficient.BaseUnit && u != HeatTransferCoefficientUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == HeatTransferCoefficientUnit.Undefined) + fromUnit = HeatTransferCoefficient.BaseUnit; + + var quantity = HeatTransferCoefficient.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs index 5537fc12bd..5dad5be5cd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class IlluminanceTestsBase : QuantityTestsBase protected virtual double MilliluxTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(IlluminanceUnit unit) + { + return unit switch + { + IlluminanceUnit.Kilolux => (KiloluxInOneLux, KiloluxTolerance), + IlluminanceUnit.Lux => (LuxInOneLux, LuxTolerance), + IlluminanceUnit.Megalux => (MegaluxInOneLux, MegaluxTolerance), + IlluminanceUnit.Millilux => (MilliluxInOneLux, MilliluxTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { IlluminanceUnit.Kilolux }, + new object[] { IlluminanceUnit.Lux }, + new object[] { IlluminanceUnit.Megalux }, + new object[] { IlluminanceUnit.Millilux }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(IlluminanceUnit unit) { - var lux = Illuminance.FromLux(1); + var inBaseUnits = Illuminance.From(1.0, Illuminance.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kiloluxQuantity = lux.ToUnit(IlluminanceUnit.Kilolux); - AssertEx.EqualTolerance(KiloluxInOneLux, (double)kiloluxQuantity.Value, KiloluxTolerance); - Assert.Equal(IlluminanceUnit.Kilolux, kiloluxQuantity.Unit); - - var luxQuantity = lux.ToUnit(IlluminanceUnit.Lux); - AssertEx.EqualTolerance(LuxInOneLux, (double)luxQuantity.Value, LuxTolerance); - Assert.Equal(IlluminanceUnit.Lux, luxQuantity.Unit); - - var megaluxQuantity = lux.ToUnit(IlluminanceUnit.Megalux); - AssertEx.EqualTolerance(MegaluxInOneLux, (double)megaluxQuantity.Value, MegaluxTolerance); - Assert.Equal(IlluminanceUnit.Megalux, megaluxQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var milliluxQuantity = lux.ToUnit(IlluminanceUnit.Millilux); - AssertEx.EqualTolerance(MilliluxInOneLux, (double)milliluxQuantity.Value, MilliluxTolerance); - Assert.Equal(IlluminanceUnit.Millilux, milliluxQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(IlluminanceUnit unit) + { + var quantity = Illuminance.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IlluminanceUnit unit) { - var quantityInBaseUnit = Illuminance.FromLux(1).ToBaseUnit(); - Assert.Equal(Illuminance.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Illuminance.Units.FirstOrDefault(u => u != Illuminance.BaseUnit && u != IlluminanceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == IlluminanceUnit.Undefined) + fromUnit = Illuminance.BaseUnit; + + var quantity = Illuminance.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs index b362e00824..d42510c69f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -93,6 +94,70 @@ public abstract partial class InformationTestsBase : QuantityTestsBase protected virtual double TerabytesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(InformationUnit unit) + { + return unit switch + { + InformationUnit.Bit => (BitsInOneBit, BitsTolerance), + InformationUnit.Byte => (BytesInOneBit, BytesTolerance), + InformationUnit.Exabit => (ExabitsInOneBit, ExabitsTolerance), + InformationUnit.Exabyte => (ExabytesInOneBit, ExabytesTolerance), + InformationUnit.Exbibit => (ExbibitsInOneBit, ExbibitsTolerance), + InformationUnit.Exbibyte => (ExbibytesInOneBit, ExbibytesTolerance), + InformationUnit.Gibibit => (GibibitsInOneBit, GibibitsTolerance), + InformationUnit.Gibibyte => (GibibytesInOneBit, GibibytesTolerance), + InformationUnit.Gigabit => (GigabitsInOneBit, GigabitsTolerance), + InformationUnit.Gigabyte => (GigabytesInOneBit, GigabytesTolerance), + InformationUnit.Kibibit => (KibibitsInOneBit, KibibitsTolerance), + InformationUnit.Kibibyte => (KibibytesInOneBit, KibibytesTolerance), + InformationUnit.Kilobit => (KilobitsInOneBit, KilobitsTolerance), + InformationUnit.Kilobyte => (KilobytesInOneBit, KilobytesTolerance), + InformationUnit.Mebibit => (MebibitsInOneBit, MebibitsTolerance), + InformationUnit.Mebibyte => (MebibytesInOneBit, MebibytesTolerance), + InformationUnit.Megabit => (MegabitsInOneBit, MegabitsTolerance), + InformationUnit.Megabyte => (MegabytesInOneBit, MegabytesTolerance), + InformationUnit.Pebibit => (PebibitsInOneBit, PebibitsTolerance), + InformationUnit.Pebibyte => (PebibytesInOneBit, PebibytesTolerance), + InformationUnit.Petabit => (PetabitsInOneBit, PetabitsTolerance), + InformationUnit.Petabyte => (PetabytesInOneBit, PetabytesTolerance), + InformationUnit.Tebibit => (TebibitsInOneBit, TebibitsTolerance), + InformationUnit.Tebibyte => (TebibytesInOneBit, TebibytesTolerance), + InformationUnit.Terabit => (TerabitsInOneBit, TerabitsTolerance), + InformationUnit.Terabyte => (TerabytesInOneBit, TerabytesTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { InformationUnit.Bit }, + new object[] { InformationUnit.Byte }, + new object[] { InformationUnit.Exabit }, + new object[] { InformationUnit.Exabyte }, + new object[] { InformationUnit.Exbibit }, + new object[] { InformationUnit.Exbibyte }, + new object[] { InformationUnit.Gibibit }, + new object[] { InformationUnit.Gibibyte }, + new object[] { InformationUnit.Gigabit }, + new object[] { InformationUnit.Gigabyte }, + new object[] { InformationUnit.Kibibit }, + new object[] { InformationUnit.Kibibyte }, + new object[] { InformationUnit.Kilobit }, + new object[] { InformationUnit.Kilobyte }, + new object[] { InformationUnit.Mebibit }, + new object[] { InformationUnit.Mebibyte }, + new object[] { InformationUnit.Megabit }, + new object[] { InformationUnit.Megabyte }, + new object[] { InformationUnit.Pebibit }, + new object[] { InformationUnit.Pebibyte }, + new object[] { InformationUnit.Petabit }, + new object[] { InformationUnit.Petabyte }, + new object[] { InformationUnit.Tebibit }, + new object[] { InformationUnit.Tebibyte }, + new object[] { InformationUnit.Terabit }, + new object[] { InformationUnit.Terabyte }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -339,121 +404,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(InformationUnit unit) { - var bit = Information.FromBits(1); - - var bitQuantity = bit.ToUnit(InformationUnit.Bit); - AssertEx.EqualTolerance(BitsInOneBit, (double)bitQuantity.Value, BitsTolerance); - Assert.Equal(InformationUnit.Bit, bitQuantity.Unit); - - var byteQuantity = bit.ToUnit(InformationUnit.Byte); - AssertEx.EqualTolerance(BytesInOneBit, (double)byteQuantity.Value, BytesTolerance); - Assert.Equal(InformationUnit.Byte, byteQuantity.Unit); - - var exabitQuantity = bit.ToUnit(InformationUnit.Exabit); - AssertEx.EqualTolerance(ExabitsInOneBit, (double)exabitQuantity.Value, ExabitsTolerance); - Assert.Equal(InformationUnit.Exabit, exabitQuantity.Unit); - - var exabyteQuantity = bit.ToUnit(InformationUnit.Exabyte); - AssertEx.EqualTolerance(ExabytesInOneBit, (double)exabyteQuantity.Value, ExabytesTolerance); - Assert.Equal(InformationUnit.Exabyte, exabyteQuantity.Unit); - - var exbibitQuantity = bit.ToUnit(InformationUnit.Exbibit); - AssertEx.EqualTolerance(ExbibitsInOneBit, (double)exbibitQuantity.Value, ExbibitsTolerance); - Assert.Equal(InformationUnit.Exbibit, exbibitQuantity.Unit); - - var exbibyteQuantity = bit.ToUnit(InformationUnit.Exbibyte); - AssertEx.EqualTolerance(ExbibytesInOneBit, (double)exbibyteQuantity.Value, ExbibytesTolerance); - Assert.Equal(InformationUnit.Exbibyte, exbibyteQuantity.Unit); - - var gibibitQuantity = bit.ToUnit(InformationUnit.Gibibit); - AssertEx.EqualTolerance(GibibitsInOneBit, (double)gibibitQuantity.Value, GibibitsTolerance); - Assert.Equal(InformationUnit.Gibibit, gibibitQuantity.Unit); - - var gibibyteQuantity = bit.ToUnit(InformationUnit.Gibibyte); - AssertEx.EqualTolerance(GibibytesInOneBit, (double)gibibyteQuantity.Value, GibibytesTolerance); - Assert.Equal(InformationUnit.Gibibyte, gibibyteQuantity.Unit); - - var gigabitQuantity = bit.ToUnit(InformationUnit.Gigabit); - AssertEx.EqualTolerance(GigabitsInOneBit, (double)gigabitQuantity.Value, GigabitsTolerance); - Assert.Equal(InformationUnit.Gigabit, gigabitQuantity.Unit); - - var gigabyteQuantity = bit.ToUnit(InformationUnit.Gigabyte); - AssertEx.EqualTolerance(GigabytesInOneBit, (double)gigabyteQuantity.Value, GigabytesTolerance); - Assert.Equal(InformationUnit.Gigabyte, gigabyteQuantity.Unit); - - var kibibitQuantity = bit.ToUnit(InformationUnit.Kibibit); - AssertEx.EqualTolerance(KibibitsInOneBit, (double)kibibitQuantity.Value, KibibitsTolerance); - Assert.Equal(InformationUnit.Kibibit, kibibitQuantity.Unit); - - var kibibyteQuantity = bit.ToUnit(InformationUnit.Kibibyte); - AssertEx.EqualTolerance(KibibytesInOneBit, (double)kibibyteQuantity.Value, KibibytesTolerance); - Assert.Equal(InformationUnit.Kibibyte, kibibyteQuantity.Unit); - - var kilobitQuantity = bit.ToUnit(InformationUnit.Kilobit); - AssertEx.EqualTolerance(KilobitsInOneBit, (double)kilobitQuantity.Value, KilobitsTolerance); - Assert.Equal(InformationUnit.Kilobit, kilobitQuantity.Unit); + var inBaseUnits = Information.From(1.0, Information.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilobyteQuantity = bit.ToUnit(InformationUnit.Kilobyte); - AssertEx.EqualTolerance(KilobytesInOneBit, (double)kilobyteQuantity.Value, KilobytesTolerance); - Assert.Equal(InformationUnit.Kilobyte, kilobyteQuantity.Unit); - - var mebibitQuantity = bit.ToUnit(InformationUnit.Mebibit); - AssertEx.EqualTolerance(MebibitsInOneBit, (double)mebibitQuantity.Value, MebibitsTolerance); - Assert.Equal(InformationUnit.Mebibit, mebibitQuantity.Unit); - - var mebibyteQuantity = bit.ToUnit(InformationUnit.Mebibyte); - AssertEx.EqualTolerance(MebibytesInOneBit, (double)mebibyteQuantity.Value, MebibytesTolerance); - Assert.Equal(InformationUnit.Mebibyte, mebibyteQuantity.Unit); - - var megabitQuantity = bit.ToUnit(InformationUnit.Megabit); - AssertEx.EqualTolerance(MegabitsInOneBit, (double)megabitQuantity.Value, MegabitsTolerance); - Assert.Equal(InformationUnit.Megabit, megabitQuantity.Unit); - - var megabyteQuantity = bit.ToUnit(InformationUnit.Megabyte); - AssertEx.EqualTolerance(MegabytesInOneBit, (double)megabyteQuantity.Value, MegabytesTolerance); - Assert.Equal(InformationUnit.Megabyte, megabyteQuantity.Unit); - - var pebibitQuantity = bit.ToUnit(InformationUnit.Pebibit); - AssertEx.EqualTolerance(PebibitsInOneBit, (double)pebibitQuantity.Value, PebibitsTolerance); - Assert.Equal(InformationUnit.Pebibit, pebibitQuantity.Unit); - - var pebibyteQuantity = bit.ToUnit(InformationUnit.Pebibyte); - AssertEx.EqualTolerance(PebibytesInOneBit, (double)pebibyteQuantity.Value, PebibytesTolerance); - Assert.Equal(InformationUnit.Pebibyte, pebibyteQuantity.Unit); - - var petabitQuantity = bit.ToUnit(InformationUnit.Petabit); - AssertEx.EqualTolerance(PetabitsInOneBit, (double)petabitQuantity.Value, PetabitsTolerance); - Assert.Equal(InformationUnit.Petabit, petabitQuantity.Unit); - - var petabyteQuantity = bit.ToUnit(InformationUnit.Petabyte); - AssertEx.EqualTolerance(PetabytesInOneBit, (double)petabyteQuantity.Value, PetabytesTolerance); - Assert.Equal(InformationUnit.Petabyte, petabyteQuantity.Unit); - - var tebibitQuantity = bit.ToUnit(InformationUnit.Tebibit); - AssertEx.EqualTolerance(TebibitsInOneBit, (double)tebibitQuantity.Value, TebibitsTolerance); - Assert.Equal(InformationUnit.Tebibit, tebibitQuantity.Unit); - - var tebibyteQuantity = bit.ToUnit(InformationUnit.Tebibyte); - AssertEx.EqualTolerance(TebibytesInOneBit, (double)tebibyteQuantity.Value, TebibytesTolerance); - Assert.Equal(InformationUnit.Tebibyte, tebibyteQuantity.Unit); - - var terabitQuantity = bit.ToUnit(InformationUnit.Terabit); - AssertEx.EqualTolerance(TerabitsInOneBit, (double)terabitQuantity.Value, TerabitsTolerance); - Assert.Equal(InformationUnit.Terabit, terabitQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var terabyteQuantity = bit.ToUnit(InformationUnit.Terabyte); - AssertEx.EqualTolerance(TerabytesInOneBit, (double)terabyteQuantity.Value, TerabytesTolerance); - Assert.Equal(InformationUnit.Terabyte, terabyteQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(InformationUnit unit) + { + var quantity = Information.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(InformationUnit unit) { - var quantityInBaseUnit = Information.FromBits(1).ToBaseUnit(); - Assert.Equal(Information.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Information.Units.FirstOrDefault(u => u != Information.BaseUnit && u != InformationUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == InformationUnit.Undefined) + fromUnit = Information.BaseUnit; + + var quantity = Information.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs index 76e0cd7403..6e6f49a82a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -69,6 +70,46 @@ public abstract partial class IrradianceTestsBase : QuantityTestsBase protected virtual double WattsPerSquareMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(IrradianceUnit unit) + { + return unit switch + { + IrradianceUnit.KilowattPerSquareCentimeter => (KilowattsPerSquareCentimeterInOneWattPerSquareMeter, KilowattsPerSquareCentimeterTolerance), + IrradianceUnit.KilowattPerSquareMeter => (KilowattsPerSquareMeterInOneWattPerSquareMeter, KilowattsPerSquareMeterTolerance), + IrradianceUnit.MegawattPerSquareCentimeter => (MegawattsPerSquareCentimeterInOneWattPerSquareMeter, MegawattsPerSquareCentimeterTolerance), + IrradianceUnit.MegawattPerSquareMeter => (MegawattsPerSquareMeterInOneWattPerSquareMeter, MegawattsPerSquareMeterTolerance), + IrradianceUnit.MicrowattPerSquareCentimeter => (MicrowattsPerSquareCentimeterInOneWattPerSquareMeter, MicrowattsPerSquareCentimeterTolerance), + IrradianceUnit.MicrowattPerSquareMeter => (MicrowattsPerSquareMeterInOneWattPerSquareMeter, MicrowattsPerSquareMeterTolerance), + IrradianceUnit.MilliwattPerSquareCentimeter => (MilliwattsPerSquareCentimeterInOneWattPerSquareMeter, MilliwattsPerSquareCentimeterTolerance), + IrradianceUnit.MilliwattPerSquareMeter => (MilliwattsPerSquareMeterInOneWattPerSquareMeter, MilliwattsPerSquareMeterTolerance), + IrradianceUnit.NanowattPerSquareCentimeter => (NanowattsPerSquareCentimeterInOneWattPerSquareMeter, NanowattsPerSquareCentimeterTolerance), + IrradianceUnit.NanowattPerSquareMeter => (NanowattsPerSquareMeterInOneWattPerSquareMeter, NanowattsPerSquareMeterTolerance), + IrradianceUnit.PicowattPerSquareCentimeter => (PicowattsPerSquareCentimeterInOneWattPerSquareMeter, PicowattsPerSquareCentimeterTolerance), + IrradianceUnit.PicowattPerSquareMeter => (PicowattsPerSquareMeterInOneWattPerSquareMeter, PicowattsPerSquareMeterTolerance), + IrradianceUnit.WattPerSquareCentimeter => (WattsPerSquareCentimeterInOneWattPerSquareMeter, WattsPerSquareCentimeterTolerance), + IrradianceUnit.WattPerSquareMeter => (WattsPerSquareMeterInOneWattPerSquareMeter, WattsPerSquareMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { IrradianceUnit.KilowattPerSquareCentimeter }, + new object[] { IrradianceUnit.KilowattPerSquareMeter }, + new object[] { IrradianceUnit.MegawattPerSquareCentimeter }, + new object[] { IrradianceUnit.MegawattPerSquareMeter }, + new object[] { IrradianceUnit.MicrowattPerSquareCentimeter }, + new object[] { IrradianceUnit.MicrowattPerSquareMeter }, + new object[] { IrradianceUnit.MilliwattPerSquareCentimeter }, + new object[] { IrradianceUnit.MilliwattPerSquareMeter }, + new object[] { IrradianceUnit.NanowattPerSquareCentimeter }, + new object[] { IrradianceUnit.NanowattPerSquareMeter }, + new object[] { IrradianceUnit.PicowattPerSquareCentimeter }, + new object[] { IrradianceUnit.PicowattPerSquareMeter }, + new object[] { IrradianceUnit.WattPerSquareCentimeter }, + new object[] { IrradianceUnit.WattPerSquareMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -268,73 +309,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(IrradianceUnit unit) { - var wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - - var kilowattpersquarecentimeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.KilowattPerSquareCentimeter); - AssertEx.EqualTolerance(KilowattsPerSquareCentimeterInOneWattPerSquareMeter, (double)kilowattpersquarecentimeterQuantity.Value, KilowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.KilowattPerSquareCentimeter, kilowattpersquarecentimeterQuantity.Unit); - - var kilowattpersquaremeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.KilowattPerSquareMeter); - AssertEx.EqualTolerance(KilowattsPerSquareMeterInOneWattPerSquareMeter, (double)kilowattpersquaremeterQuantity.Value, KilowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.KilowattPerSquareMeter, kilowattpersquaremeterQuantity.Unit); - - var megawattpersquarecentimeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.MegawattPerSquareCentimeter); - AssertEx.EqualTolerance(MegawattsPerSquareCentimeterInOneWattPerSquareMeter, (double)megawattpersquarecentimeterQuantity.Value, MegawattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.MegawattPerSquareCentimeter, megawattpersquarecentimeterQuantity.Unit); - - var megawattpersquaremeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.MegawattPerSquareMeter); - AssertEx.EqualTolerance(MegawattsPerSquareMeterInOneWattPerSquareMeter, (double)megawattpersquaremeterQuantity.Value, MegawattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.MegawattPerSquareMeter, megawattpersquaremeterQuantity.Unit); - - var microwattpersquarecentimeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.MicrowattPerSquareCentimeter); - AssertEx.EqualTolerance(MicrowattsPerSquareCentimeterInOneWattPerSquareMeter, (double)microwattpersquarecentimeterQuantity.Value, MicrowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.MicrowattPerSquareCentimeter, microwattpersquarecentimeterQuantity.Unit); - - var microwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.MicrowattPerSquareMeter); - AssertEx.EqualTolerance(MicrowattsPerSquareMeterInOneWattPerSquareMeter, (double)microwattpersquaremeterQuantity.Value, MicrowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.MicrowattPerSquareMeter, microwattpersquaremeterQuantity.Unit); - - var milliwattpersquarecentimeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.MilliwattPerSquareCentimeter); - AssertEx.EqualTolerance(MilliwattsPerSquareCentimeterInOneWattPerSquareMeter, (double)milliwattpersquarecentimeterQuantity.Value, MilliwattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.MilliwattPerSquareCentimeter, milliwattpersquarecentimeterQuantity.Unit); + var inBaseUnits = Irradiance.From(1.0, Irradiance.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var milliwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.MilliwattPerSquareMeter); - AssertEx.EqualTolerance(MilliwattsPerSquareMeterInOneWattPerSquareMeter, (double)milliwattpersquaremeterQuantity.Value, MilliwattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.MilliwattPerSquareMeter, milliwattpersquaremeterQuantity.Unit); - - var nanowattpersquarecentimeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.NanowattPerSquareCentimeter); - AssertEx.EqualTolerance(NanowattsPerSquareCentimeterInOneWattPerSquareMeter, (double)nanowattpersquarecentimeterQuantity.Value, NanowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.NanowattPerSquareCentimeter, nanowattpersquarecentimeterQuantity.Unit); - - var nanowattpersquaremeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.NanowattPerSquareMeter); - AssertEx.EqualTolerance(NanowattsPerSquareMeterInOneWattPerSquareMeter, (double)nanowattpersquaremeterQuantity.Value, NanowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.NanowattPerSquareMeter, nanowattpersquaremeterQuantity.Unit); - - var picowattpersquarecentimeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.PicowattPerSquareCentimeter); - AssertEx.EqualTolerance(PicowattsPerSquareCentimeterInOneWattPerSquareMeter, (double)picowattpersquarecentimeterQuantity.Value, PicowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.PicowattPerSquareCentimeter, picowattpersquarecentimeterQuantity.Unit); - - var picowattpersquaremeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.PicowattPerSquareMeter); - AssertEx.EqualTolerance(PicowattsPerSquareMeterInOneWattPerSquareMeter, (double)picowattpersquaremeterQuantity.Value, PicowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.PicowattPerSquareMeter, picowattpersquaremeterQuantity.Unit); - - var wattpersquarecentimeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.WattPerSquareCentimeter); - AssertEx.EqualTolerance(WattsPerSquareCentimeterInOneWattPerSquareMeter, (double)wattpersquarecentimeterQuantity.Value, WattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.WattPerSquareCentimeter, wattpersquarecentimeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var wattpersquaremeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.WattPerSquareMeter); - AssertEx.EqualTolerance(WattsPerSquareMeterInOneWattPerSquareMeter, (double)wattpersquaremeterQuantity.Value, WattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.WattPerSquareMeter, wattpersquaremeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(IrradianceUnit unit) + { + var quantity = Irradiance.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IrradianceUnit unit) { - var quantityInBaseUnit = Irradiance.FromWattsPerSquareMeter(1).ToBaseUnit(); - Assert.Equal(Irradiance.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Irradiance.Units.FirstOrDefault(u => u != Irradiance.BaseUnit && u != IrradianceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == IrradianceUnit.Undefined) + fromUnit = Irradiance.BaseUnit; + + var quantity = Irradiance.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs index afdd0b60c3..1fa8cb53cd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -55,6 +56,32 @@ public abstract partial class IrradiationTestsBase : QuantityTestsBase protected virtual double WattHoursPerSquareMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(IrradiationUnit unit) + { + return unit switch + { + IrradiationUnit.JoulePerSquareCentimeter => (JoulesPerSquareCentimeterInOneJoulePerSquareMeter, JoulesPerSquareCentimeterTolerance), + IrradiationUnit.JoulePerSquareMeter => (JoulesPerSquareMeterInOneJoulePerSquareMeter, JoulesPerSquareMeterTolerance), + IrradiationUnit.JoulePerSquareMillimeter => (JoulesPerSquareMillimeterInOneJoulePerSquareMeter, JoulesPerSquareMillimeterTolerance), + IrradiationUnit.KilojoulePerSquareMeter => (KilojoulesPerSquareMeterInOneJoulePerSquareMeter, KilojoulesPerSquareMeterTolerance), + IrradiationUnit.KilowattHourPerSquareMeter => (KilowattHoursPerSquareMeterInOneJoulePerSquareMeter, KilowattHoursPerSquareMeterTolerance), + IrradiationUnit.MillijoulePerSquareCentimeter => (MillijoulesPerSquareCentimeterInOneJoulePerSquareMeter, MillijoulesPerSquareCentimeterTolerance), + IrradiationUnit.WattHourPerSquareMeter => (WattHoursPerSquareMeterInOneJoulePerSquareMeter, WattHoursPerSquareMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { IrradiationUnit.JoulePerSquareCentimeter }, + new object[] { IrradiationUnit.JoulePerSquareMeter }, + new object[] { IrradiationUnit.JoulePerSquareMillimeter }, + new object[] { IrradiationUnit.KilojoulePerSquareMeter }, + new object[] { IrradiationUnit.KilowattHourPerSquareMeter }, + new object[] { IrradiationUnit.MillijoulePerSquareCentimeter }, + new object[] { IrradiationUnit.WattHourPerSquareMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -212,45 +239,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(IrradiationUnit unit) { - var joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - - var joulepersquarecentimeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.JoulePerSquareCentimeter); - AssertEx.EqualTolerance(JoulesPerSquareCentimeterInOneJoulePerSquareMeter, (double)joulepersquarecentimeterQuantity.Value, JoulesPerSquareCentimeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareCentimeter, joulepersquarecentimeterQuantity.Unit); - - var joulepersquaremeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.JoulePerSquareMeter); - AssertEx.EqualTolerance(JoulesPerSquareMeterInOneJoulePerSquareMeter, (double)joulepersquaremeterQuantity.Value, JoulesPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareMeter, joulepersquaremeterQuantity.Unit); + var inBaseUnits = Irradiation.From(1.0, Irradiation.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var joulepersquaremillimeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.JoulePerSquareMillimeter); - AssertEx.EqualTolerance(JoulesPerSquareMillimeterInOneJoulePerSquareMeter, (double)joulepersquaremillimeterQuantity.Value, JoulesPerSquareMillimeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareMillimeter, joulepersquaremillimeterQuantity.Unit); - - var kilojoulepersquaremeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.KilojoulePerSquareMeter); - AssertEx.EqualTolerance(KilojoulesPerSquareMeterInOneJoulePerSquareMeter, (double)kilojoulepersquaremeterQuantity.Value, KilojoulesPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.KilojoulePerSquareMeter, kilojoulepersquaremeterQuantity.Unit); - - var kilowatthourpersquaremeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.KilowattHourPerSquareMeter); - AssertEx.EqualTolerance(KilowattHoursPerSquareMeterInOneJoulePerSquareMeter, (double)kilowatthourpersquaremeterQuantity.Value, KilowattHoursPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.KilowattHourPerSquareMeter, kilowatthourpersquaremeterQuantity.Unit); - - var millijoulepersquarecentimeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.MillijoulePerSquareCentimeter); - AssertEx.EqualTolerance(MillijoulesPerSquareCentimeterInOneJoulePerSquareMeter, (double)millijoulepersquarecentimeterQuantity.Value, MillijoulesPerSquareCentimeterTolerance); - Assert.Equal(IrradiationUnit.MillijoulePerSquareCentimeter, millijoulepersquarecentimeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var watthourpersquaremeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.WattHourPerSquareMeter); - AssertEx.EqualTolerance(WattHoursPerSquareMeterInOneJoulePerSquareMeter, (double)watthourpersquaremeterQuantity.Value, WattHoursPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.WattHourPerSquareMeter, watthourpersquaremeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(IrradiationUnit unit) + { + var quantity = Irradiation.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IrradiationUnit unit) { - var quantityInBaseUnit = Irradiation.FromJoulesPerSquareMeter(1).ToBaseUnit(); - Assert.Equal(Irradiation.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Irradiation.Units.FirstOrDefault(u => u != Irradiation.BaseUnit && u != IrradiationUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == IrradiationUnit.Undefined) + fromUnit = Irradiation.BaseUnit; + + var quantity = Irradiation.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs index 34e19f82df..75b9a0be85 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -59,6 +60,36 @@ public abstract partial class KinematicViscosityTestsBase : QuantityTestsBase protected virtual double StokesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(KinematicViscosityUnit unit) + { + return unit switch + { + KinematicViscosityUnit.Centistokes => (CentistokesInOneSquareMeterPerSecond, CentistokesTolerance), + KinematicViscosityUnit.Decistokes => (DecistokesInOneSquareMeterPerSecond, DecistokesTolerance), + KinematicViscosityUnit.Kilostokes => (KilostokesInOneSquareMeterPerSecond, KilostokesTolerance), + KinematicViscosityUnit.Microstokes => (MicrostokesInOneSquareMeterPerSecond, MicrostokesTolerance), + KinematicViscosityUnit.Millistokes => (MillistokesInOneSquareMeterPerSecond, MillistokesTolerance), + KinematicViscosityUnit.Nanostokes => (NanostokesInOneSquareMeterPerSecond, NanostokesTolerance), + KinematicViscosityUnit.SquareFootPerSecond => (SquareFeetPerSecondInOneSquareMeterPerSecond, SquareFeetPerSecondTolerance), + KinematicViscosityUnit.SquareMeterPerSecond => (SquareMetersPerSecondInOneSquareMeterPerSecond, SquareMetersPerSecondTolerance), + KinematicViscosityUnit.Stokes => (StokesInOneSquareMeterPerSecond, StokesTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { KinematicViscosityUnit.Centistokes }, + new object[] { KinematicViscosityUnit.Decistokes }, + new object[] { KinematicViscosityUnit.Kilostokes }, + new object[] { KinematicViscosityUnit.Microstokes }, + new object[] { KinematicViscosityUnit.Millistokes }, + new object[] { KinematicViscosityUnit.Nanostokes }, + new object[] { KinematicViscosityUnit.SquareFootPerSecond }, + new object[] { KinematicViscosityUnit.SquareMeterPerSecond }, + new object[] { KinematicViscosityUnit.Stokes }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -228,53 +259,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(KinematicViscosityUnit unit) { - var squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - - var centistokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Centistokes); - AssertEx.EqualTolerance(CentistokesInOneSquareMeterPerSecond, (double)centistokesQuantity.Value, CentistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Centistokes, centistokesQuantity.Unit); - - var decistokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Decistokes); - AssertEx.EqualTolerance(DecistokesInOneSquareMeterPerSecond, (double)decistokesQuantity.Value, DecistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Decistokes, decistokesQuantity.Unit); - - var kilostokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Kilostokes); - AssertEx.EqualTolerance(KilostokesInOneSquareMeterPerSecond, (double)kilostokesQuantity.Value, KilostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Kilostokes, kilostokesQuantity.Unit); - - var microstokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Microstokes); - AssertEx.EqualTolerance(MicrostokesInOneSquareMeterPerSecond, (double)microstokesQuantity.Value, MicrostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Microstokes, microstokesQuantity.Unit); + var inBaseUnits = KinematicViscosity.From(1.0, KinematicViscosity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var millistokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Millistokes); - AssertEx.EqualTolerance(MillistokesInOneSquareMeterPerSecond, (double)millistokesQuantity.Value, MillistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Millistokes, millistokesQuantity.Unit); - - var nanostokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Nanostokes); - AssertEx.EqualTolerance(NanostokesInOneSquareMeterPerSecond, (double)nanostokesQuantity.Value, NanostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Nanostokes, nanostokesQuantity.Unit); - - var squarefootpersecondQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.SquareFootPerSecond); - AssertEx.EqualTolerance(SquareFeetPerSecondInOneSquareMeterPerSecond, (double)squarefootpersecondQuantity.Value, SquareFeetPerSecondTolerance); - Assert.Equal(KinematicViscosityUnit.SquareFootPerSecond, squarefootpersecondQuantity.Unit); - - var squaremeterpersecondQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond); - AssertEx.EqualTolerance(SquareMetersPerSecondInOneSquareMeterPerSecond, (double)squaremeterpersecondQuantity.Value, SquareMetersPerSecondTolerance); - Assert.Equal(KinematicViscosityUnit.SquareMeterPerSecond, squaremeterpersecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var stokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Stokes); - AssertEx.EqualTolerance(StokesInOneSquareMeterPerSecond, (double)stokesQuantity.Value, StokesTolerance); - Assert.Equal(KinematicViscosityUnit.Stokes, stokesQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(KinematicViscosityUnit unit) + { + var quantity = KinematicViscosity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(KinematicViscosityUnit unit) { - var quantityInBaseUnit = KinematicViscosity.FromSquareMetersPerSecond(1).ToBaseUnit(); - Assert.Equal(KinematicViscosity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = KinematicViscosity.Units.FirstOrDefault(u => u != KinematicViscosity.BaseUnit && u != KinematicViscosityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == KinematicViscosityUnit.Undefined) + fromUnit = KinematicViscosity.BaseUnit; + + var quantity = KinematicViscosity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs index 0012197a39..abd317b6b1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class LapseRateTestsBase : QuantityTestsBase protected virtual double DegreesCelciusPerKilometerTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LapseRateUnit unit) + { + return unit switch + { + LapseRateUnit.DegreeCelsiusPerKilometer => (DegreesCelciusPerKilometerInOneDegreeCelsiusPerKilometer, DegreesCelciusPerKilometerTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { LapseRateUnit.DegreeCelsiusPerKilometer }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(LapseRateUnit unit) { - var degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); + var inBaseUnits = LapseRate.From(1.0, LapseRate.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var degreecelsiusperkilometerQuantity = degreecelsiusperkilometer.ToUnit(LapseRateUnit.DegreeCelsiusPerKilometer); - AssertEx.EqualTolerance(DegreesCelciusPerKilometerInOneDegreeCelsiusPerKilometer, (double)degreecelsiusperkilometerQuantity.Value, DegreesCelciusPerKilometerTolerance); - Assert.Equal(LapseRateUnit.DegreeCelsiusPerKilometer, degreecelsiusperkilometerQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(LapseRateUnit unit) + { + var quantity = LapseRate.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LapseRateUnit unit) { - var quantityInBaseUnit = LapseRate.FromDegreesCelciusPerKilometer(1).ToBaseUnit(); - Assert.Equal(LapseRate.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = LapseRate.Units.FirstOrDefault(u => u != LapseRate.BaseUnit && u != LapseRateUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == LapseRateUnit.Undefined) + fromUnit = LapseRate.BaseUnit; + + var quantity = LapseRate.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs index 1cb7481f7c..4c7526e104 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -107,6 +108,84 @@ public abstract partial class LengthTestsBase : QuantityTestsBase protected virtual double YardsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LengthUnit unit) + { + return unit switch + { + LengthUnit.AstronomicalUnit => (AstronomicalUnitsInOneMeter, AstronomicalUnitsTolerance), + LengthUnit.Centimeter => (CentimetersInOneMeter, CentimetersTolerance), + LengthUnit.Chain => (ChainsInOneMeter, ChainsTolerance), + LengthUnit.Decimeter => (DecimetersInOneMeter, DecimetersTolerance), + LengthUnit.DtpPica => (DtpPicasInOneMeter, DtpPicasTolerance), + LengthUnit.DtpPoint => (DtpPointsInOneMeter, DtpPointsTolerance), + LengthUnit.Fathom => (FathomsInOneMeter, FathomsTolerance), + LengthUnit.Foot => (FeetInOneMeter, FeetTolerance), + LengthUnit.Hand => (HandsInOneMeter, HandsTolerance), + LengthUnit.Hectometer => (HectometersInOneMeter, HectometersTolerance), + LengthUnit.Inch => (InchesInOneMeter, InchesTolerance), + LengthUnit.KilolightYear => (KilolightYearsInOneMeter, KilolightYearsTolerance), + LengthUnit.Kilometer => (KilometersInOneMeter, KilometersTolerance), + LengthUnit.Kiloparsec => (KiloparsecsInOneMeter, KiloparsecsTolerance), + LengthUnit.LightYear => (LightYearsInOneMeter, LightYearsTolerance), + LengthUnit.MegalightYear => (MegalightYearsInOneMeter, MegalightYearsTolerance), + LengthUnit.Megaparsec => (MegaparsecsInOneMeter, MegaparsecsTolerance), + LengthUnit.Meter => (MetersInOneMeter, MetersTolerance), + LengthUnit.Microinch => (MicroinchesInOneMeter, MicroinchesTolerance), + LengthUnit.Micrometer => (MicrometersInOneMeter, MicrometersTolerance), + LengthUnit.Mil => (MilsInOneMeter, MilsTolerance), + LengthUnit.Mile => (MilesInOneMeter, MilesTolerance), + LengthUnit.Millimeter => (MillimetersInOneMeter, MillimetersTolerance), + LengthUnit.Nanometer => (NanometersInOneMeter, NanometersTolerance), + LengthUnit.NauticalMile => (NauticalMilesInOneMeter, NauticalMilesTolerance), + LengthUnit.Parsec => (ParsecsInOneMeter, ParsecsTolerance), + LengthUnit.PrinterPica => (PrinterPicasInOneMeter, PrinterPicasTolerance), + LengthUnit.PrinterPoint => (PrinterPointsInOneMeter, PrinterPointsTolerance), + LengthUnit.Shackle => (ShacklesInOneMeter, ShacklesTolerance), + LengthUnit.SolarRadius => (SolarRadiusesInOneMeter, SolarRadiusesTolerance), + LengthUnit.Twip => (TwipsInOneMeter, TwipsTolerance), + LengthUnit.UsSurveyFoot => (UsSurveyFeetInOneMeter, UsSurveyFeetTolerance), + LengthUnit.Yard => (YardsInOneMeter, YardsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { LengthUnit.AstronomicalUnit }, + new object[] { LengthUnit.Centimeter }, + new object[] { LengthUnit.Chain }, + new object[] { LengthUnit.Decimeter }, + new object[] { LengthUnit.DtpPica }, + new object[] { LengthUnit.DtpPoint }, + new object[] { LengthUnit.Fathom }, + new object[] { LengthUnit.Foot }, + new object[] { LengthUnit.Hand }, + new object[] { LengthUnit.Hectometer }, + new object[] { LengthUnit.Inch }, + new object[] { LengthUnit.KilolightYear }, + new object[] { LengthUnit.Kilometer }, + new object[] { LengthUnit.Kiloparsec }, + new object[] { LengthUnit.LightYear }, + new object[] { LengthUnit.MegalightYear }, + new object[] { LengthUnit.Megaparsec }, + new object[] { LengthUnit.Meter }, + new object[] { LengthUnit.Microinch }, + new object[] { LengthUnit.Micrometer }, + new object[] { LengthUnit.Mil }, + new object[] { LengthUnit.Mile }, + new object[] { LengthUnit.Millimeter }, + new object[] { LengthUnit.Nanometer }, + new object[] { LengthUnit.NauticalMile }, + new object[] { LengthUnit.Parsec }, + new object[] { LengthUnit.PrinterPica }, + new object[] { LengthUnit.PrinterPoint }, + new object[] { LengthUnit.Shackle }, + new object[] { LengthUnit.SolarRadius }, + new object[] { LengthUnit.Twip }, + new object[] { LengthUnit.UsSurveyFoot }, + new object[] { LengthUnit.Yard }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -420,149 +499,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(LengthUnit unit) { - var meter = Length.FromMeters(1); - - var astronomicalunitQuantity = meter.ToUnit(LengthUnit.AstronomicalUnit); - AssertEx.EqualTolerance(AstronomicalUnitsInOneMeter, (double)astronomicalunitQuantity.Value, AstronomicalUnitsTolerance); - Assert.Equal(LengthUnit.AstronomicalUnit, astronomicalunitQuantity.Unit); - - var centimeterQuantity = meter.ToUnit(LengthUnit.Centimeter); - AssertEx.EqualTolerance(CentimetersInOneMeter, (double)centimeterQuantity.Value, CentimetersTolerance); - Assert.Equal(LengthUnit.Centimeter, centimeterQuantity.Unit); - - var chainQuantity = meter.ToUnit(LengthUnit.Chain); - AssertEx.EqualTolerance(ChainsInOneMeter, (double)chainQuantity.Value, ChainsTolerance); - Assert.Equal(LengthUnit.Chain, chainQuantity.Unit); - - var decimeterQuantity = meter.ToUnit(LengthUnit.Decimeter); - AssertEx.EqualTolerance(DecimetersInOneMeter, (double)decimeterQuantity.Value, DecimetersTolerance); - Assert.Equal(LengthUnit.Decimeter, decimeterQuantity.Unit); - - var dtppicaQuantity = meter.ToUnit(LengthUnit.DtpPica); - AssertEx.EqualTolerance(DtpPicasInOneMeter, (double)dtppicaQuantity.Value, DtpPicasTolerance); - Assert.Equal(LengthUnit.DtpPica, dtppicaQuantity.Unit); - - var dtppointQuantity = meter.ToUnit(LengthUnit.DtpPoint); - AssertEx.EqualTolerance(DtpPointsInOneMeter, (double)dtppointQuantity.Value, DtpPointsTolerance); - Assert.Equal(LengthUnit.DtpPoint, dtppointQuantity.Unit); - - var fathomQuantity = meter.ToUnit(LengthUnit.Fathom); - AssertEx.EqualTolerance(FathomsInOneMeter, (double)fathomQuantity.Value, FathomsTolerance); - Assert.Equal(LengthUnit.Fathom, fathomQuantity.Unit); - - var footQuantity = meter.ToUnit(LengthUnit.Foot); - AssertEx.EqualTolerance(FeetInOneMeter, (double)footQuantity.Value, FeetTolerance); - Assert.Equal(LengthUnit.Foot, footQuantity.Unit); - - var handQuantity = meter.ToUnit(LengthUnit.Hand); - AssertEx.EqualTolerance(HandsInOneMeter, (double)handQuantity.Value, HandsTolerance); - Assert.Equal(LengthUnit.Hand, handQuantity.Unit); - - var hectometerQuantity = meter.ToUnit(LengthUnit.Hectometer); - AssertEx.EqualTolerance(HectometersInOneMeter, (double)hectometerQuantity.Value, HectometersTolerance); - Assert.Equal(LengthUnit.Hectometer, hectometerQuantity.Unit); - - var inchQuantity = meter.ToUnit(LengthUnit.Inch); - AssertEx.EqualTolerance(InchesInOneMeter, (double)inchQuantity.Value, InchesTolerance); - Assert.Equal(LengthUnit.Inch, inchQuantity.Unit); - - var kilolightyearQuantity = meter.ToUnit(LengthUnit.KilolightYear); - AssertEx.EqualTolerance(KilolightYearsInOneMeter, (double)kilolightyearQuantity.Value, KilolightYearsTolerance); - Assert.Equal(LengthUnit.KilolightYear, kilolightyearQuantity.Unit); - - var kilometerQuantity = meter.ToUnit(LengthUnit.Kilometer); - AssertEx.EqualTolerance(KilometersInOneMeter, (double)kilometerQuantity.Value, KilometersTolerance); - Assert.Equal(LengthUnit.Kilometer, kilometerQuantity.Unit); - - var kiloparsecQuantity = meter.ToUnit(LengthUnit.Kiloparsec); - AssertEx.EqualTolerance(KiloparsecsInOneMeter, (double)kiloparsecQuantity.Value, KiloparsecsTolerance); - Assert.Equal(LengthUnit.Kiloparsec, kiloparsecQuantity.Unit); - - var lightyearQuantity = meter.ToUnit(LengthUnit.LightYear); - AssertEx.EqualTolerance(LightYearsInOneMeter, (double)lightyearQuantity.Value, LightYearsTolerance); - Assert.Equal(LengthUnit.LightYear, lightyearQuantity.Unit); + var inBaseUnits = Length.From(1.0, Length.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megalightyearQuantity = meter.ToUnit(LengthUnit.MegalightYear); - AssertEx.EqualTolerance(MegalightYearsInOneMeter, (double)megalightyearQuantity.Value, MegalightYearsTolerance); - Assert.Equal(LengthUnit.MegalightYear, megalightyearQuantity.Unit); - - var megaparsecQuantity = meter.ToUnit(LengthUnit.Megaparsec); - AssertEx.EqualTolerance(MegaparsecsInOneMeter, (double)megaparsecQuantity.Value, MegaparsecsTolerance); - Assert.Equal(LengthUnit.Megaparsec, megaparsecQuantity.Unit); - - var meterQuantity = meter.ToUnit(LengthUnit.Meter); - AssertEx.EqualTolerance(MetersInOneMeter, (double)meterQuantity.Value, MetersTolerance); - Assert.Equal(LengthUnit.Meter, meterQuantity.Unit); - - var microinchQuantity = meter.ToUnit(LengthUnit.Microinch); - AssertEx.EqualTolerance(MicroinchesInOneMeter, (double)microinchQuantity.Value, MicroinchesTolerance); - Assert.Equal(LengthUnit.Microinch, microinchQuantity.Unit); - - var micrometerQuantity = meter.ToUnit(LengthUnit.Micrometer); - AssertEx.EqualTolerance(MicrometersInOneMeter, (double)micrometerQuantity.Value, MicrometersTolerance); - Assert.Equal(LengthUnit.Micrometer, micrometerQuantity.Unit); - - var milQuantity = meter.ToUnit(LengthUnit.Mil); - AssertEx.EqualTolerance(MilsInOneMeter, (double)milQuantity.Value, MilsTolerance); - Assert.Equal(LengthUnit.Mil, milQuantity.Unit); - - var mileQuantity = meter.ToUnit(LengthUnit.Mile); - AssertEx.EqualTolerance(MilesInOneMeter, (double)mileQuantity.Value, MilesTolerance); - Assert.Equal(LengthUnit.Mile, mileQuantity.Unit); - - var millimeterQuantity = meter.ToUnit(LengthUnit.Millimeter); - AssertEx.EqualTolerance(MillimetersInOneMeter, (double)millimeterQuantity.Value, MillimetersTolerance); - Assert.Equal(LengthUnit.Millimeter, millimeterQuantity.Unit); - - var nanometerQuantity = meter.ToUnit(LengthUnit.Nanometer); - AssertEx.EqualTolerance(NanometersInOneMeter, (double)nanometerQuantity.Value, NanometersTolerance); - Assert.Equal(LengthUnit.Nanometer, nanometerQuantity.Unit); - - var nauticalmileQuantity = meter.ToUnit(LengthUnit.NauticalMile); - AssertEx.EqualTolerance(NauticalMilesInOneMeter, (double)nauticalmileQuantity.Value, NauticalMilesTolerance); - Assert.Equal(LengthUnit.NauticalMile, nauticalmileQuantity.Unit); - - var parsecQuantity = meter.ToUnit(LengthUnit.Parsec); - AssertEx.EqualTolerance(ParsecsInOneMeter, (double)parsecQuantity.Value, ParsecsTolerance); - Assert.Equal(LengthUnit.Parsec, parsecQuantity.Unit); - - var printerpicaQuantity = meter.ToUnit(LengthUnit.PrinterPica); - AssertEx.EqualTolerance(PrinterPicasInOneMeter, (double)printerpicaQuantity.Value, PrinterPicasTolerance); - Assert.Equal(LengthUnit.PrinterPica, printerpicaQuantity.Unit); - - var printerpointQuantity = meter.ToUnit(LengthUnit.PrinterPoint); - AssertEx.EqualTolerance(PrinterPointsInOneMeter, (double)printerpointQuantity.Value, PrinterPointsTolerance); - Assert.Equal(LengthUnit.PrinterPoint, printerpointQuantity.Unit); - - var shackleQuantity = meter.ToUnit(LengthUnit.Shackle); - AssertEx.EqualTolerance(ShacklesInOneMeter, (double)shackleQuantity.Value, ShacklesTolerance); - Assert.Equal(LengthUnit.Shackle, shackleQuantity.Unit); - - var solarradiusQuantity = meter.ToUnit(LengthUnit.SolarRadius); - AssertEx.EqualTolerance(SolarRadiusesInOneMeter, (double)solarradiusQuantity.Value, SolarRadiusesTolerance); - Assert.Equal(LengthUnit.SolarRadius, solarradiusQuantity.Unit); - - var twipQuantity = meter.ToUnit(LengthUnit.Twip); - AssertEx.EqualTolerance(TwipsInOneMeter, (double)twipQuantity.Value, TwipsTolerance); - Assert.Equal(LengthUnit.Twip, twipQuantity.Unit); - - var ussurveyfootQuantity = meter.ToUnit(LengthUnit.UsSurveyFoot); - AssertEx.EqualTolerance(UsSurveyFeetInOneMeter, (double)ussurveyfootQuantity.Value, UsSurveyFeetTolerance); - Assert.Equal(LengthUnit.UsSurveyFoot, ussurveyfootQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var yardQuantity = meter.ToUnit(LengthUnit.Yard); - AssertEx.EqualTolerance(YardsInOneMeter, (double)yardQuantity.Value, YardsTolerance); - Assert.Equal(LengthUnit.Yard, yardQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(LengthUnit unit) + { + var quantity = Length.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LengthUnit unit) { - var quantityInBaseUnit = Length.FromMeters(1).ToBaseUnit(); - Assert.Equal(Length.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Length.Units.FirstOrDefault(u => u != Length.BaseUnit && u != LengthUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == LengthUnit.Undefined) + fromUnit = Length.BaseUnit; + + var quantity = Length.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs index 3cc0e5f9bb..27aca88bbf 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -45,6 +46,22 @@ public abstract partial class LevelTestsBase : QuantityTestsBase protected virtual double NepersTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LevelUnit unit) + { + return unit switch + { + LevelUnit.Decibel => (DecibelsInOneDecibel, DecibelsTolerance), + LevelUnit.Neper => (NepersInOneDecibel, NepersTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { LevelUnit.Decibel }, + new object[] { LevelUnit.Neper }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -172,25 +189,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(LevelUnit unit) { - var decibel = Level.FromDecibels(1); + var inBaseUnits = Level.From(1.0, Level.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var decibelQuantity = decibel.ToUnit(LevelUnit.Decibel); - AssertEx.EqualTolerance(DecibelsInOneDecibel, (double)decibelQuantity.Value, DecibelsTolerance); - Assert.Equal(LevelUnit.Decibel, decibelQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var neperQuantity = decibel.ToUnit(LevelUnit.Neper); - AssertEx.EqualTolerance(NepersInOneDecibel, (double)neperQuantity.Value, NepersTolerance); - Assert.Equal(LevelUnit.Neper, neperQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(LevelUnit unit) + { + var quantity = Level.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LevelUnit unit) { - var quantityInBaseUnit = Level.FromDecibels(1).ToBaseUnit(); - Assert.Equal(Level.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Level.Units.FirstOrDefault(u => u != Level.BaseUnit && u != LevelUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == LevelUnit.Undefined) + fromUnit = Level.BaseUnit; + + var quantity = Level.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs index 55b42a0dcd..94e1aab652 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -69,6 +70,46 @@ public abstract partial class LinearDensityTestsBase : QuantityTestsBase protected virtual double PoundsPerInchTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LinearDensityUnit unit) + { + return unit switch + { + LinearDensityUnit.GramPerCentimeter => (GramsPerCentimeterInOneKilogramPerMeter, GramsPerCentimeterTolerance), + LinearDensityUnit.GramPerMeter => (GramsPerMeterInOneKilogramPerMeter, GramsPerMeterTolerance), + LinearDensityUnit.GramPerMillimeter => (GramsPerMillimeterInOneKilogramPerMeter, GramsPerMillimeterTolerance), + LinearDensityUnit.KilogramPerCentimeter => (KilogramsPerCentimeterInOneKilogramPerMeter, KilogramsPerCentimeterTolerance), + LinearDensityUnit.KilogramPerMeter => (KilogramsPerMeterInOneKilogramPerMeter, KilogramsPerMeterTolerance), + LinearDensityUnit.KilogramPerMillimeter => (KilogramsPerMillimeterInOneKilogramPerMeter, KilogramsPerMillimeterTolerance), + LinearDensityUnit.MicrogramPerCentimeter => (MicrogramsPerCentimeterInOneKilogramPerMeter, MicrogramsPerCentimeterTolerance), + LinearDensityUnit.MicrogramPerMeter => (MicrogramsPerMeterInOneKilogramPerMeter, MicrogramsPerMeterTolerance), + LinearDensityUnit.MicrogramPerMillimeter => (MicrogramsPerMillimeterInOneKilogramPerMeter, MicrogramsPerMillimeterTolerance), + LinearDensityUnit.MilligramPerCentimeter => (MilligramsPerCentimeterInOneKilogramPerMeter, MilligramsPerCentimeterTolerance), + LinearDensityUnit.MilligramPerMeter => (MilligramsPerMeterInOneKilogramPerMeter, MilligramsPerMeterTolerance), + LinearDensityUnit.MilligramPerMillimeter => (MilligramsPerMillimeterInOneKilogramPerMeter, MilligramsPerMillimeterTolerance), + LinearDensityUnit.PoundPerFoot => (PoundsPerFootInOneKilogramPerMeter, PoundsPerFootTolerance), + LinearDensityUnit.PoundPerInch => (PoundsPerInchInOneKilogramPerMeter, PoundsPerInchTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { LinearDensityUnit.GramPerCentimeter }, + new object[] { LinearDensityUnit.GramPerMeter }, + new object[] { LinearDensityUnit.GramPerMillimeter }, + new object[] { LinearDensityUnit.KilogramPerCentimeter }, + new object[] { LinearDensityUnit.KilogramPerMeter }, + new object[] { LinearDensityUnit.KilogramPerMillimeter }, + new object[] { LinearDensityUnit.MicrogramPerCentimeter }, + new object[] { LinearDensityUnit.MicrogramPerMeter }, + new object[] { LinearDensityUnit.MicrogramPerMillimeter }, + new object[] { LinearDensityUnit.MilligramPerCentimeter }, + new object[] { LinearDensityUnit.MilligramPerMeter }, + new object[] { LinearDensityUnit.MilligramPerMillimeter }, + new object[] { LinearDensityUnit.PoundPerFoot }, + new object[] { LinearDensityUnit.PoundPerInch }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -268,73 +309,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(LinearDensityUnit unit) { - var kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - - var grampercentimeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.GramPerCentimeter); - AssertEx.EqualTolerance(GramsPerCentimeterInOneKilogramPerMeter, (double)grampercentimeterQuantity.Value, GramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerCentimeter, grampercentimeterQuantity.Unit); - - var grampermeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.GramPerMeter); - AssertEx.EqualTolerance(GramsPerMeterInOneKilogramPerMeter, (double)grampermeterQuantity.Value, GramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerMeter, grampermeterQuantity.Unit); - - var grampermillimeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.GramPerMillimeter); - AssertEx.EqualTolerance(GramsPerMillimeterInOneKilogramPerMeter, (double)grampermillimeterQuantity.Value, GramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerMillimeter, grampermillimeterQuantity.Unit); - - var kilogrampercentimeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.KilogramPerCentimeter); - AssertEx.EqualTolerance(KilogramsPerCentimeterInOneKilogramPerMeter, (double)kilogrampercentimeterQuantity.Value, KilogramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerCentimeter, kilogrampercentimeterQuantity.Unit); - - var kilogrampermeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.KilogramPerMeter); - AssertEx.EqualTolerance(KilogramsPerMeterInOneKilogramPerMeter, (double)kilogrampermeterQuantity.Value, KilogramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerMeter, kilogrampermeterQuantity.Unit); - - var kilogrampermillimeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.KilogramPerMillimeter); - AssertEx.EqualTolerance(KilogramsPerMillimeterInOneKilogramPerMeter, (double)kilogrampermillimeterQuantity.Value, KilogramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerMillimeter, kilogrampermillimeterQuantity.Unit); - - var microgrampercentimeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.MicrogramPerCentimeter); - AssertEx.EqualTolerance(MicrogramsPerCentimeterInOneKilogramPerMeter, (double)microgrampercentimeterQuantity.Value, MicrogramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerCentimeter, microgrampercentimeterQuantity.Unit); + var inBaseUnits = LinearDensity.From(1.0, LinearDensity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var microgrampermeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.MicrogramPerMeter); - AssertEx.EqualTolerance(MicrogramsPerMeterInOneKilogramPerMeter, (double)microgrampermeterQuantity.Value, MicrogramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerMeter, microgrampermeterQuantity.Unit); - - var microgrampermillimeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.MicrogramPerMillimeter); - AssertEx.EqualTolerance(MicrogramsPerMillimeterInOneKilogramPerMeter, (double)microgrampermillimeterQuantity.Value, MicrogramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerMillimeter, microgrampermillimeterQuantity.Unit); - - var milligrampercentimeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.MilligramPerCentimeter); - AssertEx.EqualTolerance(MilligramsPerCentimeterInOneKilogramPerMeter, (double)milligrampercentimeterQuantity.Value, MilligramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerCentimeter, milligrampercentimeterQuantity.Unit); - - var milligrampermeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.MilligramPerMeter); - AssertEx.EqualTolerance(MilligramsPerMeterInOneKilogramPerMeter, (double)milligrampermeterQuantity.Value, MilligramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerMeter, milligrampermeterQuantity.Unit); - - var milligrampermillimeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.MilligramPerMillimeter); - AssertEx.EqualTolerance(MilligramsPerMillimeterInOneKilogramPerMeter, (double)milligrampermillimeterQuantity.Value, MilligramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerMillimeter, milligrampermillimeterQuantity.Unit); - - var poundperfootQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.PoundPerFoot); - AssertEx.EqualTolerance(PoundsPerFootInOneKilogramPerMeter, (double)poundperfootQuantity.Value, PoundsPerFootTolerance); - Assert.Equal(LinearDensityUnit.PoundPerFoot, poundperfootQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var poundperinchQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.PoundPerInch); - AssertEx.EqualTolerance(PoundsPerInchInOneKilogramPerMeter, (double)poundperinchQuantity.Value, PoundsPerInchTolerance); - Assert.Equal(LinearDensityUnit.PoundPerInch, poundperinchQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(LinearDensityUnit unit) + { + var quantity = LinearDensity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LinearDensityUnit unit) { - var quantityInBaseUnit = LinearDensity.FromKilogramsPerMeter(1).ToBaseUnit(); - Assert.Equal(LinearDensity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = LinearDensity.Units.FirstOrDefault(u => u != LinearDensity.BaseUnit && u != LinearDensityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == LinearDensityUnit.Undefined) + fromUnit = LinearDensity.BaseUnit; + + var quantity = LinearDensity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs index d6b7623329..9ced6699e2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -91,6 +92,68 @@ public abstract partial class LinearPowerDensityTestsBase : QuantityTestsBase protected virtual double WattsPerMillimeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LinearPowerDensityUnit unit) + { + return unit switch + { + LinearPowerDensityUnit.GigawattPerCentimeter => (GigawattsPerCentimeterInOneWattPerMeter, GigawattsPerCentimeterTolerance), + LinearPowerDensityUnit.GigawattPerFoot => (GigawattsPerFootInOneWattPerMeter, GigawattsPerFootTolerance), + LinearPowerDensityUnit.GigawattPerInch => (GigawattsPerInchInOneWattPerMeter, GigawattsPerInchTolerance), + LinearPowerDensityUnit.GigawattPerMeter => (GigawattsPerMeterInOneWattPerMeter, GigawattsPerMeterTolerance), + LinearPowerDensityUnit.GigawattPerMillimeter => (GigawattsPerMillimeterInOneWattPerMeter, GigawattsPerMillimeterTolerance), + LinearPowerDensityUnit.KilowattPerCentimeter => (KilowattsPerCentimeterInOneWattPerMeter, KilowattsPerCentimeterTolerance), + LinearPowerDensityUnit.KilowattPerFoot => (KilowattsPerFootInOneWattPerMeter, KilowattsPerFootTolerance), + LinearPowerDensityUnit.KilowattPerInch => (KilowattsPerInchInOneWattPerMeter, KilowattsPerInchTolerance), + LinearPowerDensityUnit.KilowattPerMeter => (KilowattsPerMeterInOneWattPerMeter, KilowattsPerMeterTolerance), + LinearPowerDensityUnit.KilowattPerMillimeter => (KilowattsPerMillimeterInOneWattPerMeter, KilowattsPerMillimeterTolerance), + LinearPowerDensityUnit.MegawattPerCentimeter => (MegawattsPerCentimeterInOneWattPerMeter, MegawattsPerCentimeterTolerance), + LinearPowerDensityUnit.MegawattPerFoot => (MegawattsPerFootInOneWattPerMeter, MegawattsPerFootTolerance), + LinearPowerDensityUnit.MegawattPerInch => (MegawattsPerInchInOneWattPerMeter, MegawattsPerInchTolerance), + LinearPowerDensityUnit.MegawattPerMeter => (MegawattsPerMeterInOneWattPerMeter, MegawattsPerMeterTolerance), + LinearPowerDensityUnit.MegawattPerMillimeter => (MegawattsPerMillimeterInOneWattPerMeter, MegawattsPerMillimeterTolerance), + LinearPowerDensityUnit.MilliwattPerCentimeter => (MilliwattsPerCentimeterInOneWattPerMeter, MilliwattsPerCentimeterTolerance), + LinearPowerDensityUnit.MilliwattPerFoot => (MilliwattsPerFootInOneWattPerMeter, MilliwattsPerFootTolerance), + LinearPowerDensityUnit.MilliwattPerInch => (MilliwattsPerInchInOneWattPerMeter, MilliwattsPerInchTolerance), + LinearPowerDensityUnit.MilliwattPerMeter => (MilliwattsPerMeterInOneWattPerMeter, MilliwattsPerMeterTolerance), + LinearPowerDensityUnit.MilliwattPerMillimeter => (MilliwattsPerMillimeterInOneWattPerMeter, MilliwattsPerMillimeterTolerance), + LinearPowerDensityUnit.WattPerCentimeter => (WattsPerCentimeterInOneWattPerMeter, WattsPerCentimeterTolerance), + LinearPowerDensityUnit.WattPerFoot => (WattsPerFootInOneWattPerMeter, WattsPerFootTolerance), + LinearPowerDensityUnit.WattPerInch => (WattsPerInchInOneWattPerMeter, WattsPerInchTolerance), + LinearPowerDensityUnit.WattPerMeter => (WattsPerMeterInOneWattPerMeter, WattsPerMeterTolerance), + LinearPowerDensityUnit.WattPerMillimeter => (WattsPerMillimeterInOneWattPerMeter, WattsPerMillimeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { LinearPowerDensityUnit.GigawattPerCentimeter }, + new object[] { LinearPowerDensityUnit.GigawattPerFoot }, + new object[] { LinearPowerDensityUnit.GigawattPerInch }, + new object[] { LinearPowerDensityUnit.GigawattPerMeter }, + new object[] { LinearPowerDensityUnit.GigawattPerMillimeter }, + new object[] { LinearPowerDensityUnit.KilowattPerCentimeter }, + new object[] { LinearPowerDensityUnit.KilowattPerFoot }, + new object[] { LinearPowerDensityUnit.KilowattPerInch }, + new object[] { LinearPowerDensityUnit.KilowattPerMeter }, + new object[] { LinearPowerDensityUnit.KilowattPerMillimeter }, + new object[] { LinearPowerDensityUnit.MegawattPerCentimeter }, + new object[] { LinearPowerDensityUnit.MegawattPerFoot }, + new object[] { LinearPowerDensityUnit.MegawattPerInch }, + new object[] { LinearPowerDensityUnit.MegawattPerMeter }, + new object[] { LinearPowerDensityUnit.MegawattPerMillimeter }, + new object[] { LinearPowerDensityUnit.MilliwattPerCentimeter }, + new object[] { LinearPowerDensityUnit.MilliwattPerFoot }, + new object[] { LinearPowerDensityUnit.MilliwattPerInch }, + new object[] { LinearPowerDensityUnit.MilliwattPerMeter }, + new object[] { LinearPowerDensityUnit.MilliwattPerMillimeter }, + new object[] { LinearPowerDensityUnit.WattPerCentimeter }, + new object[] { LinearPowerDensityUnit.WattPerFoot }, + new object[] { LinearPowerDensityUnit.WattPerInch }, + new object[] { LinearPowerDensityUnit.WattPerMeter }, + new object[] { LinearPowerDensityUnit.WattPerMillimeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -356,117 +419,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(LinearPowerDensityUnit unit) { - var wattpermeter = LinearPowerDensity.FromWattsPerMeter(1); - - var gigawattpercentimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.GigawattPerCentimeter); - AssertEx.EqualTolerance(GigawattsPerCentimeterInOneWattPerMeter, (double)gigawattpercentimeterQuantity.Value, GigawattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerCentimeter, gigawattpercentimeterQuantity.Unit); - - var gigawattperfootQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.GigawattPerFoot); - AssertEx.EqualTolerance(GigawattsPerFootInOneWattPerMeter, (double)gigawattperfootQuantity.Value, GigawattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerFoot, gigawattperfootQuantity.Unit); - - var gigawattperinchQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.GigawattPerInch); - AssertEx.EqualTolerance(GigawattsPerInchInOneWattPerMeter, (double)gigawattperinchQuantity.Value, GigawattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerInch, gigawattperinchQuantity.Unit); - - var gigawattpermeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.GigawattPerMeter); - AssertEx.EqualTolerance(GigawattsPerMeterInOneWattPerMeter, (double)gigawattpermeterQuantity.Value, GigawattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerMeter, gigawattpermeterQuantity.Unit); - - var gigawattpermillimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.GigawattPerMillimeter); - AssertEx.EqualTolerance(GigawattsPerMillimeterInOneWattPerMeter, (double)gigawattpermillimeterQuantity.Value, GigawattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerMillimeter, gigawattpermillimeterQuantity.Unit); - - var kilowattpercentimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.KilowattPerCentimeter); - AssertEx.EqualTolerance(KilowattsPerCentimeterInOneWattPerMeter, (double)kilowattpercentimeterQuantity.Value, KilowattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerCentimeter, kilowattpercentimeterQuantity.Unit); - - var kilowattperfootQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.KilowattPerFoot); - AssertEx.EqualTolerance(KilowattsPerFootInOneWattPerMeter, (double)kilowattperfootQuantity.Value, KilowattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerFoot, kilowattperfootQuantity.Unit); - - var kilowattperinchQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.KilowattPerInch); - AssertEx.EqualTolerance(KilowattsPerInchInOneWattPerMeter, (double)kilowattperinchQuantity.Value, KilowattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerInch, kilowattperinchQuantity.Unit); - - var kilowattpermeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.KilowattPerMeter); - AssertEx.EqualTolerance(KilowattsPerMeterInOneWattPerMeter, (double)kilowattpermeterQuantity.Value, KilowattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerMeter, kilowattpermeterQuantity.Unit); - - var kilowattpermillimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.KilowattPerMillimeter); - AssertEx.EqualTolerance(KilowattsPerMillimeterInOneWattPerMeter, (double)kilowattpermillimeterQuantity.Value, KilowattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerMillimeter, kilowattpermillimeterQuantity.Unit); - - var megawattpercentimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MegawattPerCentimeter); - AssertEx.EqualTolerance(MegawattsPerCentimeterInOneWattPerMeter, (double)megawattpercentimeterQuantity.Value, MegawattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerCentimeter, megawattpercentimeterQuantity.Unit); - - var megawattperfootQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MegawattPerFoot); - AssertEx.EqualTolerance(MegawattsPerFootInOneWattPerMeter, (double)megawattperfootQuantity.Value, MegawattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerFoot, megawattperfootQuantity.Unit); + var inBaseUnits = LinearPowerDensity.From(1.0, LinearPowerDensity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megawattperinchQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MegawattPerInch); - AssertEx.EqualTolerance(MegawattsPerInchInOneWattPerMeter, (double)megawattperinchQuantity.Value, MegawattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerInch, megawattperinchQuantity.Unit); - - var megawattpermeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MegawattPerMeter); - AssertEx.EqualTolerance(MegawattsPerMeterInOneWattPerMeter, (double)megawattpermeterQuantity.Value, MegawattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerMeter, megawattpermeterQuantity.Unit); - - var megawattpermillimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MegawattPerMillimeter); - AssertEx.EqualTolerance(MegawattsPerMillimeterInOneWattPerMeter, (double)megawattpermillimeterQuantity.Value, MegawattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerMillimeter, megawattpermillimeterQuantity.Unit); - - var milliwattpercentimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MilliwattPerCentimeter); - AssertEx.EqualTolerance(MilliwattsPerCentimeterInOneWattPerMeter, (double)milliwattpercentimeterQuantity.Value, MilliwattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerCentimeter, milliwattpercentimeterQuantity.Unit); - - var milliwattperfootQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MilliwattPerFoot); - AssertEx.EqualTolerance(MilliwattsPerFootInOneWattPerMeter, (double)milliwattperfootQuantity.Value, MilliwattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerFoot, milliwattperfootQuantity.Unit); - - var milliwattperinchQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MilliwattPerInch); - AssertEx.EqualTolerance(MilliwattsPerInchInOneWattPerMeter, (double)milliwattperinchQuantity.Value, MilliwattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerInch, milliwattperinchQuantity.Unit); - - var milliwattpermeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MilliwattPerMeter); - AssertEx.EqualTolerance(MilliwattsPerMeterInOneWattPerMeter, (double)milliwattpermeterQuantity.Value, MilliwattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerMeter, milliwattpermeterQuantity.Unit); - - var milliwattpermillimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.MilliwattPerMillimeter); - AssertEx.EqualTolerance(MilliwattsPerMillimeterInOneWattPerMeter, (double)milliwattpermillimeterQuantity.Value, MilliwattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerMillimeter, milliwattpermillimeterQuantity.Unit); - - var wattpercentimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.WattPerCentimeter); - AssertEx.EqualTolerance(WattsPerCentimeterInOneWattPerMeter, (double)wattpercentimeterQuantity.Value, WattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerCentimeter, wattpercentimeterQuantity.Unit); - - var wattperfootQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.WattPerFoot); - AssertEx.EqualTolerance(WattsPerFootInOneWattPerMeter, (double)wattperfootQuantity.Value, WattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerFoot, wattperfootQuantity.Unit); - - var wattperinchQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.WattPerInch); - AssertEx.EqualTolerance(WattsPerInchInOneWattPerMeter, (double)wattperinchQuantity.Value, WattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerInch, wattperinchQuantity.Unit); - - var wattpermeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.WattPerMeter); - AssertEx.EqualTolerance(WattsPerMeterInOneWattPerMeter, (double)wattpermeterQuantity.Value, WattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerMeter, wattpermeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var wattpermillimeterQuantity = wattpermeter.ToUnit(LinearPowerDensityUnit.WattPerMillimeter); - AssertEx.EqualTolerance(WattsPerMillimeterInOneWattPerMeter, (double)wattpermillimeterQuantity.Value, WattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerMillimeter, wattpermillimeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(LinearPowerDensityUnit unit) + { + var quantity = LinearPowerDensity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LinearPowerDensityUnit unit) { - var quantityInBaseUnit = LinearPowerDensity.FromWattsPerMeter(1).ToBaseUnit(); - Assert.Equal(LinearPowerDensity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = LinearPowerDensity.Units.FirstOrDefault(u => u != LinearPowerDensity.BaseUnit && u != LinearPowerDensityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == LinearPowerDensityUnit.Undefined) + fromUnit = LinearPowerDensity.BaseUnit; + + var quantity = LinearPowerDensity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs index ef5509b976..28c34e2b5c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -69,6 +70,46 @@ public abstract partial class LuminosityTestsBase : QuantityTestsBase protected virtual double WattsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LuminosityUnit unit) + { + return unit switch + { + LuminosityUnit.Decawatt => (DecawattsInOneWatt, DecawattsTolerance), + LuminosityUnit.Deciwatt => (DeciwattsInOneWatt, DeciwattsTolerance), + LuminosityUnit.Femtowatt => (FemtowattsInOneWatt, FemtowattsTolerance), + LuminosityUnit.Gigawatt => (GigawattsInOneWatt, GigawattsTolerance), + LuminosityUnit.Kilowatt => (KilowattsInOneWatt, KilowattsTolerance), + LuminosityUnit.Megawatt => (MegawattsInOneWatt, MegawattsTolerance), + LuminosityUnit.Microwatt => (MicrowattsInOneWatt, MicrowattsTolerance), + LuminosityUnit.Milliwatt => (MilliwattsInOneWatt, MilliwattsTolerance), + LuminosityUnit.Nanowatt => (NanowattsInOneWatt, NanowattsTolerance), + LuminosityUnit.Petawatt => (PetawattsInOneWatt, PetawattsTolerance), + LuminosityUnit.Picowatt => (PicowattsInOneWatt, PicowattsTolerance), + LuminosityUnit.SolarLuminosity => (SolarLuminositiesInOneWatt, SolarLuminositiesTolerance), + LuminosityUnit.Terawatt => (TerawattsInOneWatt, TerawattsTolerance), + LuminosityUnit.Watt => (WattsInOneWatt, WattsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { LuminosityUnit.Decawatt }, + new object[] { LuminosityUnit.Deciwatt }, + new object[] { LuminosityUnit.Femtowatt }, + new object[] { LuminosityUnit.Gigawatt }, + new object[] { LuminosityUnit.Kilowatt }, + new object[] { LuminosityUnit.Megawatt }, + new object[] { LuminosityUnit.Microwatt }, + new object[] { LuminosityUnit.Milliwatt }, + new object[] { LuminosityUnit.Nanowatt }, + new object[] { LuminosityUnit.Petawatt }, + new object[] { LuminosityUnit.Picowatt }, + new object[] { LuminosityUnit.SolarLuminosity }, + new object[] { LuminosityUnit.Terawatt }, + new object[] { LuminosityUnit.Watt }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -268,73 +309,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(LuminosityUnit unit) { - var watt = Luminosity.FromWatts(1); - - var decawattQuantity = watt.ToUnit(LuminosityUnit.Decawatt); - AssertEx.EqualTolerance(DecawattsInOneWatt, (double)decawattQuantity.Value, DecawattsTolerance); - Assert.Equal(LuminosityUnit.Decawatt, decawattQuantity.Unit); - - var deciwattQuantity = watt.ToUnit(LuminosityUnit.Deciwatt); - AssertEx.EqualTolerance(DeciwattsInOneWatt, (double)deciwattQuantity.Value, DeciwattsTolerance); - Assert.Equal(LuminosityUnit.Deciwatt, deciwattQuantity.Unit); - - var femtowattQuantity = watt.ToUnit(LuminosityUnit.Femtowatt); - AssertEx.EqualTolerance(FemtowattsInOneWatt, (double)femtowattQuantity.Value, FemtowattsTolerance); - Assert.Equal(LuminosityUnit.Femtowatt, femtowattQuantity.Unit); - - var gigawattQuantity = watt.ToUnit(LuminosityUnit.Gigawatt); - AssertEx.EqualTolerance(GigawattsInOneWatt, (double)gigawattQuantity.Value, GigawattsTolerance); - Assert.Equal(LuminosityUnit.Gigawatt, gigawattQuantity.Unit); - - var kilowattQuantity = watt.ToUnit(LuminosityUnit.Kilowatt); - AssertEx.EqualTolerance(KilowattsInOneWatt, (double)kilowattQuantity.Value, KilowattsTolerance); - Assert.Equal(LuminosityUnit.Kilowatt, kilowattQuantity.Unit); - - var megawattQuantity = watt.ToUnit(LuminosityUnit.Megawatt); - AssertEx.EqualTolerance(MegawattsInOneWatt, (double)megawattQuantity.Value, MegawattsTolerance); - Assert.Equal(LuminosityUnit.Megawatt, megawattQuantity.Unit); - - var microwattQuantity = watt.ToUnit(LuminosityUnit.Microwatt); - AssertEx.EqualTolerance(MicrowattsInOneWatt, (double)microwattQuantity.Value, MicrowattsTolerance); - Assert.Equal(LuminosityUnit.Microwatt, microwattQuantity.Unit); + var inBaseUnits = Luminosity.From(1.0, Luminosity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var milliwattQuantity = watt.ToUnit(LuminosityUnit.Milliwatt); - AssertEx.EqualTolerance(MilliwattsInOneWatt, (double)milliwattQuantity.Value, MilliwattsTolerance); - Assert.Equal(LuminosityUnit.Milliwatt, milliwattQuantity.Unit); - - var nanowattQuantity = watt.ToUnit(LuminosityUnit.Nanowatt); - AssertEx.EqualTolerance(NanowattsInOneWatt, (double)nanowattQuantity.Value, NanowattsTolerance); - Assert.Equal(LuminosityUnit.Nanowatt, nanowattQuantity.Unit); - - var petawattQuantity = watt.ToUnit(LuminosityUnit.Petawatt); - AssertEx.EqualTolerance(PetawattsInOneWatt, (double)petawattQuantity.Value, PetawattsTolerance); - Assert.Equal(LuminosityUnit.Petawatt, petawattQuantity.Unit); - - var picowattQuantity = watt.ToUnit(LuminosityUnit.Picowatt); - AssertEx.EqualTolerance(PicowattsInOneWatt, (double)picowattQuantity.Value, PicowattsTolerance); - Assert.Equal(LuminosityUnit.Picowatt, picowattQuantity.Unit); - - var solarluminosityQuantity = watt.ToUnit(LuminosityUnit.SolarLuminosity); - AssertEx.EqualTolerance(SolarLuminositiesInOneWatt, (double)solarluminosityQuantity.Value, SolarLuminositiesTolerance); - Assert.Equal(LuminosityUnit.SolarLuminosity, solarluminosityQuantity.Unit); - - var terawattQuantity = watt.ToUnit(LuminosityUnit.Terawatt); - AssertEx.EqualTolerance(TerawattsInOneWatt, (double)terawattQuantity.Value, TerawattsTolerance); - Assert.Equal(LuminosityUnit.Terawatt, terawattQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var wattQuantity = watt.ToUnit(LuminosityUnit.Watt); - AssertEx.EqualTolerance(WattsInOneWatt, (double)wattQuantity.Value, WattsTolerance); - Assert.Equal(LuminosityUnit.Watt, wattQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(LuminosityUnit unit) + { + var quantity = Luminosity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminosityUnit unit) { - var quantityInBaseUnit = Luminosity.FromWatts(1).ToBaseUnit(); - Assert.Equal(Luminosity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Luminosity.Units.FirstOrDefault(u => u != Luminosity.BaseUnit && u != LuminosityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == LuminosityUnit.Undefined) + fromUnit = Luminosity.BaseUnit; + + var quantity = Luminosity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs index 6ce9dae421..4cbf4ecf65 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class LuminousFluxTestsBase : QuantityTestsBase protected virtual double LumensTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LuminousFluxUnit unit) + { + return unit switch + { + LuminousFluxUnit.Lumen => (LumensInOneLumen, LumensTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { LuminousFluxUnit.Lumen }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(LuminousFluxUnit unit) { - var lumen = LuminousFlux.FromLumens(1); + var inBaseUnits = LuminousFlux.From(1.0, LuminousFlux.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var lumenQuantity = lumen.ToUnit(LuminousFluxUnit.Lumen); - AssertEx.EqualTolerance(LumensInOneLumen, (double)lumenQuantity.Value, LumensTolerance); - Assert.Equal(LuminousFluxUnit.Lumen, lumenQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(LuminousFluxUnit unit) + { + var quantity = LuminousFlux.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminousFluxUnit unit) { - var quantityInBaseUnit = LuminousFlux.FromLumens(1).ToBaseUnit(); - Assert.Equal(LuminousFlux.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = LuminousFlux.Units.FirstOrDefault(u => u != LuminousFlux.BaseUnit && u != LuminousFluxUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == LuminousFluxUnit.Undefined) + fromUnit = LuminousFlux.BaseUnit; + + var quantity = LuminousFlux.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs index 7aa01f9f41..6b4462baa1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class LuminousIntensityTestsBase : QuantityTestsBase protected virtual double CandelaTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LuminousIntensityUnit unit) + { + return unit switch + { + LuminousIntensityUnit.Candela => (CandelaInOneCandela, CandelaTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { LuminousIntensityUnit.Candela }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(LuminousIntensityUnit unit) { - var candela = LuminousIntensity.FromCandela(1); + var inBaseUnits = LuminousIntensity.From(1.0, LuminousIntensity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var candelaQuantity = candela.ToUnit(LuminousIntensityUnit.Candela); - AssertEx.EqualTolerance(CandelaInOneCandela, (double)candelaQuantity.Value, CandelaTolerance); - Assert.Equal(LuminousIntensityUnit.Candela, candelaQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(LuminousIntensityUnit unit) + { + var quantity = LuminousIntensity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminousIntensityUnit unit) { - var quantityInBaseUnit = LuminousIntensity.FromCandela(1).ToBaseUnit(); - Assert.Equal(LuminousIntensity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = LuminousIntensity.Units.FirstOrDefault(u => u != LuminousIntensity.BaseUnit && u != LuminousIntensityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == LuminousIntensityUnit.Undefined) + fromUnit = LuminousIntensity.BaseUnit; + + var quantity = LuminousIntensity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs index fb0b6872b0..535a956905 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -53,6 +54,30 @@ public abstract partial class MagneticFieldTestsBase : QuantityTestsBase protected virtual double TeslasTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MagneticFieldUnit unit) + { + return unit switch + { + MagneticFieldUnit.Gauss => (GaussesInOneTesla, GaussesTolerance), + MagneticFieldUnit.Microtesla => (MicroteslasInOneTesla, MicroteslasTolerance), + MagneticFieldUnit.Milligauss => (MilligaussesInOneTesla, MilligaussesTolerance), + MagneticFieldUnit.Millitesla => (MilliteslasInOneTesla, MilliteslasTolerance), + MagneticFieldUnit.Nanotesla => (NanoteslasInOneTesla, NanoteslasTolerance), + MagneticFieldUnit.Tesla => (TeslasInOneTesla, TeslasTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MagneticFieldUnit.Gauss }, + new object[] { MagneticFieldUnit.Microtesla }, + new object[] { MagneticFieldUnit.Milligauss }, + new object[] { MagneticFieldUnit.Millitesla }, + new object[] { MagneticFieldUnit.Nanotesla }, + new object[] { MagneticFieldUnit.Tesla }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -204,41 +229,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MagneticFieldUnit unit) { - var tesla = MagneticField.FromTeslas(1); - - var gaussQuantity = tesla.ToUnit(MagneticFieldUnit.Gauss); - AssertEx.EqualTolerance(GaussesInOneTesla, (double)gaussQuantity.Value, GaussesTolerance); - Assert.Equal(MagneticFieldUnit.Gauss, gaussQuantity.Unit); + var inBaseUnits = MagneticField.From(1.0, MagneticField.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var microteslaQuantity = tesla.ToUnit(MagneticFieldUnit.Microtesla); - AssertEx.EqualTolerance(MicroteslasInOneTesla, (double)microteslaQuantity.Value, MicroteslasTolerance); - Assert.Equal(MagneticFieldUnit.Microtesla, microteslaQuantity.Unit); - - var milligaussQuantity = tesla.ToUnit(MagneticFieldUnit.Milligauss); - AssertEx.EqualTolerance(MilligaussesInOneTesla, (double)milligaussQuantity.Value, MilligaussesTolerance); - Assert.Equal(MagneticFieldUnit.Milligauss, milligaussQuantity.Unit); - - var milliteslaQuantity = tesla.ToUnit(MagneticFieldUnit.Millitesla); - AssertEx.EqualTolerance(MilliteslasInOneTesla, (double)milliteslaQuantity.Value, MilliteslasTolerance); - Assert.Equal(MagneticFieldUnit.Millitesla, milliteslaQuantity.Unit); - - var nanoteslaQuantity = tesla.ToUnit(MagneticFieldUnit.Nanotesla); - AssertEx.EqualTolerance(NanoteslasInOneTesla, (double)nanoteslaQuantity.Value, NanoteslasTolerance); - Assert.Equal(MagneticFieldUnit.Nanotesla, nanoteslaQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var teslaQuantity = tesla.ToUnit(MagneticFieldUnit.Tesla); - AssertEx.EqualTolerance(TeslasInOneTesla, (double)teslaQuantity.Value, TeslasTolerance); - Assert.Equal(MagneticFieldUnit.Tesla, teslaQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MagneticFieldUnit unit) + { + var quantity = MagneticField.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagneticFieldUnit unit) { - var quantityInBaseUnit = MagneticField.FromTeslas(1).ToBaseUnit(); - Assert.Equal(MagneticField.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MagneticField.Units.FirstOrDefault(u => u != MagneticField.BaseUnit && u != MagneticFieldUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MagneticFieldUnit.Undefined) + fromUnit = MagneticField.BaseUnit; + + var quantity = MagneticField.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs index ec2730dae4..53cceaa13a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class MagneticFluxTestsBase : QuantityTestsBase protected virtual double WebersTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MagneticFluxUnit unit) + { + return unit switch + { + MagneticFluxUnit.Weber => (WebersInOneWeber, WebersTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MagneticFluxUnit.Weber }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MagneticFluxUnit unit) { - var weber = MagneticFlux.FromWebers(1); + var inBaseUnits = MagneticFlux.From(1.0, MagneticFlux.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var weberQuantity = weber.ToUnit(MagneticFluxUnit.Weber); - AssertEx.EqualTolerance(WebersInOneWeber, (double)weberQuantity.Value, WebersTolerance); - Assert.Equal(MagneticFluxUnit.Weber, weberQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MagneticFluxUnit unit) + { + var quantity = MagneticFlux.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagneticFluxUnit unit) { - var quantityInBaseUnit = MagneticFlux.FromWebers(1).ToBaseUnit(); - Assert.Equal(MagneticFlux.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MagneticFlux.Units.FirstOrDefault(u => u != MagneticFlux.BaseUnit && u != MagneticFluxUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MagneticFluxUnit.Undefined) + fromUnit = MagneticFlux.BaseUnit; + + var quantity = MagneticFlux.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs index a1af95cb71..f77864e13f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class MagnetizationTestsBase : QuantityTestsBase protected virtual double AmperesPerMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MagnetizationUnit unit) + { + return unit switch + { + MagnetizationUnit.AmperePerMeter => (AmperesPerMeterInOneAmperePerMeter, AmperesPerMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MagnetizationUnit.AmperePerMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MagnetizationUnit unit) { - var amperepermeter = Magnetization.FromAmperesPerMeter(1); + var inBaseUnits = Magnetization.From(1.0, Magnetization.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var amperepermeterQuantity = amperepermeter.ToUnit(MagnetizationUnit.AmperePerMeter); - AssertEx.EqualTolerance(AmperesPerMeterInOneAmperePerMeter, (double)amperepermeterQuantity.Value, AmperesPerMeterTolerance); - Assert.Equal(MagnetizationUnit.AmperePerMeter, amperepermeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MagnetizationUnit unit) + { + var quantity = Magnetization.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagnetizationUnit unit) { - var quantityInBaseUnit = Magnetization.FromAmperesPerMeter(1).ToBaseUnit(); - Assert.Equal(Magnetization.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Magnetization.Units.FirstOrDefault(u => u != Magnetization.BaseUnit && u != MagnetizationUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MagnetizationUnit.Undefined) + fromUnit = Magnetization.BaseUnit; + + var quantity = Magnetization.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs index 49c606599d..8281d5947a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -139,6 +140,116 @@ public abstract partial class MassConcentrationTestsBase : QuantityTestsBase protected virtual double TonnesPerCubicMillimeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassConcentrationUnit unit) + { + return unit switch + { + MassConcentrationUnit.CentigramPerDeciliter => (CentigramsPerDeciliterInOneKilogramPerCubicMeter, CentigramsPerDeciliterTolerance), + MassConcentrationUnit.CentigramPerLiter => (CentigramsPerLiterInOneKilogramPerCubicMeter, CentigramsPerLiterTolerance), + MassConcentrationUnit.CentigramPerMicroliter => (CentigramsPerMicroliterInOneKilogramPerCubicMeter, CentigramsPerMicroliterTolerance), + MassConcentrationUnit.CentigramPerMilliliter => (CentigramsPerMilliliterInOneKilogramPerCubicMeter, CentigramsPerMilliliterTolerance), + MassConcentrationUnit.DecigramPerDeciliter => (DecigramsPerDeciliterInOneKilogramPerCubicMeter, DecigramsPerDeciliterTolerance), + MassConcentrationUnit.DecigramPerLiter => (DecigramsPerLiterInOneKilogramPerCubicMeter, DecigramsPerLiterTolerance), + MassConcentrationUnit.DecigramPerMicroliter => (DecigramsPerMicroliterInOneKilogramPerCubicMeter, DecigramsPerMicroliterTolerance), + MassConcentrationUnit.DecigramPerMilliliter => (DecigramsPerMilliliterInOneKilogramPerCubicMeter, DecigramsPerMilliliterTolerance), + MassConcentrationUnit.GramPerCubicCentimeter => (GramsPerCubicCentimeterInOneKilogramPerCubicMeter, GramsPerCubicCentimeterTolerance), + MassConcentrationUnit.GramPerCubicMeter => (GramsPerCubicMeterInOneKilogramPerCubicMeter, GramsPerCubicMeterTolerance), + MassConcentrationUnit.GramPerCubicMillimeter => (GramsPerCubicMillimeterInOneKilogramPerCubicMeter, GramsPerCubicMillimeterTolerance), + MassConcentrationUnit.GramPerDeciliter => (GramsPerDeciliterInOneKilogramPerCubicMeter, GramsPerDeciliterTolerance), + MassConcentrationUnit.GramPerLiter => (GramsPerLiterInOneKilogramPerCubicMeter, GramsPerLiterTolerance), + MassConcentrationUnit.GramPerMicroliter => (GramsPerMicroliterInOneKilogramPerCubicMeter, GramsPerMicroliterTolerance), + MassConcentrationUnit.GramPerMilliliter => (GramsPerMilliliterInOneKilogramPerCubicMeter, GramsPerMilliliterTolerance), + MassConcentrationUnit.KilogramPerCubicCentimeter => (KilogramsPerCubicCentimeterInOneKilogramPerCubicMeter, KilogramsPerCubicCentimeterTolerance), + MassConcentrationUnit.KilogramPerCubicMeter => (KilogramsPerCubicMeterInOneKilogramPerCubicMeter, KilogramsPerCubicMeterTolerance), + MassConcentrationUnit.KilogramPerCubicMillimeter => (KilogramsPerCubicMillimeterInOneKilogramPerCubicMeter, KilogramsPerCubicMillimeterTolerance), + MassConcentrationUnit.KilogramPerLiter => (KilogramsPerLiterInOneKilogramPerCubicMeter, KilogramsPerLiterTolerance), + MassConcentrationUnit.KilopoundPerCubicFoot => (KilopoundsPerCubicFootInOneKilogramPerCubicMeter, KilopoundsPerCubicFootTolerance), + MassConcentrationUnit.KilopoundPerCubicInch => (KilopoundsPerCubicInchInOneKilogramPerCubicMeter, KilopoundsPerCubicInchTolerance), + MassConcentrationUnit.MicrogramPerCubicMeter => (MicrogramsPerCubicMeterInOneKilogramPerCubicMeter, MicrogramsPerCubicMeterTolerance), + MassConcentrationUnit.MicrogramPerDeciliter => (MicrogramsPerDeciliterInOneKilogramPerCubicMeter, MicrogramsPerDeciliterTolerance), + MassConcentrationUnit.MicrogramPerLiter => (MicrogramsPerLiterInOneKilogramPerCubicMeter, MicrogramsPerLiterTolerance), + MassConcentrationUnit.MicrogramPerMicroliter => (MicrogramsPerMicroliterInOneKilogramPerCubicMeter, MicrogramsPerMicroliterTolerance), + MassConcentrationUnit.MicrogramPerMilliliter => (MicrogramsPerMilliliterInOneKilogramPerCubicMeter, MicrogramsPerMilliliterTolerance), + MassConcentrationUnit.MilligramPerCubicMeter => (MilligramsPerCubicMeterInOneKilogramPerCubicMeter, MilligramsPerCubicMeterTolerance), + MassConcentrationUnit.MilligramPerDeciliter => (MilligramsPerDeciliterInOneKilogramPerCubicMeter, MilligramsPerDeciliterTolerance), + MassConcentrationUnit.MilligramPerLiter => (MilligramsPerLiterInOneKilogramPerCubicMeter, MilligramsPerLiterTolerance), + MassConcentrationUnit.MilligramPerMicroliter => (MilligramsPerMicroliterInOneKilogramPerCubicMeter, MilligramsPerMicroliterTolerance), + MassConcentrationUnit.MilligramPerMilliliter => (MilligramsPerMilliliterInOneKilogramPerCubicMeter, MilligramsPerMilliliterTolerance), + MassConcentrationUnit.NanogramPerDeciliter => (NanogramsPerDeciliterInOneKilogramPerCubicMeter, NanogramsPerDeciliterTolerance), + MassConcentrationUnit.NanogramPerLiter => (NanogramsPerLiterInOneKilogramPerCubicMeter, NanogramsPerLiterTolerance), + MassConcentrationUnit.NanogramPerMicroliter => (NanogramsPerMicroliterInOneKilogramPerCubicMeter, NanogramsPerMicroliterTolerance), + MassConcentrationUnit.NanogramPerMilliliter => (NanogramsPerMilliliterInOneKilogramPerCubicMeter, NanogramsPerMilliliterTolerance), + MassConcentrationUnit.OuncePerImperialGallon => (OuncesPerImperialGallonInOneKilogramPerCubicMeter, OuncesPerImperialGallonTolerance), + MassConcentrationUnit.OuncePerUSGallon => (OuncesPerUSGallonInOneKilogramPerCubicMeter, OuncesPerUSGallonTolerance), + MassConcentrationUnit.PicogramPerDeciliter => (PicogramsPerDeciliterInOneKilogramPerCubicMeter, PicogramsPerDeciliterTolerance), + MassConcentrationUnit.PicogramPerLiter => (PicogramsPerLiterInOneKilogramPerCubicMeter, PicogramsPerLiterTolerance), + MassConcentrationUnit.PicogramPerMicroliter => (PicogramsPerMicroliterInOneKilogramPerCubicMeter, PicogramsPerMicroliterTolerance), + MassConcentrationUnit.PicogramPerMilliliter => (PicogramsPerMilliliterInOneKilogramPerCubicMeter, PicogramsPerMilliliterTolerance), + MassConcentrationUnit.PoundPerCubicFoot => (PoundsPerCubicFootInOneKilogramPerCubicMeter, PoundsPerCubicFootTolerance), + MassConcentrationUnit.PoundPerCubicInch => (PoundsPerCubicInchInOneKilogramPerCubicMeter, PoundsPerCubicInchTolerance), + MassConcentrationUnit.PoundPerImperialGallon => (PoundsPerImperialGallonInOneKilogramPerCubicMeter, PoundsPerImperialGallonTolerance), + MassConcentrationUnit.PoundPerUSGallon => (PoundsPerUSGallonInOneKilogramPerCubicMeter, PoundsPerUSGallonTolerance), + MassConcentrationUnit.SlugPerCubicFoot => (SlugsPerCubicFootInOneKilogramPerCubicMeter, SlugsPerCubicFootTolerance), + MassConcentrationUnit.TonnePerCubicCentimeter => (TonnesPerCubicCentimeterInOneKilogramPerCubicMeter, TonnesPerCubicCentimeterTolerance), + MassConcentrationUnit.TonnePerCubicMeter => (TonnesPerCubicMeterInOneKilogramPerCubicMeter, TonnesPerCubicMeterTolerance), + MassConcentrationUnit.TonnePerCubicMillimeter => (TonnesPerCubicMillimeterInOneKilogramPerCubicMeter, TonnesPerCubicMillimeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MassConcentrationUnit.CentigramPerDeciliter }, + new object[] { MassConcentrationUnit.CentigramPerLiter }, + new object[] { MassConcentrationUnit.CentigramPerMicroliter }, + new object[] { MassConcentrationUnit.CentigramPerMilliliter }, + new object[] { MassConcentrationUnit.DecigramPerDeciliter }, + new object[] { MassConcentrationUnit.DecigramPerLiter }, + new object[] { MassConcentrationUnit.DecigramPerMicroliter }, + new object[] { MassConcentrationUnit.DecigramPerMilliliter }, + new object[] { MassConcentrationUnit.GramPerCubicCentimeter }, + new object[] { MassConcentrationUnit.GramPerCubicMeter }, + new object[] { MassConcentrationUnit.GramPerCubicMillimeter }, + new object[] { MassConcentrationUnit.GramPerDeciliter }, + new object[] { MassConcentrationUnit.GramPerLiter }, + new object[] { MassConcentrationUnit.GramPerMicroliter }, + new object[] { MassConcentrationUnit.GramPerMilliliter }, + new object[] { MassConcentrationUnit.KilogramPerCubicCentimeter }, + new object[] { MassConcentrationUnit.KilogramPerCubicMeter }, + new object[] { MassConcentrationUnit.KilogramPerCubicMillimeter }, + new object[] { MassConcentrationUnit.KilogramPerLiter }, + new object[] { MassConcentrationUnit.KilopoundPerCubicFoot }, + new object[] { MassConcentrationUnit.KilopoundPerCubicInch }, + new object[] { MassConcentrationUnit.MicrogramPerCubicMeter }, + new object[] { MassConcentrationUnit.MicrogramPerDeciliter }, + new object[] { MassConcentrationUnit.MicrogramPerLiter }, + new object[] { MassConcentrationUnit.MicrogramPerMicroliter }, + new object[] { MassConcentrationUnit.MicrogramPerMilliliter }, + new object[] { MassConcentrationUnit.MilligramPerCubicMeter }, + new object[] { MassConcentrationUnit.MilligramPerDeciliter }, + new object[] { MassConcentrationUnit.MilligramPerLiter }, + new object[] { MassConcentrationUnit.MilligramPerMicroliter }, + new object[] { MassConcentrationUnit.MilligramPerMilliliter }, + new object[] { MassConcentrationUnit.NanogramPerDeciliter }, + new object[] { MassConcentrationUnit.NanogramPerLiter }, + new object[] { MassConcentrationUnit.NanogramPerMicroliter }, + new object[] { MassConcentrationUnit.NanogramPerMilliliter }, + new object[] { MassConcentrationUnit.OuncePerImperialGallon }, + new object[] { MassConcentrationUnit.OuncePerUSGallon }, + new object[] { MassConcentrationUnit.PicogramPerDeciliter }, + new object[] { MassConcentrationUnit.PicogramPerLiter }, + new object[] { MassConcentrationUnit.PicogramPerMicroliter }, + new object[] { MassConcentrationUnit.PicogramPerMilliliter }, + new object[] { MassConcentrationUnit.PoundPerCubicFoot }, + new object[] { MassConcentrationUnit.PoundPerCubicInch }, + new object[] { MassConcentrationUnit.PoundPerImperialGallon }, + new object[] { MassConcentrationUnit.PoundPerUSGallon }, + new object[] { MassConcentrationUnit.SlugPerCubicFoot }, + new object[] { MassConcentrationUnit.TonnePerCubicCentimeter }, + new object[] { MassConcentrationUnit.TonnePerCubicMeter }, + new object[] { MassConcentrationUnit.TonnePerCubicMillimeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -548,213 +659,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MassConcentrationUnit unit) { - var kilogrampercubicmeter = MassConcentration.FromKilogramsPerCubicMeter(1); - - var centigramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.CentigramPerDeciliter); - AssertEx.EqualTolerance(CentigramsPerDeciliterInOneKilogramPerCubicMeter, (double)centigramperdeciliterQuantity.Value, CentigramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerDeciliter, centigramperdeciliterQuantity.Unit); - - var centigramperliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.CentigramPerLiter); - AssertEx.EqualTolerance(CentigramsPerLiterInOneKilogramPerCubicMeter, (double)centigramperliterQuantity.Value, CentigramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerLiter, centigramperliterQuantity.Unit); - - var centigrampermicroliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.CentigramPerMicroliter); - AssertEx.EqualTolerance(CentigramsPerMicroliterInOneKilogramPerCubicMeter, (double)centigrampermicroliterQuantity.Value, CentigramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerMicroliter, centigrampermicroliterQuantity.Unit); - - var centigrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.CentigramPerMilliliter); - AssertEx.EqualTolerance(CentigramsPerMilliliterInOneKilogramPerCubicMeter, (double)centigrampermilliliterQuantity.Value, CentigramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerMilliliter, centigrampermilliliterQuantity.Unit); - - var decigramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.DecigramPerDeciliter); - AssertEx.EqualTolerance(DecigramsPerDeciliterInOneKilogramPerCubicMeter, (double)decigramperdeciliterQuantity.Value, DecigramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerDeciliter, decigramperdeciliterQuantity.Unit); - - var decigramperliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.DecigramPerLiter); - AssertEx.EqualTolerance(DecigramsPerLiterInOneKilogramPerCubicMeter, (double)decigramperliterQuantity.Value, DecigramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerLiter, decigramperliterQuantity.Unit); - - var decigrampermicroliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.DecigramPerMicroliter); - AssertEx.EqualTolerance(DecigramsPerMicroliterInOneKilogramPerCubicMeter, (double)decigrampermicroliterQuantity.Value, DecigramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerMicroliter, decigrampermicroliterQuantity.Unit); - - var decigrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.DecigramPerMilliliter); - AssertEx.EqualTolerance(DecigramsPerMilliliterInOneKilogramPerCubicMeter, (double)decigrampermilliliterQuantity.Value, DecigramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerMilliliter, decigrampermilliliterQuantity.Unit); - - var grampercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.GramPerCubicCentimeter); - AssertEx.EqualTolerance(GramsPerCubicCentimeterInOneKilogramPerCubicMeter, (double)grampercubiccentimeterQuantity.Value, GramsPerCubicCentimeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicCentimeter, grampercubiccentimeterQuantity.Unit); - - var grampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.GramPerCubicMeter); - AssertEx.EqualTolerance(GramsPerCubicMeterInOneKilogramPerCubicMeter, (double)grampercubicmeterQuantity.Value, GramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicMeter, grampercubicmeterQuantity.Unit); - - var grampercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.GramPerCubicMillimeter); - AssertEx.EqualTolerance(GramsPerCubicMillimeterInOneKilogramPerCubicMeter, (double)grampercubicmillimeterQuantity.Value, GramsPerCubicMillimeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicMillimeter, grampercubicmillimeterQuantity.Unit); - - var gramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.GramPerDeciliter); - AssertEx.EqualTolerance(GramsPerDeciliterInOneKilogramPerCubicMeter, (double)gramperdeciliterQuantity.Value, GramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerDeciliter, gramperdeciliterQuantity.Unit); - - var gramperliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.GramPerLiter); - AssertEx.EqualTolerance(GramsPerLiterInOneKilogramPerCubicMeter, (double)gramperliterQuantity.Value, GramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerLiter, gramperliterQuantity.Unit); - - var grampermicroliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.GramPerMicroliter); - AssertEx.EqualTolerance(GramsPerMicroliterInOneKilogramPerCubicMeter, (double)grampermicroliterQuantity.Value, GramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerMicroliter, grampermicroliterQuantity.Unit); - - var grampermilliliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.GramPerMilliliter); - AssertEx.EqualTolerance(GramsPerMilliliterInOneKilogramPerCubicMeter, (double)grampermilliliterQuantity.Value, GramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerMilliliter, grampermilliliterQuantity.Unit); - - var kilogrampercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.KilogramPerCubicCentimeter); - AssertEx.EqualTolerance(KilogramsPerCubicCentimeterInOneKilogramPerCubicMeter, (double)kilogrampercubiccentimeterQuantity.Value, KilogramsPerCubicCentimeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicCentimeter, kilogrampercubiccentimeterQuantity.Unit); - - var kilogrampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter); - AssertEx.EqualTolerance(KilogramsPerCubicMeterInOneKilogramPerCubicMeter, (double)kilogrampercubicmeterQuantity.Value, KilogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicMeter, kilogrampercubicmeterQuantity.Unit); - - var kilogrampercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.KilogramPerCubicMillimeter); - AssertEx.EqualTolerance(KilogramsPerCubicMillimeterInOneKilogramPerCubicMeter, (double)kilogrampercubicmillimeterQuantity.Value, KilogramsPerCubicMillimeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicMillimeter, kilogrampercubicmillimeterQuantity.Unit); - - var kilogramperliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.KilogramPerLiter); - AssertEx.EqualTolerance(KilogramsPerLiterInOneKilogramPerCubicMeter, (double)kilogramperliterQuantity.Value, KilogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerLiter, kilogramperliterQuantity.Unit); - - var kilopoundpercubicfootQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.KilopoundPerCubicFoot); - AssertEx.EqualTolerance(KilopoundsPerCubicFootInOneKilogramPerCubicMeter, (double)kilopoundpercubicfootQuantity.Value, KilopoundsPerCubicFootTolerance); - Assert.Equal(MassConcentrationUnit.KilopoundPerCubicFoot, kilopoundpercubicfootQuantity.Unit); - - var kilopoundpercubicinchQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.KilopoundPerCubicInch); - AssertEx.EqualTolerance(KilopoundsPerCubicInchInOneKilogramPerCubicMeter, (double)kilopoundpercubicinchQuantity.Value, KilopoundsPerCubicInchTolerance); - Assert.Equal(MassConcentrationUnit.KilopoundPerCubicInch, kilopoundpercubicinchQuantity.Unit); - - var microgrampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MicrogramPerCubicMeter); - AssertEx.EqualTolerance(MicrogramsPerCubicMeterInOneKilogramPerCubicMeter, (double)microgrampercubicmeterQuantity.Value, MicrogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerCubicMeter, microgrampercubicmeterQuantity.Unit); - - var microgramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MicrogramPerDeciliter); - AssertEx.EqualTolerance(MicrogramsPerDeciliterInOneKilogramPerCubicMeter, (double)microgramperdeciliterQuantity.Value, MicrogramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerDeciliter, microgramperdeciliterQuantity.Unit); + var inBaseUnits = MassConcentration.From(1.0, MassConcentration.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var microgramperliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MicrogramPerLiter); - AssertEx.EqualTolerance(MicrogramsPerLiterInOneKilogramPerCubicMeter, (double)microgramperliterQuantity.Value, MicrogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerLiter, microgramperliterQuantity.Unit); - - var microgrampermicroliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MicrogramPerMicroliter); - AssertEx.EqualTolerance(MicrogramsPerMicroliterInOneKilogramPerCubicMeter, (double)microgrampermicroliterQuantity.Value, MicrogramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerMicroliter, microgrampermicroliterQuantity.Unit); - - var microgrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MicrogramPerMilliliter); - AssertEx.EqualTolerance(MicrogramsPerMilliliterInOneKilogramPerCubicMeter, (double)microgrampermilliliterQuantity.Value, MicrogramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerMilliliter, microgrampermilliliterQuantity.Unit); - - var milligrampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MilligramPerCubicMeter); - AssertEx.EqualTolerance(MilligramsPerCubicMeterInOneKilogramPerCubicMeter, (double)milligrampercubicmeterQuantity.Value, MilligramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerCubicMeter, milligrampercubicmeterQuantity.Unit); - - var milligramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MilligramPerDeciliter); - AssertEx.EqualTolerance(MilligramsPerDeciliterInOneKilogramPerCubicMeter, (double)milligramperdeciliterQuantity.Value, MilligramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerDeciliter, milligramperdeciliterQuantity.Unit); - - var milligramperliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MilligramPerLiter); - AssertEx.EqualTolerance(MilligramsPerLiterInOneKilogramPerCubicMeter, (double)milligramperliterQuantity.Value, MilligramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerLiter, milligramperliterQuantity.Unit); - - var milligrampermicroliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MilligramPerMicroliter); - AssertEx.EqualTolerance(MilligramsPerMicroliterInOneKilogramPerCubicMeter, (double)milligrampermicroliterQuantity.Value, MilligramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerMicroliter, milligrampermicroliterQuantity.Unit); - - var milligrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.MilligramPerMilliliter); - AssertEx.EqualTolerance(MilligramsPerMilliliterInOneKilogramPerCubicMeter, (double)milligrampermilliliterQuantity.Value, MilligramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerMilliliter, milligrampermilliliterQuantity.Unit); - - var nanogramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.NanogramPerDeciliter); - AssertEx.EqualTolerance(NanogramsPerDeciliterInOneKilogramPerCubicMeter, (double)nanogramperdeciliterQuantity.Value, NanogramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerDeciliter, nanogramperdeciliterQuantity.Unit); - - var nanogramperliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.NanogramPerLiter); - AssertEx.EqualTolerance(NanogramsPerLiterInOneKilogramPerCubicMeter, (double)nanogramperliterQuantity.Value, NanogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerLiter, nanogramperliterQuantity.Unit); - - var nanogrampermicroliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.NanogramPerMicroliter); - AssertEx.EqualTolerance(NanogramsPerMicroliterInOneKilogramPerCubicMeter, (double)nanogrampermicroliterQuantity.Value, NanogramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerMicroliter, nanogrampermicroliterQuantity.Unit); - - var nanogrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.NanogramPerMilliliter); - AssertEx.EqualTolerance(NanogramsPerMilliliterInOneKilogramPerCubicMeter, (double)nanogrampermilliliterQuantity.Value, NanogramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerMilliliter, nanogrampermilliliterQuantity.Unit); - - var ounceperimperialgallonQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.OuncePerImperialGallon); - AssertEx.EqualTolerance(OuncesPerImperialGallonInOneKilogramPerCubicMeter, (double)ounceperimperialgallonQuantity.Value, OuncesPerImperialGallonTolerance); - Assert.Equal(MassConcentrationUnit.OuncePerImperialGallon, ounceperimperialgallonQuantity.Unit); - - var ounceperusgallonQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.OuncePerUSGallon); - AssertEx.EqualTolerance(OuncesPerUSGallonInOneKilogramPerCubicMeter, (double)ounceperusgallonQuantity.Value, OuncesPerUSGallonTolerance); - Assert.Equal(MassConcentrationUnit.OuncePerUSGallon, ounceperusgallonQuantity.Unit); - - var picogramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.PicogramPerDeciliter); - AssertEx.EqualTolerance(PicogramsPerDeciliterInOneKilogramPerCubicMeter, (double)picogramperdeciliterQuantity.Value, PicogramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerDeciliter, picogramperdeciliterQuantity.Unit); - - var picogramperliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.PicogramPerLiter); - AssertEx.EqualTolerance(PicogramsPerLiterInOneKilogramPerCubicMeter, (double)picogramperliterQuantity.Value, PicogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerLiter, picogramperliterQuantity.Unit); - - var picogrampermicroliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.PicogramPerMicroliter); - AssertEx.EqualTolerance(PicogramsPerMicroliterInOneKilogramPerCubicMeter, (double)picogrampermicroliterQuantity.Value, PicogramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerMicroliter, picogrampermicroliterQuantity.Unit); - - var picogrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.PicogramPerMilliliter); - AssertEx.EqualTolerance(PicogramsPerMilliliterInOneKilogramPerCubicMeter, (double)picogrampermilliliterQuantity.Value, PicogramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerMilliliter, picogrampermilliliterQuantity.Unit); - - var poundpercubicfootQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.PoundPerCubicFoot); - AssertEx.EqualTolerance(PoundsPerCubicFootInOneKilogramPerCubicMeter, (double)poundpercubicfootQuantity.Value, PoundsPerCubicFootTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerCubicFoot, poundpercubicfootQuantity.Unit); - - var poundpercubicinchQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.PoundPerCubicInch); - AssertEx.EqualTolerance(PoundsPerCubicInchInOneKilogramPerCubicMeter, (double)poundpercubicinchQuantity.Value, PoundsPerCubicInchTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerCubicInch, poundpercubicinchQuantity.Unit); - - var poundperimperialgallonQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.PoundPerImperialGallon); - AssertEx.EqualTolerance(PoundsPerImperialGallonInOneKilogramPerCubicMeter, (double)poundperimperialgallonQuantity.Value, PoundsPerImperialGallonTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerImperialGallon, poundperimperialgallonQuantity.Unit); - - var poundperusgallonQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.PoundPerUSGallon); - AssertEx.EqualTolerance(PoundsPerUSGallonInOneKilogramPerCubicMeter, (double)poundperusgallonQuantity.Value, PoundsPerUSGallonTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerUSGallon, poundperusgallonQuantity.Unit); - - var slugpercubicfootQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.SlugPerCubicFoot); - AssertEx.EqualTolerance(SlugsPerCubicFootInOneKilogramPerCubicMeter, (double)slugpercubicfootQuantity.Value, SlugsPerCubicFootTolerance); - Assert.Equal(MassConcentrationUnit.SlugPerCubicFoot, slugpercubicfootQuantity.Unit); - - var tonnepercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.TonnePerCubicCentimeter); - AssertEx.EqualTolerance(TonnesPerCubicCentimeterInOneKilogramPerCubicMeter, (double)tonnepercubiccentimeterQuantity.Value, TonnesPerCubicCentimeterTolerance); - Assert.Equal(MassConcentrationUnit.TonnePerCubicCentimeter, tonnepercubiccentimeterQuantity.Unit); - - var tonnepercubicmeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.TonnePerCubicMeter); - AssertEx.EqualTolerance(TonnesPerCubicMeterInOneKilogramPerCubicMeter, (double)tonnepercubicmeterQuantity.Value, TonnesPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.TonnePerCubicMeter, tonnepercubicmeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonnepercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(MassConcentrationUnit.TonnePerCubicMillimeter); - AssertEx.EqualTolerance(TonnesPerCubicMillimeterInOneKilogramPerCubicMeter, (double)tonnepercubicmillimeterQuantity.Value, TonnesPerCubicMillimeterTolerance); - Assert.Equal(MassConcentrationUnit.TonnePerCubicMillimeter, tonnepercubicmillimeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MassConcentrationUnit unit) + { + var quantity = MassConcentration.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassConcentrationUnit unit) { - var quantityInBaseUnit = MassConcentration.FromKilogramsPerCubicMeter(1).ToBaseUnit(); - Assert.Equal(MassConcentration.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MassConcentration.Units.FirstOrDefault(u => u != MassConcentration.BaseUnit && u != MassConcentrationUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MassConcentrationUnit.Undefined) + fromUnit = MassConcentration.BaseUnit; + + var quantity = MassConcentration.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs index 306ad7e5e6..8ca2653751 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -107,6 +108,84 @@ public abstract partial class MassFlowTestsBase : QuantityTestsBase protected virtual double TonnesPerHourTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassFlowUnit unit) + { + return unit switch + { + MassFlowUnit.CentigramPerDay => (CentigramsPerDayInOneGramPerSecond, CentigramsPerDayTolerance), + MassFlowUnit.CentigramPerSecond => (CentigramsPerSecondInOneGramPerSecond, CentigramsPerSecondTolerance), + MassFlowUnit.DecagramPerDay => (DecagramsPerDayInOneGramPerSecond, DecagramsPerDayTolerance), + MassFlowUnit.DecagramPerSecond => (DecagramsPerSecondInOneGramPerSecond, DecagramsPerSecondTolerance), + MassFlowUnit.DecigramPerDay => (DecigramsPerDayInOneGramPerSecond, DecigramsPerDayTolerance), + MassFlowUnit.DecigramPerSecond => (DecigramsPerSecondInOneGramPerSecond, DecigramsPerSecondTolerance), + MassFlowUnit.GramPerDay => (GramsPerDayInOneGramPerSecond, GramsPerDayTolerance), + MassFlowUnit.GramPerHour => (GramsPerHourInOneGramPerSecond, GramsPerHourTolerance), + MassFlowUnit.GramPerSecond => (GramsPerSecondInOneGramPerSecond, GramsPerSecondTolerance), + MassFlowUnit.HectogramPerDay => (HectogramsPerDayInOneGramPerSecond, HectogramsPerDayTolerance), + MassFlowUnit.HectogramPerSecond => (HectogramsPerSecondInOneGramPerSecond, HectogramsPerSecondTolerance), + MassFlowUnit.KilogramPerDay => (KilogramsPerDayInOneGramPerSecond, KilogramsPerDayTolerance), + MassFlowUnit.KilogramPerHour => (KilogramsPerHourInOneGramPerSecond, KilogramsPerHourTolerance), + MassFlowUnit.KilogramPerMinute => (KilogramsPerMinuteInOneGramPerSecond, KilogramsPerMinuteTolerance), + MassFlowUnit.KilogramPerSecond => (KilogramsPerSecondInOneGramPerSecond, KilogramsPerSecondTolerance), + MassFlowUnit.MegagramPerDay => (MegagramsPerDayInOneGramPerSecond, MegagramsPerDayTolerance), + MassFlowUnit.MegapoundPerDay => (MegapoundsPerDayInOneGramPerSecond, MegapoundsPerDayTolerance), + MassFlowUnit.MegapoundPerHour => (MegapoundsPerHourInOneGramPerSecond, MegapoundsPerHourTolerance), + MassFlowUnit.MegapoundPerMinute => (MegapoundsPerMinuteInOneGramPerSecond, MegapoundsPerMinuteTolerance), + MassFlowUnit.MegapoundPerSecond => (MegapoundsPerSecondInOneGramPerSecond, MegapoundsPerSecondTolerance), + MassFlowUnit.MicrogramPerDay => (MicrogramsPerDayInOneGramPerSecond, MicrogramsPerDayTolerance), + MassFlowUnit.MicrogramPerSecond => (MicrogramsPerSecondInOneGramPerSecond, MicrogramsPerSecondTolerance), + MassFlowUnit.MilligramPerDay => (MilligramsPerDayInOneGramPerSecond, MilligramsPerDayTolerance), + MassFlowUnit.MilligramPerSecond => (MilligramsPerSecondInOneGramPerSecond, MilligramsPerSecondTolerance), + MassFlowUnit.NanogramPerDay => (NanogramsPerDayInOneGramPerSecond, NanogramsPerDayTolerance), + MassFlowUnit.NanogramPerSecond => (NanogramsPerSecondInOneGramPerSecond, NanogramsPerSecondTolerance), + MassFlowUnit.PoundPerDay => (PoundsPerDayInOneGramPerSecond, PoundsPerDayTolerance), + MassFlowUnit.PoundPerHour => (PoundsPerHourInOneGramPerSecond, PoundsPerHourTolerance), + MassFlowUnit.PoundPerMinute => (PoundsPerMinuteInOneGramPerSecond, PoundsPerMinuteTolerance), + MassFlowUnit.PoundPerSecond => (PoundsPerSecondInOneGramPerSecond, PoundsPerSecondTolerance), + MassFlowUnit.ShortTonPerHour => (ShortTonsPerHourInOneGramPerSecond, ShortTonsPerHourTolerance), + MassFlowUnit.TonnePerDay => (TonnesPerDayInOneGramPerSecond, TonnesPerDayTolerance), + MassFlowUnit.TonnePerHour => (TonnesPerHourInOneGramPerSecond, TonnesPerHourTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MassFlowUnit.CentigramPerDay }, + new object[] { MassFlowUnit.CentigramPerSecond }, + new object[] { MassFlowUnit.DecagramPerDay }, + new object[] { MassFlowUnit.DecagramPerSecond }, + new object[] { MassFlowUnit.DecigramPerDay }, + new object[] { MassFlowUnit.DecigramPerSecond }, + new object[] { MassFlowUnit.GramPerDay }, + new object[] { MassFlowUnit.GramPerHour }, + new object[] { MassFlowUnit.GramPerSecond }, + new object[] { MassFlowUnit.HectogramPerDay }, + new object[] { MassFlowUnit.HectogramPerSecond }, + new object[] { MassFlowUnit.KilogramPerDay }, + new object[] { MassFlowUnit.KilogramPerHour }, + new object[] { MassFlowUnit.KilogramPerMinute }, + new object[] { MassFlowUnit.KilogramPerSecond }, + new object[] { MassFlowUnit.MegagramPerDay }, + new object[] { MassFlowUnit.MegapoundPerDay }, + new object[] { MassFlowUnit.MegapoundPerHour }, + new object[] { MassFlowUnit.MegapoundPerMinute }, + new object[] { MassFlowUnit.MegapoundPerSecond }, + new object[] { MassFlowUnit.MicrogramPerDay }, + new object[] { MassFlowUnit.MicrogramPerSecond }, + new object[] { MassFlowUnit.MilligramPerDay }, + new object[] { MassFlowUnit.MilligramPerSecond }, + new object[] { MassFlowUnit.NanogramPerDay }, + new object[] { MassFlowUnit.NanogramPerSecond }, + new object[] { MassFlowUnit.PoundPerDay }, + new object[] { MassFlowUnit.PoundPerHour }, + new object[] { MassFlowUnit.PoundPerMinute }, + new object[] { MassFlowUnit.PoundPerSecond }, + new object[] { MassFlowUnit.ShortTonPerHour }, + new object[] { MassFlowUnit.TonnePerDay }, + new object[] { MassFlowUnit.TonnePerHour }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -420,149 +499,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MassFlowUnit unit) { - var grampersecond = MassFlow.FromGramsPerSecond(1); - - var centigramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.CentigramPerDay); - AssertEx.EqualTolerance(CentigramsPerDayInOneGramPerSecond, (double)centigramperdayQuantity.Value, CentigramsPerDayTolerance); - Assert.Equal(MassFlowUnit.CentigramPerDay, centigramperdayQuantity.Unit); - - var centigrampersecondQuantity = grampersecond.ToUnit(MassFlowUnit.CentigramPerSecond); - AssertEx.EqualTolerance(CentigramsPerSecondInOneGramPerSecond, (double)centigrampersecondQuantity.Value, CentigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.CentigramPerSecond, centigrampersecondQuantity.Unit); - - var decagramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.DecagramPerDay); - AssertEx.EqualTolerance(DecagramsPerDayInOneGramPerSecond, (double)decagramperdayQuantity.Value, DecagramsPerDayTolerance); - Assert.Equal(MassFlowUnit.DecagramPerDay, decagramperdayQuantity.Unit); - - var decagrampersecondQuantity = grampersecond.ToUnit(MassFlowUnit.DecagramPerSecond); - AssertEx.EqualTolerance(DecagramsPerSecondInOneGramPerSecond, (double)decagrampersecondQuantity.Value, DecagramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecagramPerSecond, decagrampersecondQuantity.Unit); - - var decigramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.DecigramPerDay); - AssertEx.EqualTolerance(DecigramsPerDayInOneGramPerSecond, (double)decigramperdayQuantity.Value, DecigramsPerDayTolerance); - Assert.Equal(MassFlowUnit.DecigramPerDay, decigramperdayQuantity.Unit); - - var decigrampersecondQuantity = grampersecond.ToUnit(MassFlowUnit.DecigramPerSecond); - AssertEx.EqualTolerance(DecigramsPerSecondInOneGramPerSecond, (double)decigrampersecondQuantity.Value, DecigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecigramPerSecond, decigrampersecondQuantity.Unit); - - var gramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.GramPerDay); - AssertEx.EqualTolerance(GramsPerDayInOneGramPerSecond, (double)gramperdayQuantity.Value, GramsPerDayTolerance); - Assert.Equal(MassFlowUnit.GramPerDay, gramperdayQuantity.Unit); - - var gramperhourQuantity = grampersecond.ToUnit(MassFlowUnit.GramPerHour); - AssertEx.EqualTolerance(GramsPerHourInOneGramPerSecond, (double)gramperhourQuantity.Value, GramsPerHourTolerance); - Assert.Equal(MassFlowUnit.GramPerHour, gramperhourQuantity.Unit); - - var grampersecondQuantity = grampersecond.ToUnit(MassFlowUnit.GramPerSecond); - AssertEx.EqualTolerance(GramsPerSecondInOneGramPerSecond, (double)grampersecondQuantity.Value, GramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.GramPerSecond, grampersecondQuantity.Unit); - - var hectogramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.HectogramPerDay); - AssertEx.EqualTolerance(HectogramsPerDayInOneGramPerSecond, (double)hectogramperdayQuantity.Value, HectogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.HectogramPerDay, hectogramperdayQuantity.Unit); - - var hectogrampersecondQuantity = grampersecond.ToUnit(MassFlowUnit.HectogramPerSecond); - AssertEx.EqualTolerance(HectogramsPerSecondInOneGramPerSecond, (double)hectogrampersecondQuantity.Value, HectogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.HectogramPerSecond, hectogrampersecondQuantity.Unit); - - var kilogramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.KilogramPerDay); - AssertEx.EqualTolerance(KilogramsPerDayInOneGramPerSecond, (double)kilogramperdayQuantity.Value, KilogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.KilogramPerDay, kilogramperdayQuantity.Unit); - - var kilogramperhourQuantity = grampersecond.ToUnit(MassFlowUnit.KilogramPerHour); - AssertEx.EqualTolerance(KilogramsPerHourInOneGramPerSecond, (double)kilogramperhourQuantity.Value, KilogramsPerHourTolerance); - Assert.Equal(MassFlowUnit.KilogramPerHour, kilogramperhourQuantity.Unit); - - var kilogramperminuteQuantity = grampersecond.ToUnit(MassFlowUnit.KilogramPerMinute); - AssertEx.EqualTolerance(KilogramsPerMinuteInOneGramPerSecond, (double)kilogramperminuteQuantity.Value, KilogramsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.KilogramPerMinute, kilogramperminuteQuantity.Unit); - - var kilogrampersecondQuantity = grampersecond.ToUnit(MassFlowUnit.KilogramPerSecond); - AssertEx.EqualTolerance(KilogramsPerSecondInOneGramPerSecond, (double)kilogrampersecondQuantity.Value, KilogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.KilogramPerSecond, kilogrampersecondQuantity.Unit); + var inBaseUnits = MassFlow.From(1.0, MassFlow.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megagramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.MegagramPerDay); - AssertEx.EqualTolerance(MegagramsPerDayInOneGramPerSecond, (double)megagramperdayQuantity.Value, MegagramsPerDayTolerance); - Assert.Equal(MassFlowUnit.MegagramPerDay, megagramperdayQuantity.Unit); - - var megapoundperdayQuantity = grampersecond.ToUnit(MassFlowUnit.MegapoundPerDay); - AssertEx.EqualTolerance(MegapoundsPerDayInOneGramPerSecond, (double)megapoundperdayQuantity.Value, MegapoundsPerDayTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerDay, megapoundperdayQuantity.Unit); - - var megapoundperhourQuantity = grampersecond.ToUnit(MassFlowUnit.MegapoundPerHour); - AssertEx.EqualTolerance(MegapoundsPerHourInOneGramPerSecond, (double)megapoundperhourQuantity.Value, MegapoundsPerHourTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerHour, megapoundperhourQuantity.Unit); - - var megapoundperminuteQuantity = grampersecond.ToUnit(MassFlowUnit.MegapoundPerMinute); - AssertEx.EqualTolerance(MegapoundsPerMinuteInOneGramPerSecond, (double)megapoundperminuteQuantity.Value, MegapoundsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerMinute, megapoundperminuteQuantity.Unit); - - var megapoundpersecondQuantity = grampersecond.ToUnit(MassFlowUnit.MegapoundPerSecond); - AssertEx.EqualTolerance(MegapoundsPerSecondInOneGramPerSecond, (double)megapoundpersecondQuantity.Value, MegapoundsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerSecond, megapoundpersecondQuantity.Unit); - - var microgramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.MicrogramPerDay); - AssertEx.EqualTolerance(MicrogramsPerDayInOneGramPerSecond, (double)microgramperdayQuantity.Value, MicrogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.MicrogramPerDay, microgramperdayQuantity.Unit); - - var microgrampersecondQuantity = grampersecond.ToUnit(MassFlowUnit.MicrogramPerSecond); - AssertEx.EqualTolerance(MicrogramsPerSecondInOneGramPerSecond, (double)microgrampersecondQuantity.Value, MicrogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MicrogramPerSecond, microgrampersecondQuantity.Unit); - - var milligramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.MilligramPerDay); - AssertEx.EqualTolerance(MilligramsPerDayInOneGramPerSecond, (double)milligramperdayQuantity.Value, MilligramsPerDayTolerance); - Assert.Equal(MassFlowUnit.MilligramPerDay, milligramperdayQuantity.Unit); - - var milligrampersecondQuantity = grampersecond.ToUnit(MassFlowUnit.MilligramPerSecond); - AssertEx.EqualTolerance(MilligramsPerSecondInOneGramPerSecond, (double)milligrampersecondQuantity.Value, MilligramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MilligramPerSecond, milligrampersecondQuantity.Unit); - - var nanogramperdayQuantity = grampersecond.ToUnit(MassFlowUnit.NanogramPerDay); - AssertEx.EqualTolerance(NanogramsPerDayInOneGramPerSecond, (double)nanogramperdayQuantity.Value, NanogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.NanogramPerDay, nanogramperdayQuantity.Unit); - - var nanogrampersecondQuantity = grampersecond.ToUnit(MassFlowUnit.NanogramPerSecond); - AssertEx.EqualTolerance(NanogramsPerSecondInOneGramPerSecond, (double)nanogrampersecondQuantity.Value, NanogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.NanogramPerSecond, nanogrampersecondQuantity.Unit); - - var poundperdayQuantity = grampersecond.ToUnit(MassFlowUnit.PoundPerDay); - AssertEx.EqualTolerance(PoundsPerDayInOneGramPerSecond, (double)poundperdayQuantity.Value, PoundsPerDayTolerance); - Assert.Equal(MassFlowUnit.PoundPerDay, poundperdayQuantity.Unit); - - var poundperhourQuantity = grampersecond.ToUnit(MassFlowUnit.PoundPerHour); - AssertEx.EqualTolerance(PoundsPerHourInOneGramPerSecond, (double)poundperhourQuantity.Value, PoundsPerHourTolerance); - Assert.Equal(MassFlowUnit.PoundPerHour, poundperhourQuantity.Unit); - - var poundperminuteQuantity = grampersecond.ToUnit(MassFlowUnit.PoundPerMinute); - AssertEx.EqualTolerance(PoundsPerMinuteInOneGramPerSecond, (double)poundperminuteQuantity.Value, PoundsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.PoundPerMinute, poundperminuteQuantity.Unit); - - var poundpersecondQuantity = grampersecond.ToUnit(MassFlowUnit.PoundPerSecond); - AssertEx.EqualTolerance(PoundsPerSecondInOneGramPerSecond, (double)poundpersecondQuantity.Value, PoundsPerSecondTolerance); - Assert.Equal(MassFlowUnit.PoundPerSecond, poundpersecondQuantity.Unit); - - var shorttonperhourQuantity = grampersecond.ToUnit(MassFlowUnit.ShortTonPerHour); - AssertEx.EqualTolerance(ShortTonsPerHourInOneGramPerSecond, (double)shorttonperhourQuantity.Value, ShortTonsPerHourTolerance); - Assert.Equal(MassFlowUnit.ShortTonPerHour, shorttonperhourQuantity.Unit); - - var tonneperdayQuantity = grampersecond.ToUnit(MassFlowUnit.TonnePerDay); - AssertEx.EqualTolerance(TonnesPerDayInOneGramPerSecond, (double)tonneperdayQuantity.Value, TonnesPerDayTolerance); - Assert.Equal(MassFlowUnit.TonnePerDay, tonneperdayQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonneperhourQuantity = grampersecond.ToUnit(MassFlowUnit.TonnePerHour); - AssertEx.EqualTolerance(TonnesPerHourInOneGramPerSecond, (double)tonneperhourQuantity.Value, TonnesPerHourTolerance); - Assert.Equal(MassFlowUnit.TonnePerHour, tonneperhourQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MassFlowUnit unit) + { + var quantity = MassFlow.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFlowUnit unit) { - var quantityInBaseUnit = MassFlow.FromGramsPerSecond(1).ToBaseUnit(); - Assert.Equal(MassFlow.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MassFlow.Units.FirstOrDefault(u => u != MassFlow.BaseUnit && u != MassFlowUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MassFlowUnit.Undefined) + fromUnit = MassFlow.BaseUnit; + + var quantity = MassFlow.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs index 854af922ff..e4ee54db7d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -65,6 +66,42 @@ public abstract partial class MassFluxTestsBase : QuantityTestsBase protected virtual double KilogramsPerSecondPerSquareMillimeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassFluxUnit unit) + { + return unit switch + { + MassFluxUnit.GramPerHourPerSquareCentimeter => (GramsPerHourPerSquareCentimeterInOneKilogramPerSecondPerSquareMeter, GramsPerHourPerSquareCentimeterTolerance), + MassFluxUnit.GramPerHourPerSquareMeter => (GramsPerHourPerSquareMeterInOneKilogramPerSecondPerSquareMeter, GramsPerHourPerSquareMeterTolerance), + MassFluxUnit.GramPerHourPerSquareMillimeter => (GramsPerHourPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter, GramsPerHourPerSquareMillimeterTolerance), + MassFluxUnit.GramPerSecondPerSquareCentimeter => (GramsPerSecondPerSquareCentimeterInOneKilogramPerSecondPerSquareMeter, GramsPerSecondPerSquareCentimeterTolerance), + MassFluxUnit.GramPerSecondPerSquareMeter => (GramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, GramsPerSecondPerSquareMeterTolerance), + MassFluxUnit.GramPerSecondPerSquareMillimeter => (GramsPerSecondPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter, GramsPerSecondPerSquareMillimeterTolerance), + MassFluxUnit.KilogramPerHourPerSquareCentimeter => (KilogramsPerHourPerSquareCentimeterInOneKilogramPerSecondPerSquareMeter, KilogramsPerHourPerSquareCentimeterTolerance), + MassFluxUnit.KilogramPerHourPerSquareMeter => (KilogramsPerHourPerSquareMeterInOneKilogramPerSecondPerSquareMeter, KilogramsPerHourPerSquareMeterTolerance), + MassFluxUnit.KilogramPerHourPerSquareMillimeter => (KilogramsPerHourPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter, KilogramsPerHourPerSquareMillimeterTolerance), + MassFluxUnit.KilogramPerSecondPerSquareCentimeter => (KilogramsPerSecondPerSquareCentimeterInOneKilogramPerSecondPerSquareMeter, KilogramsPerSecondPerSquareCentimeterTolerance), + MassFluxUnit.KilogramPerSecondPerSquareMeter => (KilogramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance), + MassFluxUnit.KilogramPerSecondPerSquareMillimeter => (KilogramsPerSecondPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMillimeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MassFluxUnit.GramPerHourPerSquareCentimeter }, + new object[] { MassFluxUnit.GramPerHourPerSquareMeter }, + new object[] { MassFluxUnit.GramPerHourPerSquareMillimeter }, + new object[] { MassFluxUnit.GramPerSecondPerSquareCentimeter }, + new object[] { MassFluxUnit.GramPerSecondPerSquareMeter }, + new object[] { MassFluxUnit.GramPerSecondPerSquareMillimeter }, + new object[] { MassFluxUnit.KilogramPerHourPerSquareCentimeter }, + new object[] { MassFluxUnit.KilogramPerHourPerSquareMeter }, + new object[] { MassFluxUnit.KilogramPerHourPerSquareMillimeter }, + new object[] { MassFluxUnit.KilogramPerSecondPerSquareCentimeter }, + new object[] { MassFluxUnit.KilogramPerSecondPerSquareMeter }, + new object[] { MassFluxUnit.KilogramPerSecondPerSquareMillimeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -252,65 +289,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MassFluxUnit unit) { - var kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - - var gramperhourpersquarecentimeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.GramPerHourPerSquareCentimeter); - AssertEx.EqualTolerance(GramsPerHourPerSquareCentimeterInOneKilogramPerSecondPerSquareMeter, (double)gramperhourpersquarecentimeterQuantity.Value, GramsPerHourPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerHourPerSquareCentimeter, gramperhourpersquarecentimeterQuantity.Unit); - - var gramperhourpersquaremeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.GramPerHourPerSquareMeter); - AssertEx.EqualTolerance(GramsPerHourPerSquareMeterInOneKilogramPerSecondPerSquareMeter, (double)gramperhourpersquaremeterQuantity.Value, GramsPerHourPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.GramPerHourPerSquareMeter, gramperhourpersquaremeterQuantity.Unit); - - var gramperhourpersquaremillimeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.GramPerHourPerSquareMillimeter); - AssertEx.EqualTolerance(GramsPerHourPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter, (double)gramperhourpersquaremillimeterQuantity.Value, GramsPerHourPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerHourPerSquareMillimeter, gramperhourpersquaremillimeterQuantity.Unit); - - var grampersecondpersquarecentimeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.GramPerSecondPerSquareCentimeter); - AssertEx.EqualTolerance(GramsPerSecondPerSquareCentimeterInOneKilogramPerSecondPerSquareMeter, (double)grampersecondpersquarecentimeterQuantity.Value, GramsPerSecondPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareCentimeter, grampersecondpersquarecentimeterQuantity.Unit); - - var grampersecondpersquaremeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.GramPerSecondPerSquareMeter); - AssertEx.EqualTolerance(GramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, (double)grampersecondpersquaremeterQuantity.Value, GramsPerSecondPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareMeter, grampersecondpersquaremeterQuantity.Unit); - - var grampersecondpersquaremillimeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.GramPerSecondPerSquareMillimeter); - AssertEx.EqualTolerance(GramsPerSecondPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter, (double)grampersecondpersquaremillimeterQuantity.Value, GramsPerSecondPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareMillimeter, grampersecondpersquaremillimeterQuantity.Unit); + var inBaseUnits = MassFlux.From(1.0, MassFlux.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilogramperhourpersquarecentimeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.KilogramPerHourPerSquareCentimeter); - AssertEx.EqualTolerance(KilogramsPerHourPerSquareCentimeterInOneKilogramPerSecondPerSquareMeter, (double)kilogramperhourpersquarecentimeterQuantity.Value, KilogramsPerHourPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareCentimeter, kilogramperhourpersquarecentimeterQuantity.Unit); - - var kilogramperhourpersquaremeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.KilogramPerHourPerSquareMeter); - AssertEx.EqualTolerance(KilogramsPerHourPerSquareMeterInOneKilogramPerSecondPerSquareMeter, (double)kilogramperhourpersquaremeterQuantity.Value, KilogramsPerHourPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareMeter, kilogramperhourpersquaremeterQuantity.Unit); - - var kilogramperhourpersquaremillimeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.KilogramPerHourPerSquareMillimeter); - AssertEx.EqualTolerance(KilogramsPerHourPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter, (double)kilogramperhourpersquaremillimeterQuantity.Value, KilogramsPerHourPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareMillimeter, kilogramperhourpersquaremillimeterQuantity.Unit); - - var kilogrampersecondpersquarecentimeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareCentimeter); - AssertEx.EqualTolerance(KilogramsPerSecondPerSquareCentimeterInOneKilogramPerSecondPerSquareMeter, (double)kilogrampersecondpersquarecentimeterQuantity.Value, KilogramsPerSecondPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, kilogrampersecondpersquarecentimeterQuantity.Unit); - - var kilogrampersecondpersquaremeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter); - AssertEx.EqualTolerance(KilogramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, (double)kilogrampersecondpersquaremeterQuantity.Value, KilogramsPerSecondPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMeter, kilogrampersecondpersquaremeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var kilogrampersecondpersquaremillimeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMillimeter); - AssertEx.EqualTolerance(KilogramsPerSecondPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter, (double)kilogrampersecondpersquaremillimeterQuantity.Value, KilogramsPerSecondPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, kilogrampersecondpersquaremillimeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MassFluxUnit unit) + { + var quantity = MassFlux.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFluxUnit unit) { - var quantityInBaseUnit = MassFlux.FromKilogramsPerSecondPerSquareMeter(1).ToBaseUnit(); - Assert.Equal(MassFlux.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MassFlux.Units.FirstOrDefault(u => u != MassFlux.BaseUnit && u != MassFluxUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MassFluxUnit.Undefined) + fromUnit = MassFlux.BaseUnit; + + var quantity = MassFlux.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs index 7644821a54..2e1f094d53 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -89,6 +90,66 @@ public abstract partial class MassFractionTestsBase : QuantityTestsBase protected virtual double PercentTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassFractionUnit unit) + { + return unit switch + { + MassFractionUnit.CentigramPerGram => (CentigramsPerGramInOneDecimalFraction, CentigramsPerGramTolerance), + MassFractionUnit.CentigramPerKilogram => (CentigramsPerKilogramInOneDecimalFraction, CentigramsPerKilogramTolerance), + MassFractionUnit.DecagramPerGram => (DecagramsPerGramInOneDecimalFraction, DecagramsPerGramTolerance), + MassFractionUnit.DecagramPerKilogram => (DecagramsPerKilogramInOneDecimalFraction, DecagramsPerKilogramTolerance), + MassFractionUnit.DecigramPerGram => (DecigramsPerGramInOneDecimalFraction, DecigramsPerGramTolerance), + MassFractionUnit.DecigramPerKilogram => (DecigramsPerKilogramInOneDecimalFraction, DecigramsPerKilogramTolerance), + MassFractionUnit.DecimalFraction => (DecimalFractionsInOneDecimalFraction, DecimalFractionsTolerance), + MassFractionUnit.GramPerGram => (GramsPerGramInOneDecimalFraction, GramsPerGramTolerance), + MassFractionUnit.GramPerKilogram => (GramsPerKilogramInOneDecimalFraction, GramsPerKilogramTolerance), + MassFractionUnit.HectogramPerGram => (HectogramsPerGramInOneDecimalFraction, HectogramsPerGramTolerance), + MassFractionUnit.HectogramPerKilogram => (HectogramsPerKilogramInOneDecimalFraction, HectogramsPerKilogramTolerance), + MassFractionUnit.KilogramPerGram => (KilogramsPerGramInOneDecimalFraction, KilogramsPerGramTolerance), + MassFractionUnit.KilogramPerKilogram => (KilogramsPerKilogramInOneDecimalFraction, KilogramsPerKilogramTolerance), + MassFractionUnit.MicrogramPerGram => (MicrogramsPerGramInOneDecimalFraction, MicrogramsPerGramTolerance), + MassFractionUnit.MicrogramPerKilogram => (MicrogramsPerKilogramInOneDecimalFraction, MicrogramsPerKilogramTolerance), + MassFractionUnit.MilligramPerGram => (MilligramsPerGramInOneDecimalFraction, MilligramsPerGramTolerance), + MassFractionUnit.MilligramPerKilogram => (MilligramsPerKilogramInOneDecimalFraction, MilligramsPerKilogramTolerance), + MassFractionUnit.NanogramPerGram => (NanogramsPerGramInOneDecimalFraction, NanogramsPerGramTolerance), + MassFractionUnit.NanogramPerKilogram => (NanogramsPerKilogramInOneDecimalFraction, NanogramsPerKilogramTolerance), + MassFractionUnit.PartPerBillion => (PartsPerBillionInOneDecimalFraction, PartsPerBillionTolerance), + MassFractionUnit.PartPerMillion => (PartsPerMillionInOneDecimalFraction, PartsPerMillionTolerance), + MassFractionUnit.PartPerThousand => (PartsPerThousandInOneDecimalFraction, PartsPerThousandTolerance), + MassFractionUnit.PartPerTrillion => (PartsPerTrillionInOneDecimalFraction, PartsPerTrillionTolerance), + MassFractionUnit.Percent => (PercentInOneDecimalFraction, PercentTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MassFractionUnit.CentigramPerGram }, + new object[] { MassFractionUnit.CentigramPerKilogram }, + new object[] { MassFractionUnit.DecagramPerGram }, + new object[] { MassFractionUnit.DecagramPerKilogram }, + new object[] { MassFractionUnit.DecigramPerGram }, + new object[] { MassFractionUnit.DecigramPerKilogram }, + new object[] { MassFractionUnit.DecimalFraction }, + new object[] { MassFractionUnit.GramPerGram }, + new object[] { MassFractionUnit.GramPerKilogram }, + new object[] { MassFractionUnit.HectogramPerGram }, + new object[] { MassFractionUnit.HectogramPerKilogram }, + new object[] { MassFractionUnit.KilogramPerGram }, + new object[] { MassFractionUnit.KilogramPerKilogram }, + new object[] { MassFractionUnit.MicrogramPerGram }, + new object[] { MassFractionUnit.MicrogramPerKilogram }, + new object[] { MassFractionUnit.MilligramPerGram }, + new object[] { MassFractionUnit.MilligramPerKilogram }, + new object[] { MassFractionUnit.NanogramPerGram }, + new object[] { MassFractionUnit.NanogramPerKilogram }, + new object[] { MassFractionUnit.PartPerBillion }, + new object[] { MassFractionUnit.PartPerMillion }, + new object[] { MassFractionUnit.PartPerThousand }, + new object[] { MassFractionUnit.PartPerTrillion }, + new object[] { MassFractionUnit.Percent }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -348,113 +409,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MassFractionUnit unit) { - var decimalfraction = MassFraction.FromDecimalFractions(1); - - var centigrampergramQuantity = decimalfraction.ToUnit(MassFractionUnit.CentigramPerGram); - AssertEx.EqualTolerance(CentigramsPerGramInOneDecimalFraction, (double)centigrampergramQuantity.Value, CentigramsPerGramTolerance); - Assert.Equal(MassFractionUnit.CentigramPerGram, centigrampergramQuantity.Unit); - - var centigramperkilogramQuantity = decimalfraction.ToUnit(MassFractionUnit.CentigramPerKilogram); - AssertEx.EqualTolerance(CentigramsPerKilogramInOneDecimalFraction, (double)centigramperkilogramQuantity.Value, CentigramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.CentigramPerKilogram, centigramperkilogramQuantity.Unit); - - var decagrampergramQuantity = decimalfraction.ToUnit(MassFractionUnit.DecagramPerGram); - AssertEx.EqualTolerance(DecagramsPerGramInOneDecimalFraction, (double)decagrampergramQuantity.Value, DecagramsPerGramTolerance); - Assert.Equal(MassFractionUnit.DecagramPerGram, decagrampergramQuantity.Unit); - - var decagramperkilogramQuantity = decimalfraction.ToUnit(MassFractionUnit.DecagramPerKilogram); - AssertEx.EqualTolerance(DecagramsPerKilogramInOneDecimalFraction, (double)decagramperkilogramQuantity.Value, DecagramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.DecagramPerKilogram, decagramperkilogramQuantity.Unit); - - var decigrampergramQuantity = decimalfraction.ToUnit(MassFractionUnit.DecigramPerGram); - AssertEx.EqualTolerance(DecigramsPerGramInOneDecimalFraction, (double)decigrampergramQuantity.Value, DecigramsPerGramTolerance); - Assert.Equal(MassFractionUnit.DecigramPerGram, decigrampergramQuantity.Unit); - - var decigramperkilogramQuantity = decimalfraction.ToUnit(MassFractionUnit.DecigramPerKilogram); - AssertEx.EqualTolerance(DecigramsPerKilogramInOneDecimalFraction, (double)decigramperkilogramQuantity.Value, DecigramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.DecigramPerKilogram, decigramperkilogramQuantity.Unit); - - var decimalfractionQuantity = decimalfraction.ToUnit(MassFractionUnit.DecimalFraction); - AssertEx.EqualTolerance(DecimalFractionsInOneDecimalFraction, (double)decimalfractionQuantity.Value, DecimalFractionsTolerance); - Assert.Equal(MassFractionUnit.DecimalFraction, decimalfractionQuantity.Unit); - - var grampergramQuantity = decimalfraction.ToUnit(MassFractionUnit.GramPerGram); - AssertEx.EqualTolerance(GramsPerGramInOneDecimalFraction, (double)grampergramQuantity.Value, GramsPerGramTolerance); - Assert.Equal(MassFractionUnit.GramPerGram, grampergramQuantity.Unit); - - var gramperkilogramQuantity = decimalfraction.ToUnit(MassFractionUnit.GramPerKilogram); - AssertEx.EqualTolerance(GramsPerKilogramInOneDecimalFraction, (double)gramperkilogramQuantity.Value, GramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.GramPerKilogram, gramperkilogramQuantity.Unit); - - var hectogrampergramQuantity = decimalfraction.ToUnit(MassFractionUnit.HectogramPerGram); - AssertEx.EqualTolerance(HectogramsPerGramInOneDecimalFraction, (double)hectogrampergramQuantity.Value, HectogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.HectogramPerGram, hectogrampergramQuantity.Unit); - - var hectogramperkilogramQuantity = decimalfraction.ToUnit(MassFractionUnit.HectogramPerKilogram); - AssertEx.EqualTolerance(HectogramsPerKilogramInOneDecimalFraction, (double)hectogramperkilogramQuantity.Value, HectogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.HectogramPerKilogram, hectogramperkilogramQuantity.Unit); - - var kilogrampergramQuantity = decimalfraction.ToUnit(MassFractionUnit.KilogramPerGram); - AssertEx.EqualTolerance(KilogramsPerGramInOneDecimalFraction, (double)kilogrampergramQuantity.Value, KilogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.KilogramPerGram, kilogrampergramQuantity.Unit); + var inBaseUnits = MassFraction.From(1.0, MassFraction.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilogramperkilogramQuantity = decimalfraction.ToUnit(MassFractionUnit.KilogramPerKilogram); - AssertEx.EqualTolerance(KilogramsPerKilogramInOneDecimalFraction, (double)kilogramperkilogramQuantity.Value, KilogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.KilogramPerKilogram, kilogramperkilogramQuantity.Unit); - - var microgrampergramQuantity = decimalfraction.ToUnit(MassFractionUnit.MicrogramPerGram); - AssertEx.EqualTolerance(MicrogramsPerGramInOneDecimalFraction, (double)microgrampergramQuantity.Value, MicrogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.MicrogramPerGram, microgrampergramQuantity.Unit); - - var microgramperkilogramQuantity = decimalfraction.ToUnit(MassFractionUnit.MicrogramPerKilogram); - AssertEx.EqualTolerance(MicrogramsPerKilogramInOneDecimalFraction, (double)microgramperkilogramQuantity.Value, MicrogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.MicrogramPerKilogram, microgramperkilogramQuantity.Unit); - - var milligrampergramQuantity = decimalfraction.ToUnit(MassFractionUnit.MilligramPerGram); - AssertEx.EqualTolerance(MilligramsPerGramInOneDecimalFraction, (double)milligrampergramQuantity.Value, MilligramsPerGramTolerance); - Assert.Equal(MassFractionUnit.MilligramPerGram, milligrampergramQuantity.Unit); - - var milligramperkilogramQuantity = decimalfraction.ToUnit(MassFractionUnit.MilligramPerKilogram); - AssertEx.EqualTolerance(MilligramsPerKilogramInOneDecimalFraction, (double)milligramperkilogramQuantity.Value, MilligramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.MilligramPerKilogram, milligramperkilogramQuantity.Unit); - - var nanogrampergramQuantity = decimalfraction.ToUnit(MassFractionUnit.NanogramPerGram); - AssertEx.EqualTolerance(NanogramsPerGramInOneDecimalFraction, (double)nanogrampergramQuantity.Value, NanogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.NanogramPerGram, nanogrampergramQuantity.Unit); - - var nanogramperkilogramQuantity = decimalfraction.ToUnit(MassFractionUnit.NanogramPerKilogram); - AssertEx.EqualTolerance(NanogramsPerKilogramInOneDecimalFraction, (double)nanogramperkilogramQuantity.Value, NanogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.NanogramPerKilogram, nanogramperkilogramQuantity.Unit); - - var partperbillionQuantity = decimalfraction.ToUnit(MassFractionUnit.PartPerBillion); - AssertEx.EqualTolerance(PartsPerBillionInOneDecimalFraction, (double)partperbillionQuantity.Value, PartsPerBillionTolerance); - Assert.Equal(MassFractionUnit.PartPerBillion, partperbillionQuantity.Unit); - - var partpermillionQuantity = decimalfraction.ToUnit(MassFractionUnit.PartPerMillion); - AssertEx.EqualTolerance(PartsPerMillionInOneDecimalFraction, (double)partpermillionQuantity.Value, PartsPerMillionTolerance); - Assert.Equal(MassFractionUnit.PartPerMillion, partpermillionQuantity.Unit); - - var partperthousandQuantity = decimalfraction.ToUnit(MassFractionUnit.PartPerThousand); - AssertEx.EqualTolerance(PartsPerThousandInOneDecimalFraction, (double)partperthousandQuantity.Value, PartsPerThousandTolerance); - Assert.Equal(MassFractionUnit.PartPerThousand, partperthousandQuantity.Unit); - - var partpertrillionQuantity = decimalfraction.ToUnit(MassFractionUnit.PartPerTrillion); - AssertEx.EqualTolerance(PartsPerTrillionInOneDecimalFraction, (double)partpertrillionQuantity.Value, PartsPerTrillionTolerance); - Assert.Equal(MassFractionUnit.PartPerTrillion, partpertrillionQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var percentQuantity = decimalfraction.ToUnit(MassFractionUnit.Percent); - AssertEx.EqualTolerance(PercentInOneDecimalFraction, (double)percentQuantity.Value, PercentTolerance); - Assert.Equal(MassFractionUnit.Percent, percentQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MassFractionUnit unit) + { + var quantity = MassFraction.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFractionUnit unit) { - var quantityInBaseUnit = MassFraction.FromDecimalFractions(1).ToBaseUnit(); - Assert.Equal(MassFraction.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MassFraction.Units.FirstOrDefault(u => u != MassFraction.BaseUnit && u != MassFractionUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MassFractionUnit.Undefined) + fromUnit = MassFraction.BaseUnit; + + var quantity = MassFraction.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs index ff9b74d7df..f4b8bb0263 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -97,6 +98,74 @@ public abstract partial class MassMomentOfInertiaTestsBase : QuantityTestsBase protected virtual double TonneSquareMilimetersTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassMomentOfInertiaUnit unit) + { + return unit switch + { + MassMomentOfInertiaUnit.GramSquareCentimeter => (GramSquareCentimetersInOneKilogramSquareMeter, GramSquareCentimetersTolerance), + MassMomentOfInertiaUnit.GramSquareDecimeter => (GramSquareDecimetersInOneKilogramSquareMeter, GramSquareDecimetersTolerance), + MassMomentOfInertiaUnit.GramSquareMeter => (GramSquareMetersInOneKilogramSquareMeter, GramSquareMetersTolerance), + MassMomentOfInertiaUnit.GramSquareMillimeter => (GramSquareMillimetersInOneKilogramSquareMeter, GramSquareMillimetersTolerance), + MassMomentOfInertiaUnit.KilogramSquareCentimeter => (KilogramSquareCentimetersInOneKilogramSquareMeter, KilogramSquareCentimetersTolerance), + MassMomentOfInertiaUnit.KilogramSquareDecimeter => (KilogramSquareDecimetersInOneKilogramSquareMeter, KilogramSquareDecimetersTolerance), + MassMomentOfInertiaUnit.KilogramSquareMeter => (KilogramSquareMetersInOneKilogramSquareMeter, KilogramSquareMetersTolerance), + MassMomentOfInertiaUnit.KilogramSquareMillimeter => (KilogramSquareMillimetersInOneKilogramSquareMeter, KilogramSquareMillimetersTolerance), + MassMomentOfInertiaUnit.KilotonneSquareCentimeter => (KilotonneSquareCentimetersInOneKilogramSquareMeter, KilotonneSquareCentimetersTolerance), + MassMomentOfInertiaUnit.KilotonneSquareDecimeter => (KilotonneSquareDecimetersInOneKilogramSquareMeter, KilotonneSquareDecimetersTolerance), + MassMomentOfInertiaUnit.KilotonneSquareMeter => (KilotonneSquareMetersInOneKilogramSquareMeter, KilotonneSquareMetersTolerance), + MassMomentOfInertiaUnit.KilotonneSquareMilimeter => (KilotonneSquareMilimetersInOneKilogramSquareMeter, KilotonneSquareMilimetersTolerance), + MassMomentOfInertiaUnit.MegatonneSquareCentimeter => (MegatonneSquareCentimetersInOneKilogramSquareMeter, MegatonneSquareCentimetersTolerance), + MassMomentOfInertiaUnit.MegatonneSquareDecimeter => (MegatonneSquareDecimetersInOneKilogramSquareMeter, MegatonneSquareDecimetersTolerance), + MassMomentOfInertiaUnit.MegatonneSquareMeter => (MegatonneSquareMetersInOneKilogramSquareMeter, MegatonneSquareMetersTolerance), + MassMomentOfInertiaUnit.MegatonneSquareMilimeter => (MegatonneSquareMilimetersInOneKilogramSquareMeter, MegatonneSquareMilimetersTolerance), + MassMomentOfInertiaUnit.MilligramSquareCentimeter => (MilligramSquareCentimetersInOneKilogramSquareMeter, MilligramSquareCentimetersTolerance), + MassMomentOfInertiaUnit.MilligramSquareDecimeter => (MilligramSquareDecimetersInOneKilogramSquareMeter, MilligramSquareDecimetersTolerance), + MassMomentOfInertiaUnit.MilligramSquareMeter => (MilligramSquareMetersInOneKilogramSquareMeter, MilligramSquareMetersTolerance), + MassMomentOfInertiaUnit.MilligramSquareMillimeter => (MilligramSquareMillimetersInOneKilogramSquareMeter, MilligramSquareMillimetersTolerance), + MassMomentOfInertiaUnit.PoundSquareFoot => (PoundSquareFeetInOneKilogramSquareMeter, PoundSquareFeetTolerance), + MassMomentOfInertiaUnit.PoundSquareInch => (PoundSquareInchesInOneKilogramSquareMeter, PoundSquareInchesTolerance), + MassMomentOfInertiaUnit.SlugSquareFoot => (SlugSquareFeetInOneKilogramSquareMeter, SlugSquareFeetTolerance), + MassMomentOfInertiaUnit.SlugSquareInch => (SlugSquareInchesInOneKilogramSquareMeter, SlugSquareInchesTolerance), + MassMomentOfInertiaUnit.TonneSquareCentimeter => (TonneSquareCentimetersInOneKilogramSquareMeter, TonneSquareCentimetersTolerance), + MassMomentOfInertiaUnit.TonneSquareDecimeter => (TonneSquareDecimetersInOneKilogramSquareMeter, TonneSquareDecimetersTolerance), + MassMomentOfInertiaUnit.TonneSquareMeter => (TonneSquareMetersInOneKilogramSquareMeter, TonneSquareMetersTolerance), + MassMomentOfInertiaUnit.TonneSquareMilimeter => (TonneSquareMilimetersInOneKilogramSquareMeter, TonneSquareMilimetersTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MassMomentOfInertiaUnit.GramSquareCentimeter }, + new object[] { MassMomentOfInertiaUnit.GramSquareDecimeter }, + new object[] { MassMomentOfInertiaUnit.GramSquareMeter }, + new object[] { MassMomentOfInertiaUnit.GramSquareMillimeter }, + new object[] { MassMomentOfInertiaUnit.KilogramSquareCentimeter }, + new object[] { MassMomentOfInertiaUnit.KilogramSquareDecimeter }, + new object[] { MassMomentOfInertiaUnit.KilogramSquareMeter }, + new object[] { MassMomentOfInertiaUnit.KilogramSquareMillimeter }, + new object[] { MassMomentOfInertiaUnit.KilotonneSquareCentimeter }, + new object[] { MassMomentOfInertiaUnit.KilotonneSquareDecimeter }, + new object[] { MassMomentOfInertiaUnit.KilotonneSquareMeter }, + new object[] { MassMomentOfInertiaUnit.KilotonneSquareMilimeter }, + new object[] { MassMomentOfInertiaUnit.MegatonneSquareCentimeter }, + new object[] { MassMomentOfInertiaUnit.MegatonneSquareDecimeter }, + new object[] { MassMomentOfInertiaUnit.MegatonneSquareMeter }, + new object[] { MassMomentOfInertiaUnit.MegatonneSquareMilimeter }, + new object[] { MassMomentOfInertiaUnit.MilligramSquareCentimeter }, + new object[] { MassMomentOfInertiaUnit.MilligramSquareDecimeter }, + new object[] { MassMomentOfInertiaUnit.MilligramSquareMeter }, + new object[] { MassMomentOfInertiaUnit.MilligramSquareMillimeter }, + new object[] { MassMomentOfInertiaUnit.PoundSquareFoot }, + new object[] { MassMomentOfInertiaUnit.PoundSquareInch }, + new object[] { MassMomentOfInertiaUnit.SlugSquareFoot }, + new object[] { MassMomentOfInertiaUnit.SlugSquareInch }, + new object[] { MassMomentOfInertiaUnit.TonneSquareCentimeter }, + new object[] { MassMomentOfInertiaUnit.TonneSquareDecimeter }, + new object[] { MassMomentOfInertiaUnit.TonneSquareMeter }, + new object[] { MassMomentOfInertiaUnit.TonneSquareMilimeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -380,129 +449,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MassMomentOfInertiaUnit unit) { - var kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - - var gramsquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.GramSquareCentimeter); - AssertEx.EqualTolerance(GramSquareCentimetersInOneKilogramSquareMeter, (double)gramsquarecentimeterQuantity.Value, GramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareCentimeter, gramsquarecentimeterQuantity.Unit); - - var gramsquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.GramSquareDecimeter); - AssertEx.EqualTolerance(GramSquareDecimetersInOneKilogramSquareMeter, (double)gramsquaredecimeterQuantity.Value, GramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareDecimeter, gramsquaredecimeterQuantity.Unit); - - var gramsquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.GramSquareMeter); - AssertEx.EqualTolerance(GramSquareMetersInOneKilogramSquareMeter, (double)gramsquaremeterQuantity.Value, GramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareMeter, gramsquaremeterQuantity.Unit); - - var gramsquaremillimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.GramSquareMillimeter); - AssertEx.EqualTolerance(GramSquareMillimetersInOneKilogramSquareMeter, (double)gramsquaremillimeterQuantity.Value, GramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareMillimeter, gramsquaremillimeterQuantity.Unit); - - var kilogramsquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilogramSquareCentimeter); - AssertEx.EqualTolerance(KilogramSquareCentimetersInOneKilogramSquareMeter, (double)kilogramsquarecentimeterQuantity.Value, KilogramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareCentimeter, kilogramsquarecentimeterQuantity.Unit); - - var kilogramsquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilogramSquareDecimeter); - AssertEx.EqualTolerance(KilogramSquareDecimetersInOneKilogramSquareMeter, (double)kilogramsquaredecimeterQuantity.Value, KilogramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareDecimeter, kilogramsquaredecimeterQuantity.Unit); - - var kilogramsquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter); - AssertEx.EqualTolerance(KilogramSquareMetersInOneKilogramSquareMeter, (double)kilogramsquaremeterQuantity.Value, KilogramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMeter, kilogramsquaremeterQuantity.Unit); - - var kilogramsquaremillimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMillimeter); - AssertEx.EqualTolerance(KilogramSquareMillimetersInOneKilogramSquareMeter, (double)kilogramsquaremillimeterQuantity.Value, KilogramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMillimeter, kilogramsquaremillimeterQuantity.Unit); - - var kilotonnesquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); - AssertEx.EqualTolerance(KilotonneSquareCentimetersInOneKilogramSquareMeter, (double)kilotonnesquarecentimeterQuantity.Value, KilotonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, kilotonnesquarecentimeterQuantity.Unit); - - var kilotonnesquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); - AssertEx.EqualTolerance(KilotonneSquareDecimetersInOneKilogramSquareMeter, (double)kilotonnesquaredecimeterQuantity.Value, KilotonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, kilotonnesquaredecimeterQuantity.Unit); - - var kilotonnesquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMeter); - AssertEx.EqualTolerance(KilotonneSquareMetersInOneKilogramSquareMeter, (double)kilotonnesquaremeterQuantity.Value, KilotonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMeter, kilotonnesquaremeterQuantity.Unit); - - var kilotonnesquaremilimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); - AssertEx.EqualTolerance(KilotonneSquareMilimetersInOneKilogramSquareMeter, (double)kilotonnesquaremilimeterQuantity.Value, KilotonneSquareMilimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMilimeter, kilotonnesquaremilimeterQuantity.Unit); - - var megatonnesquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); - AssertEx.EqualTolerance(MegatonneSquareCentimetersInOneKilogramSquareMeter, (double)megatonnesquarecentimeterQuantity.Value, MegatonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, megatonnesquarecentimeterQuantity.Unit); - - var megatonnesquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); - AssertEx.EqualTolerance(MegatonneSquareDecimetersInOneKilogramSquareMeter, (double)megatonnesquaredecimeterQuantity.Value, MegatonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, megatonnesquaredecimeterQuantity.Unit); + var inBaseUnits = MassMomentOfInertia.From(1.0, MassMomentOfInertia.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megatonnesquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMeter); - AssertEx.EqualTolerance(MegatonneSquareMetersInOneKilogramSquareMeter, (double)megatonnesquaremeterQuantity.Value, MegatonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMeter, megatonnesquaremeterQuantity.Unit); - - var megatonnesquaremilimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); - AssertEx.EqualTolerance(MegatonneSquareMilimetersInOneKilogramSquareMeter, (double)megatonnesquaremilimeterQuantity.Value, MegatonneSquareMilimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMilimeter, megatonnesquaremilimeterQuantity.Unit); - - var milligramsquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MilligramSquareCentimeter); - AssertEx.EqualTolerance(MilligramSquareCentimetersInOneKilogramSquareMeter, (double)milligramsquarecentimeterQuantity.Value, MilligramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareCentimeter, milligramsquarecentimeterQuantity.Unit); - - var milligramsquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MilligramSquareDecimeter); - AssertEx.EqualTolerance(MilligramSquareDecimetersInOneKilogramSquareMeter, (double)milligramsquaredecimeterQuantity.Value, MilligramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareDecimeter, milligramsquaredecimeterQuantity.Unit); - - var milligramsquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMeter); - AssertEx.EqualTolerance(MilligramSquareMetersInOneKilogramSquareMeter, (double)milligramsquaremeterQuantity.Value, MilligramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMeter, milligramsquaremeterQuantity.Unit); - - var milligramsquaremillimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMillimeter); - AssertEx.EqualTolerance(MilligramSquareMillimetersInOneKilogramSquareMeter, (double)milligramsquaremillimeterQuantity.Value, MilligramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMillimeter, milligramsquaremillimeterQuantity.Unit); - - var poundsquarefootQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.PoundSquareFoot); - AssertEx.EqualTolerance(PoundSquareFeetInOneKilogramSquareMeter, (double)poundsquarefootQuantity.Value, PoundSquareFeetTolerance); - Assert.Equal(MassMomentOfInertiaUnit.PoundSquareFoot, poundsquarefootQuantity.Unit); - - var poundsquareinchQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.PoundSquareInch); - AssertEx.EqualTolerance(PoundSquareInchesInOneKilogramSquareMeter, (double)poundsquareinchQuantity.Value, PoundSquareInchesTolerance); - Assert.Equal(MassMomentOfInertiaUnit.PoundSquareInch, poundsquareinchQuantity.Unit); - - var slugsquarefootQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.SlugSquareFoot); - AssertEx.EqualTolerance(SlugSquareFeetInOneKilogramSquareMeter, (double)slugsquarefootQuantity.Value, SlugSquareFeetTolerance); - Assert.Equal(MassMomentOfInertiaUnit.SlugSquareFoot, slugsquarefootQuantity.Unit); - - var slugsquareinchQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.SlugSquareInch); - AssertEx.EqualTolerance(SlugSquareInchesInOneKilogramSquareMeter, (double)slugsquareinchQuantity.Value, SlugSquareInchesTolerance); - Assert.Equal(MassMomentOfInertiaUnit.SlugSquareInch, slugsquareinchQuantity.Unit); - - var tonnesquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.TonneSquareCentimeter); - AssertEx.EqualTolerance(TonneSquareCentimetersInOneKilogramSquareMeter, (double)tonnesquarecentimeterQuantity.Value, TonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareCentimeter, tonnesquarecentimeterQuantity.Unit); - - var tonnesquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.TonneSquareDecimeter); - AssertEx.EqualTolerance(TonneSquareDecimetersInOneKilogramSquareMeter, (double)tonnesquaredecimeterQuantity.Value, TonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareDecimeter, tonnesquaredecimeterQuantity.Unit); - - var tonnesquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.TonneSquareMeter); - AssertEx.EqualTolerance(TonneSquareMetersInOneKilogramSquareMeter, (double)tonnesquaremeterQuantity.Value, TonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMeter, tonnesquaremeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonnesquaremilimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.TonneSquareMilimeter); - AssertEx.EqualTolerance(TonneSquareMilimetersInOneKilogramSquareMeter, (double)tonnesquaremilimeterQuantity.Value, TonneSquareMilimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMilimeter, tonnesquaremilimeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MassMomentOfInertiaUnit unit) + { + var quantity = MassMomentOfInertia.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassMomentOfInertiaUnit unit) { - var quantityInBaseUnit = MassMomentOfInertia.FromKilogramSquareMeters(1).ToBaseUnit(); - Assert.Equal(MassMomentOfInertia.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MassMomentOfInertia.Units.FirstOrDefault(u => u != MassMomentOfInertia.BaseUnit && u != MassMomentOfInertiaUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MassMomentOfInertiaUnit.Undefined) + fromUnit = MassMomentOfInertia.BaseUnit; + + var quantity = MassMomentOfInertia.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs index 0d28d6724e..ae7364df1b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -91,6 +92,68 @@ public abstract partial class MassTestsBase : QuantityTestsBase protected virtual double TonnesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassUnit unit) + { + return unit switch + { + MassUnit.Centigram => (CentigramsInOneKilogram, CentigramsTolerance), + MassUnit.Decagram => (DecagramsInOneKilogram, DecagramsTolerance), + MassUnit.Decigram => (DecigramsInOneKilogram, DecigramsTolerance), + MassUnit.EarthMass => (EarthMassesInOneKilogram, EarthMassesTolerance), + MassUnit.Grain => (GrainsInOneKilogram, GrainsTolerance), + MassUnit.Gram => (GramsInOneKilogram, GramsTolerance), + MassUnit.Hectogram => (HectogramsInOneKilogram, HectogramsTolerance), + MassUnit.Kilogram => (KilogramsInOneKilogram, KilogramsTolerance), + MassUnit.Kilopound => (KilopoundsInOneKilogram, KilopoundsTolerance), + MassUnit.Kilotonne => (KilotonnesInOneKilogram, KilotonnesTolerance), + MassUnit.LongHundredweight => (LongHundredweightInOneKilogram, LongHundredweightTolerance), + MassUnit.LongTon => (LongTonsInOneKilogram, LongTonsTolerance), + MassUnit.Megapound => (MegapoundsInOneKilogram, MegapoundsTolerance), + MassUnit.Megatonne => (MegatonnesInOneKilogram, MegatonnesTolerance), + MassUnit.Microgram => (MicrogramsInOneKilogram, MicrogramsTolerance), + MassUnit.Milligram => (MilligramsInOneKilogram, MilligramsTolerance), + MassUnit.Nanogram => (NanogramsInOneKilogram, NanogramsTolerance), + MassUnit.Ounce => (OuncesInOneKilogram, OuncesTolerance), + MassUnit.Pound => (PoundsInOneKilogram, PoundsTolerance), + MassUnit.ShortHundredweight => (ShortHundredweightInOneKilogram, ShortHundredweightTolerance), + MassUnit.ShortTon => (ShortTonsInOneKilogram, ShortTonsTolerance), + MassUnit.Slug => (SlugsInOneKilogram, SlugsTolerance), + MassUnit.SolarMass => (SolarMassesInOneKilogram, SolarMassesTolerance), + MassUnit.Stone => (StoneInOneKilogram, StoneTolerance), + MassUnit.Tonne => (TonnesInOneKilogram, TonnesTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MassUnit.Centigram }, + new object[] { MassUnit.Decagram }, + new object[] { MassUnit.Decigram }, + new object[] { MassUnit.EarthMass }, + new object[] { MassUnit.Grain }, + new object[] { MassUnit.Gram }, + new object[] { MassUnit.Hectogram }, + new object[] { MassUnit.Kilogram }, + new object[] { MassUnit.Kilopound }, + new object[] { MassUnit.Kilotonne }, + new object[] { MassUnit.LongHundredweight }, + new object[] { MassUnit.LongTon }, + new object[] { MassUnit.Megapound }, + new object[] { MassUnit.Megatonne }, + new object[] { MassUnit.Microgram }, + new object[] { MassUnit.Milligram }, + new object[] { MassUnit.Nanogram }, + new object[] { MassUnit.Ounce }, + new object[] { MassUnit.Pound }, + new object[] { MassUnit.ShortHundredweight }, + new object[] { MassUnit.ShortTon }, + new object[] { MassUnit.Slug }, + new object[] { MassUnit.SolarMass }, + new object[] { MassUnit.Stone }, + new object[] { MassUnit.Tonne }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -356,117 +419,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MassUnit unit) { - var kilogram = Mass.FromKilograms(1); - - var centigramQuantity = kilogram.ToUnit(MassUnit.Centigram); - AssertEx.EqualTolerance(CentigramsInOneKilogram, (double)centigramQuantity.Value, CentigramsTolerance); - Assert.Equal(MassUnit.Centigram, centigramQuantity.Unit); - - var decagramQuantity = kilogram.ToUnit(MassUnit.Decagram); - AssertEx.EqualTolerance(DecagramsInOneKilogram, (double)decagramQuantity.Value, DecagramsTolerance); - Assert.Equal(MassUnit.Decagram, decagramQuantity.Unit); - - var decigramQuantity = kilogram.ToUnit(MassUnit.Decigram); - AssertEx.EqualTolerance(DecigramsInOneKilogram, (double)decigramQuantity.Value, DecigramsTolerance); - Assert.Equal(MassUnit.Decigram, decigramQuantity.Unit); - - var earthmassQuantity = kilogram.ToUnit(MassUnit.EarthMass); - AssertEx.EqualTolerance(EarthMassesInOneKilogram, (double)earthmassQuantity.Value, EarthMassesTolerance); - Assert.Equal(MassUnit.EarthMass, earthmassQuantity.Unit); - - var grainQuantity = kilogram.ToUnit(MassUnit.Grain); - AssertEx.EqualTolerance(GrainsInOneKilogram, (double)grainQuantity.Value, GrainsTolerance); - Assert.Equal(MassUnit.Grain, grainQuantity.Unit); - - var gramQuantity = kilogram.ToUnit(MassUnit.Gram); - AssertEx.EqualTolerance(GramsInOneKilogram, (double)gramQuantity.Value, GramsTolerance); - Assert.Equal(MassUnit.Gram, gramQuantity.Unit); - - var hectogramQuantity = kilogram.ToUnit(MassUnit.Hectogram); - AssertEx.EqualTolerance(HectogramsInOneKilogram, (double)hectogramQuantity.Value, HectogramsTolerance); - Assert.Equal(MassUnit.Hectogram, hectogramQuantity.Unit); - - var kilogramQuantity = kilogram.ToUnit(MassUnit.Kilogram); - AssertEx.EqualTolerance(KilogramsInOneKilogram, (double)kilogramQuantity.Value, KilogramsTolerance); - Assert.Equal(MassUnit.Kilogram, kilogramQuantity.Unit); - - var kilopoundQuantity = kilogram.ToUnit(MassUnit.Kilopound); - AssertEx.EqualTolerance(KilopoundsInOneKilogram, (double)kilopoundQuantity.Value, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, kilopoundQuantity.Unit); - - var kilotonneQuantity = kilogram.ToUnit(MassUnit.Kilotonne); - AssertEx.EqualTolerance(KilotonnesInOneKilogram, (double)kilotonneQuantity.Value, KilotonnesTolerance); - Assert.Equal(MassUnit.Kilotonne, kilotonneQuantity.Unit); - - var longhundredweightQuantity = kilogram.ToUnit(MassUnit.LongHundredweight); - AssertEx.EqualTolerance(LongHundredweightInOneKilogram, (double)longhundredweightQuantity.Value, LongHundredweightTolerance); - Assert.Equal(MassUnit.LongHundredweight, longhundredweightQuantity.Unit); - - var longtonQuantity = kilogram.ToUnit(MassUnit.LongTon); - AssertEx.EqualTolerance(LongTonsInOneKilogram, (double)longtonQuantity.Value, LongTonsTolerance); - Assert.Equal(MassUnit.LongTon, longtonQuantity.Unit); + var inBaseUnits = Mass.From(1.0, Mass.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megapoundQuantity = kilogram.ToUnit(MassUnit.Megapound); - AssertEx.EqualTolerance(MegapoundsInOneKilogram, (double)megapoundQuantity.Value, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, megapoundQuantity.Unit); - - var megatonneQuantity = kilogram.ToUnit(MassUnit.Megatonne); - AssertEx.EqualTolerance(MegatonnesInOneKilogram, (double)megatonneQuantity.Value, MegatonnesTolerance); - Assert.Equal(MassUnit.Megatonne, megatonneQuantity.Unit); - - var microgramQuantity = kilogram.ToUnit(MassUnit.Microgram); - AssertEx.EqualTolerance(MicrogramsInOneKilogram, (double)microgramQuantity.Value, MicrogramsTolerance); - Assert.Equal(MassUnit.Microgram, microgramQuantity.Unit); - - var milligramQuantity = kilogram.ToUnit(MassUnit.Milligram); - AssertEx.EqualTolerance(MilligramsInOneKilogram, (double)milligramQuantity.Value, MilligramsTolerance); - Assert.Equal(MassUnit.Milligram, milligramQuantity.Unit); - - var nanogramQuantity = kilogram.ToUnit(MassUnit.Nanogram); - AssertEx.EqualTolerance(NanogramsInOneKilogram, (double)nanogramQuantity.Value, NanogramsTolerance); - Assert.Equal(MassUnit.Nanogram, nanogramQuantity.Unit); - - var ounceQuantity = kilogram.ToUnit(MassUnit.Ounce); - AssertEx.EqualTolerance(OuncesInOneKilogram, (double)ounceQuantity.Value, OuncesTolerance); - Assert.Equal(MassUnit.Ounce, ounceQuantity.Unit); - - var poundQuantity = kilogram.ToUnit(MassUnit.Pound); - AssertEx.EqualTolerance(PoundsInOneKilogram, (double)poundQuantity.Value, PoundsTolerance); - Assert.Equal(MassUnit.Pound, poundQuantity.Unit); - - var shorthundredweightQuantity = kilogram.ToUnit(MassUnit.ShortHundredweight); - AssertEx.EqualTolerance(ShortHundredweightInOneKilogram, (double)shorthundredweightQuantity.Value, ShortHundredweightTolerance); - Assert.Equal(MassUnit.ShortHundredweight, shorthundredweightQuantity.Unit); - - var shorttonQuantity = kilogram.ToUnit(MassUnit.ShortTon); - AssertEx.EqualTolerance(ShortTonsInOneKilogram, (double)shorttonQuantity.Value, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, shorttonQuantity.Unit); - - var slugQuantity = kilogram.ToUnit(MassUnit.Slug); - AssertEx.EqualTolerance(SlugsInOneKilogram, (double)slugQuantity.Value, SlugsTolerance); - Assert.Equal(MassUnit.Slug, slugQuantity.Unit); - - var solarmassQuantity = kilogram.ToUnit(MassUnit.SolarMass); - AssertEx.EqualTolerance(SolarMassesInOneKilogram, (double)solarmassQuantity.Value, SolarMassesTolerance); - Assert.Equal(MassUnit.SolarMass, solarmassQuantity.Unit); - - var stoneQuantity = kilogram.ToUnit(MassUnit.Stone); - AssertEx.EqualTolerance(StoneInOneKilogram, (double)stoneQuantity.Value, StoneTolerance); - Assert.Equal(MassUnit.Stone, stoneQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonneQuantity = kilogram.ToUnit(MassUnit.Tonne); - AssertEx.EqualTolerance(TonnesInOneKilogram, (double)tonneQuantity.Value, TonnesTolerance); - Assert.Equal(MassUnit.Tonne, tonneQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MassUnit unit) + { + var quantity = Mass.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassUnit unit) { - var quantityInBaseUnit = Mass.FromKilograms(1).ToBaseUnit(); - Assert.Equal(Mass.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Mass.Units.FirstOrDefault(u => u != Mass.BaseUnit && u != MassUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MassUnit.Undefined) + fromUnit = Mass.BaseUnit; + + var quantity = Mass.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs index 2bcf7a5820..fdbfa2178c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class MolarEnergyTestsBase : QuantityTestsBase protected virtual double MegajoulesPerMoleTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MolarEnergyUnit unit) + { + return unit switch + { + MolarEnergyUnit.JoulePerMole => (JoulesPerMoleInOneJoulePerMole, JoulesPerMoleTolerance), + MolarEnergyUnit.KilojoulePerMole => (KilojoulesPerMoleInOneJoulePerMole, KilojoulesPerMoleTolerance), + MolarEnergyUnit.MegajoulePerMole => (MegajoulesPerMoleInOneJoulePerMole, MegajoulesPerMoleTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MolarEnergyUnit.JoulePerMole }, + new object[] { MolarEnergyUnit.KilojoulePerMole }, + new object[] { MolarEnergyUnit.MegajoulePerMole }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MolarEnergyUnit unit) { - var joulepermole = MolarEnergy.FromJoulesPerMole(1); + var inBaseUnits = MolarEnergy.From(1.0, MolarEnergy.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var joulepermoleQuantity = joulepermole.ToUnit(MolarEnergyUnit.JoulePerMole); - AssertEx.EqualTolerance(JoulesPerMoleInOneJoulePerMole, (double)joulepermoleQuantity.Value, JoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.JoulePerMole, joulepermoleQuantity.Unit); - - var kilojoulepermoleQuantity = joulepermole.ToUnit(MolarEnergyUnit.KilojoulePerMole); - AssertEx.EqualTolerance(KilojoulesPerMoleInOneJoulePerMole, (double)kilojoulepermoleQuantity.Value, KilojoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.KilojoulePerMole, kilojoulepermoleQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var megajoulepermoleQuantity = joulepermole.ToUnit(MolarEnergyUnit.MegajoulePerMole); - AssertEx.EqualTolerance(MegajoulesPerMoleInOneJoulePerMole, (double)megajoulepermoleQuantity.Value, MegajoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.MegajoulePerMole, megajoulepermoleQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MolarEnergyUnit unit) + { + var quantity = MolarEnergy.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarEnergyUnit unit) { - var quantityInBaseUnit = MolarEnergy.FromJoulesPerMole(1).ToBaseUnit(); - Assert.Equal(MolarEnergy.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MolarEnergy.Units.FirstOrDefault(u => u != MolarEnergy.BaseUnit && u != MolarEnergyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MolarEnergyUnit.Undefined) + fromUnit = MolarEnergy.BaseUnit; + + var quantity = MolarEnergy.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs index 0a076aae5e..93ef01239e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class MolarEntropyTestsBase : QuantityTestsBase protected virtual double MegajoulesPerMoleKelvinTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MolarEntropyUnit unit) + { + return unit switch + { + MolarEntropyUnit.JoulePerMoleKelvin => (JoulesPerMoleKelvinInOneJoulePerMoleKelvin, JoulesPerMoleKelvinTolerance), + MolarEntropyUnit.KilojoulePerMoleKelvin => (KilojoulesPerMoleKelvinInOneJoulePerMoleKelvin, KilojoulesPerMoleKelvinTolerance), + MolarEntropyUnit.MegajoulePerMoleKelvin => (MegajoulesPerMoleKelvinInOneJoulePerMoleKelvin, MegajoulesPerMoleKelvinTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MolarEntropyUnit.JoulePerMoleKelvin }, + new object[] { MolarEntropyUnit.KilojoulePerMoleKelvin }, + new object[] { MolarEntropyUnit.MegajoulePerMoleKelvin }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MolarEntropyUnit unit) { - var joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); + var inBaseUnits = MolarEntropy.From(1.0, MolarEntropy.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var joulepermolekelvinQuantity = joulepermolekelvin.ToUnit(MolarEntropyUnit.JoulePerMoleKelvin); - AssertEx.EqualTolerance(JoulesPerMoleKelvinInOneJoulePerMoleKelvin, (double)joulepermolekelvinQuantity.Value, JoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.JoulePerMoleKelvin, joulepermolekelvinQuantity.Unit); - - var kilojoulepermolekelvinQuantity = joulepermolekelvin.ToUnit(MolarEntropyUnit.KilojoulePerMoleKelvin); - AssertEx.EqualTolerance(KilojoulesPerMoleKelvinInOneJoulePerMoleKelvin, (double)kilojoulepermolekelvinQuantity.Value, KilojoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.KilojoulePerMoleKelvin, kilojoulepermolekelvinQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var megajoulepermolekelvinQuantity = joulepermolekelvin.ToUnit(MolarEntropyUnit.MegajoulePerMoleKelvin); - AssertEx.EqualTolerance(MegajoulesPerMoleKelvinInOneJoulePerMoleKelvin, (double)megajoulepermolekelvinQuantity.Value, MegajoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.MegajoulePerMoleKelvin, megajoulepermolekelvinQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MolarEntropyUnit unit) + { + var quantity = MolarEntropy.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarEntropyUnit unit) { - var quantityInBaseUnit = MolarEntropy.FromJoulesPerMoleKelvin(1).ToBaseUnit(); - Assert.Equal(MolarEntropy.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MolarEntropy.Units.FirstOrDefault(u => u != MolarEntropy.BaseUnit && u != MolarEntropyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MolarEntropyUnit.Undefined) + fromUnit = MolarEntropy.BaseUnit; + + var quantity = MolarEntropy.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs index 7df39a1cc9..b6b58539ad 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -65,6 +66,42 @@ public abstract partial class MolarMassTestsBase : QuantityTestsBase protected virtual double PoundsPerMoleTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MolarMassUnit unit) + { + return unit switch + { + MolarMassUnit.CentigramPerMole => (CentigramsPerMoleInOneKilogramPerMole, CentigramsPerMoleTolerance), + MolarMassUnit.DecagramPerMole => (DecagramsPerMoleInOneKilogramPerMole, DecagramsPerMoleTolerance), + MolarMassUnit.DecigramPerMole => (DecigramsPerMoleInOneKilogramPerMole, DecigramsPerMoleTolerance), + MolarMassUnit.GramPerMole => (GramsPerMoleInOneKilogramPerMole, GramsPerMoleTolerance), + MolarMassUnit.HectogramPerMole => (HectogramsPerMoleInOneKilogramPerMole, HectogramsPerMoleTolerance), + MolarMassUnit.KilogramPerMole => (KilogramsPerMoleInOneKilogramPerMole, KilogramsPerMoleTolerance), + MolarMassUnit.KilopoundPerMole => (KilopoundsPerMoleInOneKilogramPerMole, KilopoundsPerMoleTolerance), + MolarMassUnit.MegapoundPerMole => (MegapoundsPerMoleInOneKilogramPerMole, MegapoundsPerMoleTolerance), + MolarMassUnit.MicrogramPerMole => (MicrogramsPerMoleInOneKilogramPerMole, MicrogramsPerMoleTolerance), + MolarMassUnit.MilligramPerMole => (MilligramsPerMoleInOneKilogramPerMole, MilligramsPerMoleTolerance), + MolarMassUnit.NanogramPerMole => (NanogramsPerMoleInOneKilogramPerMole, NanogramsPerMoleTolerance), + MolarMassUnit.PoundPerMole => (PoundsPerMoleInOneKilogramPerMole, PoundsPerMoleTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MolarMassUnit.CentigramPerMole }, + new object[] { MolarMassUnit.DecagramPerMole }, + new object[] { MolarMassUnit.DecigramPerMole }, + new object[] { MolarMassUnit.GramPerMole }, + new object[] { MolarMassUnit.HectogramPerMole }, + new object[] { MolarMassUnit.KilogramPerMole }, + new object[] { MolarMassUnit.KilopoundPerMole }, + new object[] { MolarMassUnit.MegapoundPerMole }, + new object[] { MolarMassUnit.MicrogramPerMole }, + new object[] { MolarMassUnit.MilligramPerMole }, + new object[] { MolarMassUnit.NanogramPerMole }, + new object[] { MolarMassUnit.PoundPerMole }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -252,65 +289,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MolarMassUnit unit) { - var kilogrampermole = MolarMass.FromKilogramsPerMole(1); - - var centigrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.CentigramPerMole); - AssertEx.EqualTolerance(CentigramsPerMoleInOneKilogramPerMole, (double)centigrampermoleQuantity.Value, CentigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.CentigramPerMole, centigrampermoleQuantity.Unit); - - var decagrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.DecagramPerMole); - AssertEx.EqualTolerance(DecagramsPerMoleInOneKilogramPerMole, (double)decagrampermoleQuantity.Value, DecagramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecagramPerMole, decagrampermoleQuantity.Unit); - - var decigrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.DecigramPerMole); - AssertEx.EqualTolerance(DecigramsPerMoleInOneKilogramPerMole, (double)decigrampermoleQuantity.Value, DecigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecigramPerMole, decigrampermoleQuantity.Unit); - - var grampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.GramPerMole); - AssertEx.EqualTolerance(GramsPerMoleInOneKilogramPerMole, (double)grampermoleQuantity.Value, GramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.GramPerMole, grampermoleQuantity.Unit); - - var hectogrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.HectogramPerMole); - AssertEx.EqualTolerance(HectogramsPerMoleInOneKilogramPerMole, (double)hectogrampermoleQuantity.Value, HectogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.HectogramPerMole, hectogrampermoleQuantity.Unit); - - var kilogrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.KilogramPerMole); - AssertEx.EqualTolerance(KilogramsPerMoleInOneKilogramPerMole, (double)kilogrampermoleQuantity.Value, KilogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilogramPerMole, kilogrampermoleQuantity.Unit); + var inBaseUnits = MolarMass.From(1.0, MolarMass.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilopoundpermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.KilopoundPerMole); - AssertEx.EqualTolerance(KilopoundsPerMoleInOneKilogramPerMole, (double)kilopoundpermoleQuantity.Value, KilopoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilopoundPerMole, kilopoundpermoleQuantity.Unit); - - var megapoundpermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.MegapoundPerMole); - AssertEx.EqualTolerance(MegapoundsPerMoleInOneKilogramPerMole, (double)megapoundpermoleQuantity.Value, MegapoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MegapoundPerMole, megapoundpermoleQuantity.Unit); - - var microgrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.MicrogramPerMole); - AssertEx.EqualTolerance(MicrogramsPerMoleInOneKilogramPerMole, (double)microgrampermoleQuantity.Value, MicrogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MicrogramPerMole, microgrampermoleQuantity.Unit); - - var milligrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.MilligramPerMole); - AssertEx.EqualTolerance(MilligramsPerMoleInOneKilogramPerMole, (double)milligrampermoleQuantity.Value, MilligramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MilligramPerMole, milligrampermoleQuantity.Unit); - - var nanogrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.NanogramPerMole); - AssertEx.EqualTolerance(NanogramsPerMoleInOneKilogramPerMole, (double)nanogrampermoleQuantity.Value, NanogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.NanogramPerMole, nanogrampermoleQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var poundpermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.PoundPerMole); - AssertEx.EqualTolerance(PoundsPerMoleInOneKilogramPerMole, (double)poundpermoleQuantity.Value, PoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.PoundPerMole, poundpermoleQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MolarMassUnit unit) + { + var quantity = MolarMass.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarMassUnit unit) { - var quantityInBaseUnit = MolarMass.FromKilogramsPerMole(1).ToBaseUnit(); - Assert.Equal(MolarMass.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = MolarMass.Units.FirstOrDefault(u => u != MolarMass.BaseUnit && u != MolarMassUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MolarMassUnit.Undefined) + fromUnit = MolarMass.BaseUnit; + + var quantity = MolarMass.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs index 5e77ce6c5d..f0592f4211 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -57,6 +58,34 @@ public abstract partial class MolarityTestsBase : QuantityTestsBase protected virtual double PicomolesPerLiterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MolarityUnit unit) + { + return unit switch + { + MolarityUnit.CentimolesPerLiter => (CentimolesPerLiterInOneMolesPerCubicMeter, CentimolesPerLiterTolerance), + MolarityUnit.DecimolesPerLiter => (DecimolesPerLiterInOneMolesPerCubicMeter, DecimolesPerLiterTolerance), + MolarityUnit.MicromolesPerLiter => (MicromolesPerLiterInOneMolesPerCubicMeter, MicromolesPerLiterTolerance), + MolarityUnit.MillimolesPerLiter => (MillimolesPerLiterInOneMolesPerCubicMeter, MillimolesPerLiterTolerance), + MolarityUnit.MolesPerCubicMeter => (MolesPerCubicMeterInOneMolesPerCubicMeter, MolesPerCubicMeterTolerance), + MolarityUnit.MolesPerLiter => (MolesPerLiterInOneMolesPerCubicMeter, MolesPerLiterTolerance), + MolarityUnit.NanomolesPerLiter => (NanomolesPerLiterInOneMolesPerCubicMeter, NanomolesPerLiterTolerance), + MolarityUnit.PicomolesPerLiter => (PicomolesPerLiterInOneMolesPerCubicMeter, PicomolesPerLiterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { MolarityUnit.CentimolesPerLiter }, + new object[] { MolarityUnit.DecimolesPerLiter }, + new object[] { MolarityUnit.MicromolesPerLiter }, + new object[] { MolarityUnit.MillimolesPerLiter }, + new object[] { MolarityUnit.MolesPerCubicMeter }, + new object[] { MolarityUnit.MolesPerLiter }, + new object[] { MolarityUnit.NanomolesPerLiter }, + new object[] { MolarityUnit.PicomolesPerLiter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -220,49 +249,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(MolarityUnit unit) { - var molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - - var centimolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.CentimolesPerLiter); - AssertEx.EqualTolerance(CentimolesPerLiterInOneMolesPerCubicMeter, (double)centimolesperliterQuantity.Value, CentimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.CentimolesPerLiter, centimolesperliterQuantity.Unit); - - var decimolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.DecimolesPerLiter); - AssertEx.EqualTolerance(DecimolesPerLiterInOneMolesPerCubicMeter, (double)decimolesperliterQuantity.Value, DecimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.DecimolesPerLiter, decimolesperliterQuantity.Unit); - - var micromolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.MicromolesPerLiter); - AssertEx.EqualTolerance(MicromolesPerLiterInOneMolesPerCubicMeter, (double)micromolesperliterQuantity.Value, MicromolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MicromolesPerLiter, micromolesperliterQuantity.Unit); - - var millimolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.MillimolesPerLiter); - AssertEx.EqualTolerance(MillimolesPerLiterInOneMolesPerCubicMeter, (double)millimolesperliterQuantity.Value, MillimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MillimolesPerLiter, millimolesperliterQuantity.Unit); + var inBaseUnits = Molarity.From(1.0, Molarity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var molespercubicmeterQuantity = molespercubicmeter.ToUnit(MolarityUnit.MolesPerCubicMeter); - AssertEx.EqualTolerance(MolesPerCubicMeterInOneMolesPerCubicMeter, (double)molespercubicmeterQuantity.Value, MolesPerCubicMeterTolerance); - Assert.Equal(MolarityUnit.MolesPerCubicMeter, molespercubicmeterQuantity.Unit); - - var molesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.MolesPerLiter); - AssertEx.EqualTolerance(MolesPerLiterInOneMolesPerCubicMeter, (double)molesperliterQuantity.Value, MolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MolesPerLiter, molesperliterQuantity.Unit); - - var nanomolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.NanomolesPerLiter); - AssertEx.EqualTolerance(NanomolesPerLiterInOneMolesPerCubicMeter, (double)nanomolesperliterQuantity.Value, NanomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.NanomolesPerLiter, nanomolesperliterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var picomolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.PicomolesPerLiter); - AssertEx.EqualTolerance(PicomolesPerLiterInOneMolesPerCubicMeter, (double)picomolesperliterQuantity.Value, PicomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.PicomolesPerLiter, picomolesperliterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(MolarityUnit unit) + { + var quantity = Molarity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarityUnit unit) { - var quantityInBaseUnit = Molarity.FromMolesPerCubicMeter(1).ToBaseUnit(); - Assert.Equal(Molarity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Molarity.Units.FirstOrDefault(u => u != Molarity.BaseUnit && u != MolarityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == MolarityUnit.Undefined) + fromUnit = Molarity.BaseUnit; + + var quantity = Molarity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs index 2cd5d7c69e..bfc744d102 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class PermeabilityTestsBase : QuantityTestsBase protected virtual double HenriesPerMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PermeabilityUnit unit) + { + return unit switch + { + PermeabilityUnit.HenryPerMeter => (HenriesPerMeterInOneHenryPerMeter, HenriesPerMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { PermeabilityUnit.HenryPerMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(PermeabilityUnit unit) { - var henrypermeter = Permeability.FromHenriesPerMeter(1); + var inBaseUnits = Permeability.From(1.0, Permeability.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var henrypermeterQuantity = henrypermeter.ToUnit(PermeabilityUnit.HenryPerMeter); - AssertEx.EqualTolerance(HenriesPerMeterInOneHenryPerMeter, (double)henrypermeterQuantity.Value, HenriesPerMeterTolerance); - Assert.Equal(PermeabilityUnit.HenryPerMeter, henrypermeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(PermeabilityUnit unit) + { + var quantity = Permeability.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PermeabilityUnit unit) { - var quantityInBaseUnit = Permeability.FromHenriesPerMeter(1).ToBaseUnit(); - Assert.Equal(Permeability.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Permeability.Units.FirstOrDefault(u => u != Permeability.BaseUnit && u != PermeabilityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == PermeabilityUnit.Undefined) + fromUnit = Permeability.BaseUnit; + + var quantity = Permeability.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs index d42b94bb7b..553dc76b6c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class PermittivityTestsBase : QuantityTestsBase protected virtual double FaradsPerMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PermittivityUnit unit) + { + return unit switch + { + PermittivityUnit.FaradPerMeter => (FaradsPerMeterInOneFaradPerMeter, FaradsPerMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { PermittivityUnit.FaradPerMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(PermittivityUnit unit) { - var faradpermeter = Permittivity.FromFaradsPerMeter(1); + var inBaseUnits = Permittivity.From(1.0, Permittivity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var faradpermeterQuantity = faradpermeter.ToUnit(PermittivityUnit.FaradPerMeter); - AssertEx.EqualTolerance(FaradsPerMeterInOneFaradPerMeter, (double)faradpermeterQuantity.Value, FaradsPerMeterTolerance); - Assert.Equal(PermittivityUnit.FaradPerMeter, faradpermeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(PermittivityUnit unit) + { + var quantity = Permittivity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PermittivityUnit unit) { - var quantityInBaseUnit = Permittivity.FromFaradsPerMeter(1).ToBaseUnit(); - Assert.Equal(Permittivity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Permittivity.Units.FirstOrDefault(u => u != Permittivity.BaseUnit && u != PermittivityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == PermittivityUnit.Undefined) + fromUnit = Permittivity.BaseUnit; + + var quantity = Permittivity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs index fe43ad30c0..5a479b3bc7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -129,6 +130,106 @@ public abstract partial class PowerDensityTestsBase : QuantityTestsBase protected virtual double WattsPerLiterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PowerDensityUnit unit) + { + return unit switch + { + PowerDensityUnit.DecawattPerCubicFoot => (DecawattsPerCubicFootInOneWattPerCubicMeter, DecawattsPerCubicFootTolerance), + PowerDensityUnit.DecawattPerCubicInch => (DecawattsPerCubicInchInOneWattPerCubicMeter, DecawattsPerCubicInchTolerance), + PowerDensityUnit.DecawattPerCubicMeter => (DecawattsPerCubicMeterInOneWattPerCubicMeter, DecawattsPerCubicMeterTolerance), + PowerDensityUnit.DecawattPerLiter => (DecawattsPerLiterInOneWattPerCubicMeter, DecawattsPerLiterTolerance), + PowerDensityUnit.DeciwattPerCubicFoot => (DeciwattsPerCubicFootInOneWattPerCubicMeter, DeciwattsPerCubicFootTolerance), + PowerDensityUnit.DeciwattPerCubicInch => (DeciwattsPerCubicInchInOneWattPerCubicMeter, DeciwattsPerCubicInchTolerance), + PowerDensityUnit.DeciwattPerCubicMeter => (DeciwattsPerCubicMeterInOneWattPerCubicMeter, DeciwattsPerCubicMeterTolerance), + PowerDensityUnit.DeciwattPerLiter => (DeciwattsPerLiterInOneWattPerCubicMeter, DeciwattsPerLiterTolerance), + PowerDensityUnit.GigawattPerCubicFoot => (GigawattsPerCubicFootInOneWattPerCubicMeter, GigawattsPerCubicFootTolerance), + PowerDensityUnit.GigawattPerCubicInch => (GigawattsPerCubicInchInOneWattPerCubicMeter, GigawattsPerCubicInchTolerance), + PowerDensityUnit.GigawattPerCubicMeter => (GigawattsPerCubicMeterInOneWattPerCubicMeter, GigawattsPerCubicMeterTolerance), + PowerDensityUnit.GigawattPerLiter => (GigawattsPerLiterInOneWattPerCubicMeter, GigawattsPerLiterTolerance), + PowerDensityUnit.KilowattPerCubicFoot => (KilowattsPerCubicFootInOneWattPerCubicMeter, KilowattsPerCubicFootTolerance), + PowerDensityUnit.KilowattPerCubicInch => (KilowattsPerCubicInchInOneWattPerCubicMeter, KilowattsPerCubicInchTolerance), + PowerDensityUnit.KilowattPerCubicMeter => (KilowattsPerCubicMeterInOneWattPerCubicMeter, KilowattsPerCubicMeterTolerance), + PowerDensityUnit.KilowattPerLiter => (KilowattsPerLiterInOneWattPerCubicMeter, KilowattsPerLiterTolerance), + PowerDensityUnit.MegawattPerCubicFoot => (MegawattsPerCubicFootInOneWattPerCubicMeter, MegawattsPerCubicFootTolerance), + PowerDensityUnit.MegawattPerCubicInch => (MegawattsPerCubicInchInOneWattPerCubicMeter, MegawattsPerCubicInchTolerance), + PowerDensityUnit.MegawattPerCubicMeter => (MegawattsPerCubicMeterInOneWattPerCubicMeter, MegawattsPerCubicMeterTolerance), + PowerDensityUnit.MegawattPerLiter => (MegawattsPerLiterInOneWattPerCubicMeter, MegawattsPerLiterTolerance), + PowerDensityUnit.MicrowattPerCubicFoot => (MicrowattsPerCubicFootInOneWattPerCubicMeter, MicrowattsPerCubicFootTolerance), + PowerDensityUnit.MicrowattPerCubicInch => (MicrowattsPerCubicInchInOneWattPerCubicMeter, MicrowattsPerCubicInchTolerance), + PowerDensityUnit.MicrowattPerCubicMeter => (MicrowattsPerCubicMeterInOneWattPerCubicMeter, MicrowattsPerCubicMeterTolerance), + PowerDensityUnit.MicrowattPerLiter => (MicrowattsPerLiterInOneWattPerCubicMeter, MicrowattsPerLiterTolerance), + PowerDensityUnit.MilliwattPerCubicFoot => (MilliwattsPerCubicFootInOneWattPerCubicMeter, MilliwattsPerCubicFootTolerance), + PowerDensityUnit.MilliwattPerCubicInch => (MilliwattsPerCubicInchInOneWattPerCubicMeter, MilliwattsPerCubicInchTolerance), + PowerDensityUnit.MilliwattPerCubicMeter => (MilliwattsPerCubicMeterInOneWattPerCubicMeter, MilliwattsPerCubicMeterTolerance), + PowerDensityUnit.MilliwattPerLiter => (MilliwattsPerLiterInOneWattPerCubicMeter, MilliwattsPerLiterTolerance), + PowerDensityUnit.NanowattPerCubicFoot => (NanowattsPerCubicFootInOneWattPerCubicMeter, NanowattsPerCubicFootTolerance), + PowerDensityUnit.NanowattPerCubicInch => (NanowattsPerCubicInchInOneWattPerCubicMeter, NanowattsPerCubicInchTolerance), + PowerDensityUnit.NanowattPerCubicMeter => (NanowattsPerCubicMeterInOneWattPerCubicMeter, NanowattsPerCubicMeterTolerance), + PowerDensityUnit.NanowattPerLiter => (NanowattsPerLiterInOneWattPerCubicMeter, NanowattsPerLiterTolerance), + PowerDensityUnit.PicowattPerCubicFoot => (PicowattsPerCubicFootInOneWattPerCubicMeter, PicowattsPerCubicFootTolerance), + PowerDensityUnit.PicowattPerCubicInch => (PicowattsPerCubicInchInOneWattPerCubicMeter, PicowattsPerCubicInchTolerance), + PowerDensityUnit.PicowattPerCubicMeter => (PicowattsPerCubicMeterInOneWattPerCubicMeter, PicowattsPerCubicMeterTolerance), + PowerDensityUnit.PicowattPerLiter => (PicowattsPerLiterInOneWattPerCubicMeter, PicowattsPerLiterTolerance), + PowerDensityUnit.TerawattPerCubicFoot => (TerawattsPerCubicFootInOneWattPerCubicMeter, TerawattsPerCubicFootTolerance), + PowerDensityUnit.TerawattPerCubicInch => (TerawattsPerCubicInchInOneWattPerCubicMeter, TerawattsPerCubicInchTolerance), + PowerDensityUnit.TerawattPerCubicMeter => (TerawattsPerCubicMeterInOneWattPerCubicMeter, TerawattsPerCubicMeterTolerance), + PowerDensityUnit.TerawattPerLiter => (TerawattsPerLiterInOneWattPerCubicMeter, TerawattsPerLiterTolerance), + PowerDensityUnit.WattPerCubicFoot => (WattsPerCubicFootInOneWattPerCubicMeter, WattsPerCubicFootTolerance), + PowerDensityUnit.WattPerCubicInch => (WattsPerCubicInchInOneWattPerCubicMeter, WattsPerCubicInchTolerance), + PowerDensityUnit.WattPerCubicMeter => (WattsPerCubicMeterInOneWattPerCubicMeter, WattsPerCubicMeterTolerance), + PowerDensityUnit.WattPerLiter => (WattsPerLiterInOneWattPerCubicMeter, WattsPerLiterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { PowerDensityUnit.DecawattPerCubicFoot }, + new object[] { PowerDensityUnit.DecawattPerCubicInch }, + new object[] { PowerDensityUnit.DecawattPerCubicMeter }, + new object[] { PowerDensityUnit.DecawattPerLiter }, + new object[] { PowerDensityUnit.DeciwattPerCubicFoot }, + new object[] { PowerDensityUnit.DeciwattPerCubicInch }, + new object[] { PowerDensityUnit.DeciwattPerCubicMeter }, + new object[] { PowerDensityUnit.DeciwattPerLiter }, + new object[] { PowerDensityUnit.GigawattPerCubicFoot }, + new object[] { PowerDensityUnit.GigawattPerCubicInch }, + new object[] { PowerDensityUnit.GigawattPerCubicMeter }, + new object[] { PowerDensityUnit.GigawattPerLiter }, + new object[] { PowerDensityUnit.KilowattPerCubicFoot }, + new object[] { PowerDensityUnit.KilowattPerCubicInch }, + new object[] { PowerDensityUnit.KilowattPerCubicMeter }, + new object[] { PowerDensityUnit.KilowattPerLiter }, + new object[] { PowerDensityUnit.MegawattPerCubicFoot }, + new object[] { PowerDensityUnit.MegawattPerCubicInch }, + new object[] { PowerDensityUnit.MegawattPerCubicMeter }, + new object[] { PowerDensityUnit.MegawattPerLiter }, + new object[] { PowerDensityUnit.MicrowattPerCubicFoot }, + new object[] { PowerDensityUnit.MicrowattPerCubicInch }, + new object[] { PowerDensityUnit.MicrowattPerCubicMeter }, + new object[] { PowerDensityUnit.MicrowattPerLiter }, + new object[] { PowerDensityUnit.MilliwattPerCubicFoot }, + new object[] { PowerDensityUnit.MilliwattPerCubicInch }, + new object[] { PowerDensityUnit.MilliwattPerCubicMeter }, + new object[] { PowerDensityUnit.MilliwattPerLiter }, + new object[] { PowerDensityUnit.NanowattPerCubicFoot }, + new object[] { PowerDensityUnit.NanowattPerCubicInch }, + new object[] { PowerDensityUnit.NanowattPerCubicMeter }, + new object[] { PowerDensityUnit.NanowattPerLiter }, + new object[] { PowerDensityUnit.PicowattPerCubicFoot }, + new object[] { PowerDensityUnit.PicowattPerCubicInch }, + new object[] { PowerDensityUnit.PicowattPerCubicMeter }, + new object[] { PowerDensityUnit.PicowattPerLiter }, + new object[] { PowerDensityUnit.TerawattPerCubicFoot }, + new object[] { PowerDensityUnit.TerawattPerCubicInch }, + new object[] { PowerDensityUnit.TerawattPerCubicMeter }, + new object[] { PowerDensityUnit.TerawattPerLiter }, + new object[] { PowerDensityUnit.WattPerCubicFoot }, + new object[] { PowerDensityUnit.WattPerCubicInch }, + new object[] { PowerDensityUnit.WattPerCubicMeter }, + new object[] { PowerDensityUnit.WattPerLiter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -508,193 +609,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(PowerDensityUnit unit) { - var wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - - var decawattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DecawattPerCubicFoot); - AssertEx.EqualTolerance(DecawattsPerCubicFootInOneWattPerCubicMeter, (double)decawattpercubicfootQuantity.Value, DecawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicFoot, decawattpercubicfootQuantity.Unit); - - var decawattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DecawattPerCubicInch); - AssertEx.EqualTolerance(DecawattsPerCubicInchInOneWattPerCubicMeter, (double)decawattpercubicinchQuantity.Value, DecawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicInch, decawattpercubicinchQuantity.Unit); - - var decawattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DecawattPerCubicMeter); - AssertEx.EqualTolerance(DecawattsPerCubicMeterInOneWattPerCubicMeter, (double)decawattpercubicmeterQuantity.Value, DecawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicMeter, decawattpercubicmeterQuantity.Unit); - - var decawattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DecawattPerLiter); - AssertEx.EqualTolerance(DecawattsPerLiterInOneWattPerCubicMeter, (double)decawattperliterQuantity.Value, DecawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerLiter, decawattperliterQuantity.Unit); - - var deciwattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DeciwattPerCubicFoot); - AssertEx.EqualTolerance(DeciwattsPerCubicFootInOneWattPerCubicMeter, (double)deciwattpercubicfootQuantity.Value, DeciwattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicFoot, deciwattpercubicfootQuantity.Unit); - - var deciwattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DeciwattPerCubicInch); - AssertEx.EqualTolerance(DeciwattsPerCubicInchInOneWattPerCubicMeter, (double)deciwattpercubicinchQuantity.Value, DeciwattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicInch, deciwattpercubicinchQuantity.Unit); - - var deciwattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DeciwattPerCubicMeter); - AssertEx.EqualTolerance(DeciwattsPerCubicMeterInOneWattPerCubicMeter, (double)deciwattpercubicmeterQuantity.Value, DeciwattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicMeter, deciwattpercubicmeterQuantity.Unit); - - var deciwattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DeciwattPerLiter); - AssertEx.EqualTolerance(DeciwattsPerLiterInOneWattPerCubicMeter, (double)deciwattperliterQuantity.Value, DeciwattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerLiter, deciwattperliterQuantity.Unit); - - var gigawattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.GigawattPerCubicFoot); - AssertEx.EqualTolerance(GigawattsPerCubicFootInOneWattPerCubicMeter, (double)gigawattpercubicfootQuantity.Value, GigawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicFoot, gigawattpercubicfootQuantity.Unit); - - var gigawattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.GigawattPerCubicInch); - AssertEx.EqualTolerance(GigawattsPerCubicInchInOneWattPerCubicMeter, (double)gigawattpercubicinchQuantity.Value, GigawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicInch, gigawattpercubicinchQuantity.Unit); - - var gigawattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.GigawattPerCubicMeter); - AssertEx.EqualTolerance(GigawattsPerCubicMeterInOneWattPerCubicMeter, (double)gigawattpercubicmeterQuantity.Value, GigawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicMeter, gigawattpercubicmeterQuantity.Unit); - - var gigawattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.GigawattPerLiter); - AssertEx.EqualTolerance(GigawattsPerLiterInOneWattPerCubicMeter, (double)gigawattperliterQuantity.Value, GigawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerLiter, gigawattperliterQuantity.Unit); - - var kilowattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.KilowattPerCubicFoot); - AssertEx.EqualTolerance(KilowattsPerCubicFootInOneWattPerCubicMeter, (double)kilowattpercubicfootQuantity.Value, KilowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicFoot, kilowattpercubicfootQuantity.Unit); - - var kilowattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.KilowattPerCubicInch); - AssertEx.EqualTolerance(KilowattsPerCubicInchInOneWattPerCubicMeter, (double)kilowattpercubicinchQuantity.Value, KilowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicInch, kilowattpercubicinchQuantity.Unit); - - var kilowattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.KilowattPerCubicMeter); - AssertEx.EqualTolerance(KilowattsPerCubicMeterInOneWattPerCubicMeter, (double)kilowattpercubicmeterQuantity.Value, KilowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicMeter, kilowattpercubicmeterQuantity.Unit); - - var kilowattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.KilowattPerLiter); - AssertEx.EqualTolerance(KilowattsPerLiterInOneWattPerCubicMeter, (double)kilowattperliterQuantity.Value, KilowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerLiter, kilowattperliterQuantity.Unit); - - var megawattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MegawattPerCubicFoot); - AssertEx.EqualTolerance(MegawattsPerCubicFootInOneWattPerCubicMeter, (double)megawattpercubicfootQuantity.Value, MegawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerCubicFoot, megawattpercubicfootQuantity.Unit); - - var megawattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MegawattPerCubicInch); - AssertEx.EqualTolerance(MegawattsPerCubicInchInOneWattPerCubicMeter, (double)megawattpercubicinchQuantity.Value, MegawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerCubicInch, megawattpercubicinchQuantity.Unit); - - var megawattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MegawattPerCubicMeter); - AssertEx.EqualTolerance(MegawattsPerCubicMeterInOneWattPerCubicMeter, (double)megawattpercubicmeterQuantity.Value, MegawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerCubicMeter, megawattpercubicmeterQuantity.Unit); - - var megawattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MegawattPerLiter); - AssertEx.EqualTolerance(MegawattsPerLiterInOneWattPerCubicMeter, (double)megawattperliterQuantity.Value, MegawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerLiter, megawattperliterQuantity.Unit); + var inBaseUnits = PowerDensity.From(1.0, PowerDensity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var microwattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MicrowattPerCubicFoot); - AssertEx.EqualTolerance(MicrowattsPerCubicFootInOneWattPerCubicMeter, (double)microwattpercubicfootQuantity.Value, MicrowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicFoot, microwattpercubicfootQuantity.Unit); - - var microwattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MicrowattPerCubicInch); - AssertEx.EqualTolerance(MicrowattsPerCubicInchInOneWattPerCubicMeter, (double)microwattpercubicinchQuantity.Value, MicrowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicInch, microwattpercubicinchQuantity.Unit); - - var microwattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MicrowattPerCubicMeter); - AssertEx.EqualTolerance(MicrowattsPerCubicMeterInOneWattPerCubicMeter, (double)microwattpercubicmeterQuantity.Value, MicrowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicMeter, microwattpercubicmeterQuantity.Unit); - - var microwattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MicrowattPerLiter); - AssertEx.EqualTolerance(MicrowattsPerLiterInOneWattPerCubicMeter, (double)microwattperliterQuantity.Value, MicrowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerLiter, microwattperliterQuantity.Unit); - - var milliwattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MilliwattPerCubicFoot); - AssertEx.EqualTolerance(MilliwattsPerCubicFootInOneWattPerCubicMeter, (double)milliwattpercubicfootQuantity.Value, MilliwattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerCubicFoot, milliwattpercubicfootQuantity.Unit); - - var milliwattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MilliwattPerCubicInch); - AssertEx.EqualTolerance(MilliwattsPerCubicInchInOneWattPerCubicMeter, (double)milliwattpercubicinchQuantity.Value, MilliwattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerCubicInch, milliwattpercubicinchQuantity.Unit); - - var milliwattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MilliwattPerCubicMeter); - AssertEx.EqualTolerance(MilliwattsPerCubicMeterInOneWattPerCubicMeter, (double)milliwattpercubicmeterQuantity.Value, MilliwattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerCubicMeter, milliwattpercubicmeterQuantity.Unit); - - var milliwattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MilliwattPerLiter); - AssertEx.EqualTolerance(MilliwattsPerLiterInOneWattPerCubicMeter, (double)milliwattperliterQuantity.Value, MilliwattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerLiter, milliwattperliterQuantity.Unit); - - var nanowattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.NanowattPerCubicFoot); - AssertEx.EqualTolerance(NanowattsPerCubicFootInOneWattPerCubicMeter, (double)nanowattpercubicfootQuantity.Value, NanowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicFoot, nanowattpercubicfootQuantity.Unit); - - var nanowattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.NanowattPerCubicInch); - AssertEx.EqualTolerance(NanowattsPerCubicInchInOneWattPerCubicMeter, (double)nanowattpercubicinchQuantity.Value, NanowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicInch, nanowattpercubicinchQuantity.Unit); - - var nanowattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.NanowattPerCubicMeter); - AssertEx.EqualTolerance(NanowattsPerCubicMeterInOneWattPerCubicMeter, (double)nanowattpercubicmeterQuantity.Value, NanowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicMeter, nanowattpercubicmeterQuantity.Unit); - - var nanowattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.NanowattPerLiter); - AssertEx.EqualTolerance(NanowattsPerLiterInOneWattPerCubicMeter, (double)nanowattperliterQuantity.Value, NanowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerLiter, nanowattperliterQuantity.Unit); - - var picowattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.PicowattPerCubicFoot); - AssertEx.EqualTolerance(PicowattsPerCubicFootInOneWattPerCubicMeter, (double)picowattpercubicfootQuantity.Value, PicowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicFoot, picowattpercubicfootQuantity.Unit); - - var picowattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.PicowattPerCubicInch); - AssertEx.EqualTolerance(PicowattsPerCubicInchInOneWattPerCubicMeter, (double)picowattpercubicinchQuantity.Value, PicowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicInch, picowattpercubicinchQuantity.Unit); - - var picowattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.PicowattPerCubicMeter); - AssertEx.EqualTolerance(PicowattsPerCubicMeterInOneWattPerCubicMeter, (double)picowattpercubicmeterQuantity.Value, PicowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicMeter, picowattpercubicmeterQuantity.Unit); - - var picowattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.PicowattPerLiter); - AssertEx.EqualTolerance(PicowattsPerLiterInOneWattPerCubicMeter, (double)picowattperliterQuantity.Value, PicowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerLiter, picowattperliterQuantity.Unit); - - var terawattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.TerawattPerCubicFoot); - AssertEx.EqualTolerance(TerawattsPerCubicFootInOneWattPerCubicMeter, (double)terawattpercubicfootQuantity.Value, TerawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicFoot, terawattpercubicfootQuantity.Unit); - - var terawattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.TerawattPerCubicInch); - AssertEx.EqualTolerance(TerawattsPerCubicInchInOneWattPerCubicMeter, (double)terawattpercubicinchQuantity.Value, TerawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicInch, terawattpercubicinchQuantity.Unit); - - var terawattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.TerawattPerCubicMeter); - AssertEx.EqualTolerance(TerawattsPerCubicMeterInOneWattPerCubicMeter, (double)terawattpercubicmeterQuantity.Value, TerawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicMeter, terawattpercubicmeterQuantity.Unit); - - var terawattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.TerawattPerLiter); - AssertEx.EqualTolerance(TerawattsPerLiterInOneWattPerCubicMeter, (double)terawattperliterQuantity.Value, TerawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerLiter, terawattperliterQuantity.Unit); - - var wattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.WattPerCubicFoot); - AssertEx.EqualTolerance(WattsPerCubicFootInOneWattPerCubicMeter, (double)wattpercubicfootQuantity.Value, WattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicFoot, wattpercubicfootQuantity.Unit); - - var wattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.WattPerCubicInch); - AssertEx.EqualTolerance(WattsPerCubicInchInOneWattPerCubicMeter, (double)wattpercubicinchQuantity.Value, WattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicInch, wattpercubicinchQuantity.Unit); - - var wattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.WattPerCubicMeter); - AssertEx.EqualTolerance(WattsPerCubicMeterInOneWattPerCubicMeter, (double)wattpercubicmeterQuantity.Value, WattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicMeter, wattpercubicmeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var wattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.WattPerLiter); - AssertEx.EqualTolerance(WattsPerLiterInOneWattPerCubicMeter, (double)wattperliterQuantity.Value, WattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.WattPerLiter, wattperliterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(PowerDensityUnit unit) + { + var quantity = PowerDensity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerDensityUnit unit) { - var quantityInBaseUnit = PowerDensity.FromWattsPerCubicMeter(1).ToBaseUnit(); - Assert.Equal(PowerDensity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = PowerDensity.Units.FirstOrDefault(u => u != PowerDensity.BaseUnit && u != PowerDensityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == PowerDensityUnit.Undefined) + fromUnit = PowerDensity.BaseUnit; + + var quantity = PowerDensity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs index 2468327188..2105344f09 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -45,6 +46,22 @@ public abstract partial class PowerRatioTestsBase : QuantityTestsBase protected virtual double DecibelWattsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PowerRatioUnit unit) + { + return unit switch + { + PowerRatioUnit.DecibelMilliwatt => (DecibelMilliwattsInOneDecibelWatt, DecibelMilliwattsTolerance), + PowerRatioUnit.DecibelWatt => (DecibelWattsInOneDecibelWatt, DecibelWattsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { PowerRatioUnit.DecibelMilliwatt }, + new object[] { PowerRatioUnit.DecibelWatt }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -172,25 +189,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(PowerRatioUnit unit) { - var decibelwatt = PowerRatio.FromDecibelWatts(1); + var inBaseUnits = PowerRatio.From(1.0, PowerRatio.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var decibelmilliwattQuantity = decibelwatt.ToUnit(PowerRatioUnit.DecibelMilliwatt); - AssertEx.EqualTolerance(DecibelMilliwattsInOneDecibelWatt, (double)decibelmilliwattQuantity.Value, DecibelMilliwattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelMilliwatt, decibelmilliwattQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var decibelwattQuantity = decibelwatt.ToUnit(PowerRatioUnit.DecibelWatt); - AssertEx.EqualTolerance(DecibelWattsInOneDecibelWatt, (double)decibelwattQuantity.Value, DecibelWattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelWatt, decibelwattQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(PowerRatioUnit unit) + { + var quantity = PowerRatio.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerRatioUnit unit) { - var quantityInBaseUnit = PowerRatio.FromDecibelWatts(1).ToBaseUnit(); - Assert.Equal(PowerRatio.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = PowerRatio.Units.FirstOrDefault(u => u != PowerRatio.BaseUnit && u != PowerRatioUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == PowerRatioUnit.Undefined) + fromUnit = PowerRatio.BaseUnit; + + var quantity = PowerRatio.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs index 234c3c9f09..7dcfd7a6a4 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -91,6 +92,68 @@ public abstract partial class PowerTestsBase : QuantityTestsBase protected virtual double WattsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PowerUnit unit) + { + return unit switch + { + PowerUnit.BoilerHorsepower => (BoilerHorsepowerInOneWatt, BoilerHorsepowerTolerance), + PowerUnit.BritishThermalUnitPerHour => (BritishThermalUnitsPerHourInOneWatt, BritishThermalUnitsPerHourTolerance), + PowerUnit.Decawatt => (DecawattsInOneWatt, DecawattsTolerance), + PowerUnit.Deciwatt => (DeciwattsInOneWatt, DeciwattsTolerance), + PowerUnit.ElectricalHorsepower => (ElectricalHorsepowerInOneWatt, ElectricalHorsepowerTolerance), + PowerUnit.Femtowatt => (FemtowattsInOneWatt, FemtowattsTolerance), + PowerUnit.GigajoulePerHour => (GigajoulesPerHourInOneWatt, GigajoulesPerHourTolerance), + PowerUnit.Gigawatt => (GigawattsInOneWatt, GigawattsTolerance), + PowerUnit.HydraulicHorsepower => (HydraulicHorsepowerInOneWatt, HydraulicHorsepowerTolerance), + PowerUnit.JoulePerHour => (JoulesPerHourInOneWatt, JoulesPerHourTolerance), + PowerUnit.KilobritishThermalUnitPerHour => (KilobritishThermalUnitsPerHourInOneWatt, KilobritishThermalUnitsPerHourTolerance), + PowerUnit.KilojoulePerHour => (KilojoulesPerHourInOneWatt, KilojoulesPerHourTolerance), + PowerUnit.Kilowatt => (KilowattsInOneWatt, KilowattsTolerance), + PowerUnit.MechanicalHorsepower => (MechanicalHorsepowerInOneWatt, MechanicalHorsepowerTolerance), + PowerUnit.MegajoulePerHour => (MegajoulesPerHourInOneWatt, MegajoulesPerHourTolerance), + PowerUnit.Megawatt => (MegawattsInOneWatt, MegawattsTolerance), + PowerUnit.MetricHorsepower => (MetricHorsepowerInOneWatt, MetricHorsepowerTolerance), + PowerUnit.Microwatt => (MicrowattsInOneWatt, MicrowattsTolerance), + PowerUnit.MillijoulePerHour => (MillijoulesPerHourInOneWatt, MillijoulesPerHourTolerance), + PowerUnit.Milliwatt => (MilliwattsInOneWatt, MilliwattsTolerance), + PowerUnit.Nanowatt => (NanowattsInOneWatt, NanowattsTolerance), + PowerUnit.Petawatt => (PetawattsInOneWatt, PetawattsTolerance), + PowerUnit.Picowatt => (PicowattsInOneWatt, PicowattsTolerance), + PowerUnit.Terawatt => (TerawattsInOneWatt, TerawattsTolerance), + PowerUnit.Watt => (WattsInOneWatt, WattsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { PowerUnit.BoilerHorsepower }, + new object[] { PowerUnit.BritishThermalUnitPerHour }, + new object[] { PowerUnit.Decawatt }, + new object[] { PowerUnit.Deciwatt }, + new object[] { PowerUnit.ElectricalHorsepower }, + new object[] { PowerUnit.Femtowatt }, + new object[] { PowerUnit.GigajoulePerHour }, + new object[] { PowerUnit.Gigawatt }, + new object[] { PowerUnit.HydraulicHorsepower }, + new object[] { PowerUnit.JoulePerHour }, + new object[] { PowerUnit.KilobritishThermalUnitPerHour }, + new object[] { PowerUnit.KilojoulePerHour }, + new object[] { PowerUnit.Kilowatt }, + new object[] { PowerUnit.MechanicalHorsepower }, + new object[] { PowerUnit.MegajoulePerHour }, + new object[] { PowerUnit.Megawatt }, + new object[] { PowerUnit.MetricHorsepower }, + new object[] { PowerUnit.Microwatt }, + new object[] { PowerUnit.MillijoulePerHour }, + new object[] { PowerUnit.Milliwatt }, + new object[] { PowerUnit.Nanowatt }, + new object[] { PowerUnit.Petawatt }, + new object[] { PowerUnit.Picowatt }, + new object[] { PowerUnit.Terawatt }, + new object[] { PowerUnit.Watt }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -331,117 +394,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(PowerUnit unit) { - var watt = Power.FromWatts(1); - - var boilerhorsepowerQuantity = watt.ToUnit(PowerUnit.BoilerHorsepower); - AssertEx.EqualTolerance(BoilerHorsepowerInOneWatt, (double)boilerhorsepowerQuantity.Value, BoilerHorsepowerTolerance); - Assert.Equal(PowerUnit.BoilerHorsepower, boilerhorsepowerQuantity.Unit); - - var britishthermalunitperhourQuantity = watt.ToUnit(PowerUnit.BritishThermalUnitPerHour); - AssertEx.EqualTolerance(BritishThermalUnitsPerHourInOneWatt, (double)britishthermalunitperhourQuantity.Value, BritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.BritishThermalUnitPerHour, britishthermalunitperhourQuantity.Unit); - - var decawattQuantity = watt.ToUnit(PowerUnit.Decawatt); - AssertEx.EqualTolerance(DecawattsInOneWatt, (double)decawattQuantity.Value, DecawattsTolerance); - Assert.Equal(PowerUnit.Decawatt, decawattQuantity.Unit); - - var deciwattQuantity = watt.ToUnit(PowerUnit.Deciwatt); - AssertEx.EqualTolerance(DeciwattsInOneWatt, (double)deciwattQuantity.Value, DeciwattsTolerance); - Assert.Equal(PowerUnit.Deciwatt, deciwattQuantity.Unit); - - var electricalhorsepowerQuantity = watt.ToUnit(PowerUnit.ElectricalHorsepower); - AssertEx.EqualTolerance(ElectricalHorsepowerInOneWatt, (double)electricalhorsepowerQuantity.Value, ElectricalHorsepowerTolerance); - Assert.Equal(PowerUnit.ElectricalHorsepower, electricalhorsepowerQuantity.Unit); - - var femtowattQuantity = watt.ToUnit(PowerUnit.Femtowatt); - AssertEx.EqualTolerance(FemtowattsInOneWatt, (double)femtowattQuantity.Value, FemtowattsTolerance); - Assert.Equal(PowerUnit.Femtowatt, femtowattQuantity.Unit); - - var gigajouleperhourQuantity = watt.ToUnit(PowerUnit.GigajoulePerHour); - AssertEx.EqualTolerance(GigajoulesPerHourInOneWatt, (double)gigajouleperhourQuantity.Value, GigajoulesPerHourTolerance); - Assert.Equal(PowerUnit.GigajoulePerHour, gigajouleperhourQuantity.Unit); - - var gigawattQuantity = watt.ToUnit(PowerUnit.Gigawatt); - AssertEx.EqualTolerance(GigawattsInOneWatt, (double)gigawattQuantity.Value, GigawattsTolerance); - Assert.Equal(PowerUnit.Gigawatt, gigawattQuantity.Unit); - - var hydraulichorsepowerQuantity = watt.ToUnit(PowerUnit.HydraulicHorsepower); - AssertEx.EqualTolerance(HydraulicHorsepowerInOneWatt, (double)hydraulichorsepowerQuantity.Value, HydraulicHorsepowerTolerance); - Assert.Equal(PowerUnit.HydraulicHorsepower, hydraulichorsepowerQuantity.Unit); - - var jouleperhourQuantity = watt.ToUnit(PowerUnit.JoulePerHour); - AssertEx.EqualTolerance(JoulesPerHourInOneWatt, (double)jouleperhourQuantity.Value, JoulesPerHourTolerance); - Assert.Equal(PowerUnit.JoulePerHour, jouleperhourQuantity.Unit); - - var kilobritishthermalunitperhourQuantity = watt.ToUnit(PowerUnit.KilobritishThermalUnitPerHour); - AssertEx.EqualTolerance(KilobritishThermalUnitsPerHourInOneWatt, (double)kilobritishthermalunitperhourQuantity.Value, KilobritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.KilobritishThermalUnitPerHour, kilobritishthermalunitperhourQuantity.Unit); - - var kilojouleperhourQuantity = watt.ToUnit(PowerUnit.KilojoulePerHour); - AssertEx.EqualTolerance(KilojoulesPerHourInOneWatt, (double)kilojouleperhourQuantity.Value, KilojoulesPerHourTolerance); - Assert.Equal(PowerUnit.KilojoulePerHour, kilojouleperhourQuantity.Unit); + var inBaseUnits = Power.From(1.0, Power.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilowattQuantity = watt.ToUnit(PowerUnit.Kilowatt); - AssertEx.EqualTolerance(KilowattsInOneWatt, (double)kilowattQuantity.Value, KilowattsTolerance); - Assert.Equal(PowerUnit.Kilowatt, kilowattQuantity.Unit); - - var mechanicalhorsepowerQuantity = watt.ToUnit(PowerUnit.MechanicalHorsepower); - AssertEx.EqualTolerance(MechanicalHorsepowerInOneWatt, (double)mechanicalhorsepowerQuantity.Value, MechanicalHorsepowerTolerance); - Assert.Equal(PowerUnit.MechanicalHorsepower, mechanicalhorsepowerQuantity.Unit); - - var megajouleperhourQuantity = watt.ToUnit(PowerUnit.MegajoulePerHour); - AssertEx.EqualTolerance(MegajoulesPerHourInOneWatt, (double)megajouleperhourQuantity.Value, MegajoulesPerHourTolerance); - Assert.Equal(PowerUnit.MegajoulePerHour, megajouleperhourQuantity.Unit); - - var megawattQuantity = watt.ToUnit(PowerUnit.Megawatt); - AssertEx.EqualTolerance(MegawattsInOneWatt, (double)megawattQuantity.Value, MegawattsTolerance); - Assert.Equal(PowerUnit.Megawatt, megawattQuantity.Unit); - - var metrichorsepowerQuantity = watt.ToUnit(PowerUnit.MetricHorsepower); - AssertEx.EqualTolerance(MetricHorsepowerInOneWatt, (double)metrichorsepowerQuantity.Value, MetricHorsepowerTolerance); - Assert.Equal(PowerUnit.MetricHorsepower, metrichorsepowerQuantity.Unit); - - var microwattQuantity = watt.ToUnit(PowerUnit.Microwatt); - AssertEx.EqualTolerance(MicrowattsInOneWatt, (double)microwattQuantity.Value, MicrowattsTolerance); - Assert.Equal(PowerUnit.Microwatt, microwattQuantity.Unit); - - var millijouleperhourQuantity = watt.ToUnit(PowerUnit.MillijoulePerHour); - AssertEx.EqualTolerance(MillijoulesPerHourInOneWatt, (double)millijouleperhourQuantity.Value, MillijoulesPerHourTolerance); - Assert.Equal(PowerUnit.MillijoulePerHour, millijouleperhourQuantity.Unit); - - var milliwattQuantity = watt.ToUnit(PowerUnit.Milliwatt); - AssertEx.EqualTolerance(MilliwattsInOneWatt, (double)milliwattQuantity.Value, MilliwattsTolerance); - Assert.Equal(PowerUnit.Milliwatt, milliwattQuantity.Unit); - - var nanowattQuantity = watt.ToUnit(PowerUnit.Nanowatt); - AssertEx.EqualTolerance(NanowattsInOneWatt, (double)nanowattQuantity.Value, NanowattsTolerance); - Assert.Equal(PowerUnit.Nanowatt, nanowattQuantity.Unit); - - var petawattQuantity = watt.ToUnit(PowerUnit.Petawatt); - AssertEx.EqualTolerance(PetawattsInOneWatt, (double)petawattQuantity.Value, PetawattsTolerance); - Assert.Equal(PowerUnit.Petawatt, petawattQuantity.Unit); - - var picowattQuantity = watt.ToUnit(PowerUnit.Picowatt); - AssertEx.EqualTolerance(PicowattsInOneWatt, (double)picowattQuantity.Value, PicowattsTolerance); - Assert.Equal(PowerUnit.Picowatt, picowattQuantity.Unit); - - var terawattQuantity = watt.ToUnit(PowerUnit.Terawatt); - AssertEx.EqualTolerance(TerawattsInOneWatt, (double)terawattQuantity.Value, TerawattsTolerance); - Assert.Equal(PowerUnit.Terawatt, terawattQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var wattQuantity = watt.ToUnit(PowerUnit.Watt); - AssertEx.EqualTolerance(WattsInOneWatt, (double)wattQuantity.Value, WattsTolerance); - Assert.Equal(PowerUnit.Watt, wattQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(PowerUnit unit) + { + var quantity = Power.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerUnit unit) { - var quantityInBaseUnit = Power.FromWatts(1).ToBaseUnit(); - Assert.Equal(Power.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Power.Units.FirstOrDefault(u => u != Power.BaseUnit && u != PowerUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == PowerUnit.Undefined) + fromUnit = Power.BaseUnit; + + var quantity = Power.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs index cc9e185838..6a73fa3571 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -69,6 +70,46 @@ public abstract partial class PressureChangeRateTestsBase : QuantityTestsBase protected virtual double PoundsForcePerSquareInchPerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PressureChangeRateUnit unit) + { + return unit switch + { + PressureChangeRateUnit.AtmospherePerSecond => (AtmospheresPerSecondInOnePascalPerSecond, AtmospheresPerSecondTolerance), + PressureChangeRateUnit.KilopascalPerMinute => (KilopascalsPerMinuteInOnePascalPerSecond, KilopascalsPerMinuteTolerance), + PressureChangeRateUnit.KilopascalPerSecond => (KilopascalsPerSecondInOnePascalPerSecond, KilopascalsPerSecondTolerance), + PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute => (KilopoundsForcePerSquareInchPerMinuteInOnePascalPerSecond, KilopoundsForcePerSquareInchPerMinuteTolerance), + PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond => (KilopoundsForcePerSquareInchPerSecondInOnePascalPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance), + PressureChangeRateUnit.MegapascalPerMinute => (MegapascalsPerMinuteInOnePascalPerSecond, MegapascalsPerMinuteTolerance), + PressureChangeRateUnit.MegapascalPerSecond => (MegapascalsPerSecondInOnePascalPerSecond, MegapascalsPerSecondTolerance), + PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute => (MegapoundsForcePerSquareInchPerMinuteInOnePascalPerSecond, MegapoundsForcePerSquareInchPerMinuteTolerance), + PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond => (MegapoundsForcePerSquareInchPerSecondInOnePascalPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance), + PressureChangeRateUnit.MillimeterOfMercuryPerSecond => (MillimetersOfMercuryPerSecondInOnePascalPerSecond, MillimetersOfMercuryPerSecondTolerance), + PressureChangeRateUnit.PascalPerMinute => (PascalsPerMinuteInOnePascalPerSecond, PascalsPerMinuteTolerance), + PressureChangeRateUnit.PascalPerSecond => (PascalsPerSecondInOnePascalPerSecond, PascalsPerSecondTolerance), + PressureChangeRateUnit.PoundForcePerSquareInchPerMinute => (PoundsForcePerSquareInchPerMinuteInOnePascalPerSecond, PoundsForcePerSquareInchPerMinuteTolerance), + PressureChangeRateUnit.PoundForcePerSquareInchPerSecond => (PoundsForcePerSquareInchPerSecondInOnePascalPerSecond, PoundsForcePerSquareInchPerSecondTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { PressureChangeRateUnit.AtmospherePerSecond }, + new object[] { PressureChangeRateUnit.KilopascalPerMinute }, + new object[] { PressureChangeRateUnit.KilopascalPerSecond }, + new object[] { PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute }, + new object[] { PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond }, + new object[] { PressureChangeRateUnit.MegapascalPerMinute }, + new object[] { PressureChangeRateUnit.MegapascalPerSecond }, + new object[] { PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute }, + new object[] { PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond }, + new object[] { PressureChangeRateUnit.MillimeterOfMercuryPerSecond }, + new object[] { PressureChangeRateUnit.PascalPerMinute }, + new object[] { PressureChangeRateUnit.PascalPerSecond }, + new object[] { PressureChangeRateUnit.PoundForcePerSquareInchPerMinute }, + new object[] { PressureChangeRateUnit.PoundForcePerSquareInchPerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -268,73 +309,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(PressureChangeRateUnit unit) { - var pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - - var atmospherepersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.AtmospherePerSecond); - AssertEx.EqualTolerance(AtmospheresPerSecondInOnePascalPerSecond, (double)atmospherepersecondQuantity.Value, AtmospheresPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.AtmospherePerSecond, atmospherepersecondQuantity.Unit); - - var kilopascalperminuteQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.KilopascalPerMinute); - AssertEx.EqualTolerance(KilopascalsPerMinuteInOnePascalPerSecond, (double)kilopascalperminuteQuantity.Value, KilopascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerMinute, kilopascalperminuteQuantity.Unit); - - var kilopascalpersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.KilopascalPerSecond); - AssertEx.EqualTolerance(KilopascalsPerSecondInOnePascalPerSecond, (double)kilopascalpersecondQuantity.Value, KilopascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerSecond, kilopascalpersecondQuantity.Unit); - - var kilopoundforcepersquareinchperminuteQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); - AssertEx.EqualTolerance(KilopoundsForcePerSquareInchPerMinuteInOnePascalPerSecond, (double)kilopoundforcepersquareinchperminuteQuantity.Value, KilopoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, kilopoundforcepersquareinchperminuteQuantity.Unit); - - var kilopoundforcepersquareinchpersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); - AssertEx.EqualTolerance(KilopoundsForcePerSquareInchPerSecondInOnePascalPerSecond, (double)kilopoundforcepersquareinchpersecondQuantity.Value, KilopoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, kilopoundforcepersquareinchpersecondQuantity.Unit); - - var megapascalperminuteQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.MegapascalPerMinute); - AssertEx.EqualTolerance(MegapascalsPerMinuteInOnePascalPerSecond, (double)megapascalperminuteQuantity.Value, MegapascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerMinute, megapascalperminuteQuantity.Unit); - - var megapascalpersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.MegapascalPerSecond); - AssertEx.EqualTolerance(MegapascalsPerSecondInOnePascalPerSecond, (double)megapascalpersecondQuantity.Value, MegapascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerSecond, megapascalpersecondQuantity.Unit); + var inBaseUnits = PressureChangeRate.From(1.0, PressureChangeRate.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var megapoundforcepersquareinchperminuteQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); - AssertEx.EqualTolerance(MegapoundsForcePerSquareInchPerMinuteInOnePascalPerSecond, (double)megapoundforcepersquareinchperminuteQuantity.Value, MegapoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, megapoundforcepersquareinchperminuteQuantity.Unit); - - var megapoundforcepersquareinchpersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); - AssertEx.EqualTolerance(MegapoundsForcePerSquareInchPerSecondInOnePascalPerSecond, (double)megapoundforcepersquareinchpersecondQuantity.Value, MegapoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, megapoundforcepersquareinchpersecondQuantity.Unit); - - var millimeterofmercurypersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.MillimeterOfMercuryPerSecond); - AssertEx.EqualTolerance(MillimetersOfMercuryPerSecondInOnePascalPerSecond, (double)millimeterofmercurypersecondQuantity.Value, MillimetersOfMercuryPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, millimeterofmercurypersecondQuantity.Unit); - - var pascalperminuteQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.PascalPerMinute); - AssertEx.EqualTolerance(PascalsPerMinuteInOnePascalPerSecond, (double)pascalperminuteQuantity.Value, PascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerMinute, pascalperminuteQuantity.Unit); - - var pascalpersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.PascalPerSecond); - AssertEx.EqualTolerance(PascalsPerSecondInOnePascalPerSecond, (double)pascalpersecondQuantity.Value, PascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerSecond, pascalpersecondQuantity.Unit); - - var poundforcepersquareinchperminuteQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); - AssertEx.EqualTolerance(PoundsForcePerSquareInchPerMinuteInOnePascalPerSecond, (double)poundforcepersquareinchperminuteQuantity.Value, PoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, poundforcepersquareinchperminuteQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var poundforcepersquareinchpersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); - AssertEx.EqualTolerance(PoundsForcePerSquareInchPerSecondInOnePascalPerSecond, (double)poundforcepersquareinchpersecondQuantity.Value, PoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, poundforcepersquareinchpersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(PressureChangeRateUnit unit) + { + var quantity = PressureChangeRate.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PressureChangeRateUnit unit) { - var quantityInBaseUnit = PressureChangeRate.FromPascalsPerSecond(1).ToBaseUnit(); - Assert.Equal(PressureChangeRate.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = PressureChangeRate.Units.FirstOrDefault(u => u != PressureChangeRate.BaseUnit && u != PressureChangeRateUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == PressureChangeRateUnit.Undefined) + fromUnit = PressureChangeRate.BaseUnit; + + var quantity = PressureChangeRate.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs index 84f3bfa29b..5c78f02394 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -131,6 +132,108 @@ public abstract partial class PressureTestsBase : QuantityTestsBase protected virtual double TorrsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PressureUnit unit) + { + return unit switch + { + PressureUnit.Atmosphere => (AtmospheresInOnePascal, AtmospheresTolerance), + PressureUnit.Bar => (BarsInOnePascal, BarsTolerance), + PressureUnit.Centibar => (CentibarsInOnePascal, CentibarsTolerance), + PressureUnit.Decapascal => (DecapascalsInOnePascal, DecapascalsTolerance), + PressureUnit.Decibar => (DecibarsInOnePascal, DecibarsTolerance), + PressureUnit.DynePerSquareCentimeter => (DynesPerSquareCentimeterInOnePascal, DynesPerSquareCentimeterTolerance), + PressureUnit.FootOfElevation => (FeetOfElevationInOnePascal, FeetOfElevationTolerance), + PressureUnit.FootOfHead => (FeetOfHeadInOnePascal, FeetOfHeadTolerance), + PressureUnit.Gigapascal => (GigapascalsInOnePascal, GigapascalsTolerance), + PressureUnit.Hectopascal => (HectopascalsInOnePascal, HectopascalsTolerance), + PressureUnit.InchOfMercury => (InchesOfMercuryInOnePascal, InchesOfMercuryTolerance), + PressureUnit.InchOfWaterColumn => (InchesOfWaterColumnInOnePascal, InchesOfWaterColumnTolerance), + PressureUnit.Kilobar => (KilobarsInOnePascal, KilobarsTolerance), + PressureUnit.KilogramForcePerSquareCentimeter => (KilogramsForcePerSquareCentimeterInOnePascal, KilogramsForcePerSquareCentimeterTolerance), + PressureUnit.KilogramForcePerSquareMeter => (KilogramsForcePerSquareMeterInOnePascal, KilogramsForcePerSquareMeterTolerance), + PressureUnit.KilogramForcePerSquareMillimeter => (KilogramsForcePerSquareMillimeterInOnePascal, KilogramsForcePerSquareMillimeterTolerance), + PressureUnit.KilonewtonPerSquareCentimeter => (KilonewtonsPerSquareCentimeterInOnePascal, KilonewtonsPerSquareCentimeterTolerance), + PressureUnit.KilonewtonPerSquareMeter => (KilonewtonsPerSquareMeterInOnePascal, KilonewtonsPerSquareMeterTolerance), + PressureUnit.KilonewtonPerSquareMillimeter => (KilonewtonsPerSquareMillimeterInOnePascal, KilonewtonsPerSquareMillimeterTolerance), + PressureUnit.Kilopascal => (KilopascalsInOnePascal, KilopascalsTolerance), + PressureUnit.KilopoundForcePerSquareFoot => (KilopoundsForcePerSquareFootInOnePascal, KilopoundsForcePerSquareFootTolerance), + PressureUnit.KilopoundForcePerSquareInch => (KilopoundsForcePerSquareInchInOnePascal, KilopoundsForcePerSquareInchTolerance), + PressureUnit.Megabar => (MegabarsInOnePascal, MegabarsTolerance), + PressureUnit.MeganewtonPerSquareMeter => (MeganewtonsPerSquareMeterInOnePascal, MeganewtonsPerSquareMeterTolerance), + PressureUnit.Megapascal => (MegapascalsInOnePascal, MegapascalsTolerance), + PressureUnit.MeterOfElevation => (MetersOfElevationInOnePascal, MetersOfElevationTolerance), + PressureUnit.MeterOfHead => (MetersOfHeadInOnePascal, MetersOfHeadTolerance), + PressureUnit.Microbar => (MicrobarsInOnePascal, MicrobarsTolerance), + PressureUnit.Micropascal => (MicropascalsInOnePascal, MicropascalsTolerance), + PressureUnit.Millibar => (MillibarsInOnePascal, MillibarsTolerance), + PressureUnit.MillimeterOfMercury => (MillimetersOfMercuryInOnePascal, MillimetersOfMercuryTolerance), + PressureUnit.MillimeterOfWaterColumn => (MillimeterOfWaterColumnInOnePascal, MillimeterOfWaterColumnTolerance), + PressureUnit.Millipascal => (MillipascalsInOnePascal, MillipascalsTolerance), + PressureUnit.NewtonPerSquareCentimeter => (NewtonsPerSquareCentimeterInOnePascal, NewtonsPerSquareCentimeterTolerance), + PressureUnit.NewtonPerSquareMeter => (NewtonsPerSquareMeterInOnePascal, NewtonsPerSquareMeterTolerance), + PressureUnit.NewtonPerSquareMillimeter => (NewtonsPerSquareMillimeterInOnePascal, NewtonsPerSquareMillimeterTolerance), + PressureUnit.Pascal => (PascalsInOnePascal, PascalsTolerance), + PressureUnit.PoundForcePerSquareFoot => (PoundsForcePerSquareFootInOnePascal, PoundsForcePerSquareFootTolerance), + PressureUnit.PoundForcePerSquareInch => (PoundsForcePerSquareInchInOnePascal, PoundsForcePerSquareInchTolerance), + PressureUnit.PoundPerInchSecondSquared => (PoundsPerInchSecondSquaredInOnePascal, PoundsPerInchSecondSquaredTolerance), + PressureUnit.TechnicalAtmosphere => (TechnicalAtmospheresInOnePascal, TechnicalAtmospheresTolerance), + PressureUnit.TonneForcePerSquareCentimeter => (TonnesForcePerSquareCentimeterInOnePascal, TonnesForcePerSquareCentimeterTolerance), + PressureUnit.TonneForcePerSquareMeter => (TonnesForcePerSquareMeterInOnePascal, TonnesForcePerSquareMeterTolerance), + PressureUnit.TonneForcePerSquareMillimeter => (TonnesForcePerSquareMillimeterInOnePascal, TonnesForcePerSquareMillimeterTolerance), + PressureUnit.Torr => (TorrsInOnePascal, TorrsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { PressureUnit.Atmosphere }, + new object[] { PressureUnit.Bar }, + new object[] { PressureUnit.Centibar }, + new object[] { PressureUnit.Decapascal }, + new object[] { PressureUnit.Decibar }, + new object[] { PressureUnit.DynePerSquareCentimeter }, + new object[] { PressureUnit.FootOfElevation }, + new object[] { PressureUnit.FootOfHead }, + new object[] { PressureUnit.Gigapascal }, + new object[] { PressureUnit.Hectopascal }, + new object[] { PressureUnit.InchOfMercury }, + new object[] { PressureUnit.InchOfWaterColumn }, + new object[] { PressureUnit.Kilobar }, + new object[] { PressureUnit.KilogramForcePerSquareCentimeter }, + new object[] { PressureUnit.KilogramForcePerSquareMeter }, + new object[] { PressureUnit.KilogramForcePerSquareMillimeter }, + new object[] { PressureUnit.KilonewtonPerSquareCentimeter }, + new object[] { PressureUnit.KilonewtonPerSquareMeter }, + new object[] { PressureUnit.KilonewtonPerSquareMillimeter }, + new object[] { PressureUnit.Kilopascal }, + new object[] { PressureUnit.KilopoundForcePerSquareFoot }, + new object[] { PressureUnit.KilopoundForcePerSquareInch }, + new object[] { PressureUnit.Megabar }, + new object[] { PressureUnit.MeganewtonPerSquareMeter }, + new object[] { PressureUnit.Megapascal }, + new object[] { PressureUnit.MeterOfElevation }, + new object[] { PressureUnit.MeterOfHead }, + new object[] { PressureUnit.Microbar }, + new object[] { PressureUnit.Micropascal }, + new object[] { PressureUnit.Millibar }, + new object[] { PressureUnit.MillimeterOfMercury }, + new object[] { PressureUnit.MillimeterOfWaterColumn }, + new object[] { PressureUnit.Millipascal }, + new object[] { PressureUnit.NewtonPerSquareCentimeter }, + new object[] { PressureUnit.NewtonPerSquareMeter }, + new object[] { PressureUnit.NewtonPerSquareMillimeter }, + new object[] { PressureUnit.Pascal }, + new object[] { PressureUnit.PoundForcePerSquareFoot }, + new object[] { PressureUnit.PoundForcePerSquareInch }, + new object[] { PressureUnit.PoundPerInchSecondSquared }, + new object[] { PressureUnit.TechnicalAtmosphere }, + new object[] { PressureUnit.TonneForcePerSquareCentimeter }, + new object[] { PressureUnit.TonneForcePerSquareMeter }, + new object[] { PressureUnit.TonneForcePerSquareMillimeter }, + new object[] { PressureUnit.Torr }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -516,197 +619,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(PressureUnit unit) { - var pascal = Pressure.FromPascals(1); - - var atmosphereQuantity = pascal.ToUnit(PressureUnit.Atmosphere); - AssertEx.EqualTolerance(AtmospheresInOnePascal, (double)atmosphereQuantity.Value, AtmospheresTolerance); - Assert.Equal(PressureUnit.Atmosphere, atmosphereQuantity.Unit); - - var barQuantity = pascal.ToUnit(PressureUnit.Bar); - AssertEx.EqualTolerance(BarsInOnePascal, (double)barQuantity.Value, BarsTolerance); - Assert.Equal(PressureUnit.Bar, barQuantity.Unit); - - var centibarQuantity = pascal.ToUnit(PressureUnit.Centibar); - AssertEx.EqualTolerance(CentibarsInOnePascal, (double)centibarQuantity.Value, CentibarsTolerance); - Assert.Equal(PressureUnit.Centibar, centibarQuantity.Unit); - - var decapascalQuantity = pascal.ToUnit(PressureUnit.Decapascal); - AssertEx.EqualTolerance(DecapascalsInOnePascal, (double)decapascalQuantity.Value, DecapascalsTolerance); - Assert.Equal(PressureUnit.Decapascal, decapascalQuantity.Unit); - - var decibarQuantity = pascal.ToUnit(PressureUnit.Decibar); - AssertEx.EqualTolerance(DecibarsInOnePascal, (double)decibarQuantity.Value, DecibarsTolerance); - Assert.Equal(PressureUnit.Decibar, decibarQuantity.Unit); - - var dynepersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.DynePerSquareCentimeter); - AssertEx.EqualTolerance(DynesPerSquareCentimeterInOnePascal, (double)dynepersquarecentimeterQuantity.Value, DynesPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.DynePerSquareCentimeter, dynepersquarecentimeterQuantity.Unit); - - var footofelevationQuantity = pascal.ToUnit(PressureUnit.FootOfElevation); - AssertEx.EqualTolerance(FeetOfElevationInOnePascal, (double)footofelevationQuantity.Value, FeetOfElevationTolerance); - Assert.Equal(PressureUnit.FootOfElevation, footofelevationQuantity.Unit); - - var footofheadQuantity = pascal.ToUnit(PressureUnit.FootOfHead); - AssertEx.EqualTolerance(FeetOfHeadInOnePascal, (double)footofheadQuantity.Value, FeetOfHeadTolerance); - Assert.Equal(PressureUnit.FootOfHead, footofheadQuantity.Unit); - - var gigapascalQuantity = pascal.ToUnit(PressureUnit.Gigapascal); - AssertEx.EqualTolerance(GigapascalsInOnePascal, (double)gigapascalQuantity.Value, GigapascalsTolerance); - Assert.Equal(PressureUnit.Gigapascal, gigapascalQuantity.Unit); - - var hectopascalQuantity = pascal.ToUnit(PressureUnit.Hectopascal); - AssertEx.EqualTolerance(HectopascalsInOnePascal, (double)hectopascalQuantity.Value, HectopascalsTolerance); - Assert.Equal(PressureUnit.Hectopascal, hectopascalQuantity.Unit); - - var inchofmercuryQuantity = pascal.ToUnit(PressureUnit.InchOfMercury); - AssertEx.EqualTolerance(InchesOfMercuryInOnePascal, (double)inchofmercuryQuantity.Value, InchesOfMercuryTolerance); - Assert.Equal(PressureUnit.InchOfMercury, inchofmercuryQuantity.Unit); - - var inchofwatercolumnQuantity = pascal.ToUnit(PressureUnit.InchOfWaterColumn); - AssertEx.EqualTolerance(InchesOfWaterColumnInOnePascal, (double)inchofwatercolumnQuantity.Value, InchesOfWaterColumnTolerance); - Assert.Equal(PressureUnit.InchOfWaterColumn, inchofwatercolumnQuantity.Unit); - - var kilobarQuantity = pascal.ToUnit(PressureUnit.Kilobar); - AssertEx.EqualTolerance(KilobarsInOnePascal, (double)kilobarQuantity.Value, KilobarsTolerance); - Assert.Equal(PressureUnit.Kilobar, kilobarQuantity.Unit); - - var kilogramforcepersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.KilogramForcePerSquareCentimeter); - AssertEx.EqualTolerance(KilogramsForcePerSquareCentimeterInOnePascal, (double)kilogramforcepersquarecentimeterQuantity.Value, KilogramsForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareCentimeter, kilogramforcepersquarecentimeterQuantity.Unit); - - var kilogramforcepersquaremeterQuantity = pascal.ToUnit(PressureUnit.KilogramForcePerSquareMeter); - AssertEx.EqualTolerance(KilogramsForcePerSquareMeterInOnePascal, (double)kilogramforcepersquaremeterQuantity.Value, KilogramsForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMeter, kilogramforcepersquaremeterQuantity.Unit); - - var kilogramforcepersquaremillimeterQuantity = pascal.ToUnit(PressureUnit.KilogramForcePerSquareMillimeter); - AssertEx.EqualTolerance(KilogramsForcePerSquareMillimeterInOnePascal, (double)kilogramforcepersquaremillimeterQuantity.Value, KilogramsForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMillimeter, kilogramforcepersquaremillimeterQuantity.Unit); - - var kilonewtonpersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.KilonewtonPerSquareCentimeter); - AssertEx.EqualTolerance(KilonewtonsPerSquareCentimeterInOnePascal, (double)kilonewtonpersquarecentimeterQuantity.Value, KilonewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareCentimeter, kilonewtonpersquarecentimeterQuantity.Unit); - - var kilonewtonpersquaremeterQuantity = pascal.ToUnit(PressureUnit.KilonewtonPerSquareMeter); - AssertEx.EqualTolerance(KilonewtonsPerSquareMeterInOnePascal, (double)kilonewtonpersquaremeterQuantity.Value, KilonewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMeter, kilonewtonpersquaremeterQuantity.Unit); - - var kilonewtonpersquaremillimeterQuantity = pascal.ToUnit(PressureUnit.KilonewtonPerSquareMillimeter); - AssertEx.EqualTolerance(KilonewtonsPerSquareMillimeterInOnePascal, (double)kilonewtonpersquaremillimeterQuantity.Value, KilonewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMillimeter, kilonewtonpersquaremillimeterQuantity.Unit); - - var kilopascalQuantity = pascal.ToUnit(PressureUnit.Kilopascal); - AssertEx.EqualTolerance(KilopascalsInOnePascal, (double)kilopascalQuantity.Value, KilopascalsTolerance); - Assert.Equal(PressureUnit.Kilopascal, kilopascalQuantity.Unit); - - var kilopoundforcepersquarefootQuantity = pascal.ToUnit(PressureUnit.KilopoundForcePerSquareFoot); - AssertEx.EqualTolerance(KilopoundsForcePerSquareFootInOnePascal, (double)kilopoundforcepersquarefootQuantity.Value, KilopoundsForcePerSquareFootTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareFoot, kilopoundforcepersquarefootQuantity.Unit); + var inBaseUnits = Pressure.From(1.0, Pressure.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilopoundforcepersquareinchQuantity = pascal.ToUnit(PressureUnit.KilopoundForcePerSquareInch); - AssertEx.EqualTolerance(KilopoundsForcePerSquareInchInOnePascal, (double)kilopoundforcepersquareinchQuantity.Value, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, kilopoundforcepersquareinchQuantity.Unit); - - var megabarQuantity = pascal.ToUnit(PressureUnit.Megabar); - AssertEx.EqualTolerance(MegabarsInOnePascal, (double)megabarQuantity.Value, MegabarsTolerance); - Assert.Equal(PressureUnit.Megabar, megabarQuantity.Unit); - - var meganewtonpersquaremeterQuantity = pascal.ToUnit(PressureUnit.MeganewtonPerSquareMeter); - AssertEx.EqualTolerance(MeganewtonsPerSquareMeterInOnePascal, (double)meganewtonpersquaremeterQuantity.Value, MeganewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.MeganewtonPerSquareMeter, meganewtonpersquaremeterQuantity.Unit); - - var megapascalQuantity = pascal.ToUnit(PressureUnit.Megapascal); - AssertEx.EqualTolerance(MegapascalsInOnePascal, (double)megapascalQuantity.Value, MegapascalsTolerance); - Assert.Equal(PressureUnit.Megapascal, megapascalQuantity.Unit); - - var meterofelevationQuantity = pascal.ToUnit(PressureUnit.MeterOfElevation); - AssertEx.EqualTolerance(MetersOfElevationInOnePascal, (double)meterofelevationQuantity.Value, MetersOfElevationTolerance); - Assert.Equal(PressureUnit.MeterOfElevation, meterofelevationQuantity.Unit); - - var meterofheadQuantity = pascal.ToUnit(PressureUnit.MeterOfHead); - AssertEx.EqualTolerance(MetersOfHeadInOnePascal, (double)meterofheadQuantity.Value, MetersOfHeadTolerance); - Assert.Equal(PressureUnit.MeterOfHead, meterofheadQuantity.Unit); - - var microbarQuantity = pascal.ToUnit(PressureUnit.Microbar); - AssertEx.EqualTolerance(MicrobarsInOnePascal, (double)microbarQuantity.Value, MicrobarsTolerance); - Assert.Equal(PressureUnit.Microbar, microbarQuantity.Unit); - - var micropascalQuantity = pascal.ToUnit(PressureUnit.Micropascal); - AssertEx.EqualTolerance(MicropascalsInOnePascal, (double)micropascalQuantity.Value, MicropascalsTolerance); - Assert.Equal(PressureUnit.Micropascal, micropascalQuantity.Unit); - - var millibarQuantity = pascal.ToUnit(PressureUnit.Millibar); - AssertEx.EqualTolerance(MillibarsInOnePascal, (double)millibarQuantity.Value, MillibarsTolerance); - Assert.Equal(PressureUnit.Millibar, millibarQuantity.Unit); - - var millimeterofmercuryQuantity = pascal.ToUnit(PressureUnit.MillimeterOfMercury); - AssertEx.EqualTolerance(MillimetersOfMercuryInOnePascal, (double)millimeterofmercuryQuantity.Value, MillimetersOfMercuryTolerance); - Assert.Equal(PressureUnit.MillimeterOfMercury, millimeterofmercuryQuantity.Unit); - - var millimeterofwatercolumnQuantity = pascal.ToUnit(PressureUnit.MillimeterOfWaterColumn); - AssertEx.EqualTolerance(MillimeterOfWaterColumnInOnePascal, (double)millimeterofwatercolumnQuantity.Value, MillimeterOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MillimeterOfWaterColumn, millimeterofwatercolumnQuantity.Unit); - - var millipascalQuantity = pascal.ToUnit(PressureUnit.Millipascal); - AssertEx.EqualTolerance(MillipascalsInOnePascal, (double)millipascalQuantity.Value, MillipascalsTolerance); - Assert.Equal(PressureUnit.Millipascal, millipascalQuantity.Unit); - - var newtonpersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.NewtonPerSquareCentimeter); - AssertEx.EqualTolerance(NewtonsPerSquareCentimeterInOnePascal, (double)newtonpersquarecentimeterQuantity.Value, NewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareCentimeter, newtonpersquarecentimeterQuantity.Unit); - - var newtonpersquaremeterQuantity = pascal.ToUnit(PressureUnit.NewtonPerSquareMeter); - AssertEx.EqualTolerance(NewtonsPerSquareMeterInOnePascal, (double)newtonpersquaremeterQuantity.Value, NewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMeter, newtonpersquaremeterQuantity.Unit); - - var newtonpersquaremillimeterQuantity = pascal.ToUnit(PressureUnit.NewtonPerSquareMillimeter); - AssertEx.EqualTolerance(NewtonsPerSquareMillimeterInOnePascal, (double)newtonpersquaremillimeterQuantity.Value, NewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMillimeter, newtonpersquaremillimeterQuantity.Unit); - - var pascalQuantity = pascal.ToUnit(PressureUnit.Pascal); - AssertEx.EqualTolerance(PascalsInOnePascal, (double)pascalQuantity.Value, PascalsTolerance); - Assert.Equal(PressureUnit.Pascal, pascalQuantity.Unit); - - var poundforcepersquarefootQuantity = pascal.ToUnit(PressureUnit.PoundForcePerSquareFoot); - AssertEx.EqualTolerance(PoundsForcePerSquareFootInOnePascal, (double)poundforcepersquarefootQuantity.Value, PoundsForcePerSquareFootTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareFoot, poundforcepersquarefootQuantity.Unit); - - var poundforcepersquareinchQuantity = pascal.ToUnit(PressureUnit.PoundForcePerSquareInch); - AssertEx.EqualTolerance(PoundsForcePerSquareInchInOnePascal, (double)poundforcepersquareinchQuantity.Value, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, poundforcepersquareinchQuantity.Unit); - - var poundperinchsecondsquaredQuantity = pascal.ToUnit(PressureUnit.PoundPerInchSecondSquared); - AssertEx.EqualTolerance(PoundsPerInchSecondSquaredInOnePascal, (double)poundperinchsecondsquaredQuantity.Value, PoundsPerInchSecondSquaredTolerance); - Assert.Equal(PressureUnit.PoundPerInchSecondSquared, poundperinchsecondsquaredQuantity.Unit); - - var technicalatmosphereQuantity = pascal.ToUnit(PressureUnit.TechnicalAtmosphere); - AssertEx.EqualTolerance(TechnicalAtmospheresInOnePascal, (double)technicalatmosphereQuantity.Value, TechnicalAtmospheresTolerance); - Assert.Equal(PressureUnit.TechnicalAtmosphere, technicalatmosphereQuantity.Unit); - - var tonneforcepersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.TonneForcePerSquareCentimeter); - AssertEx.EqualTolerance(TonnesForcePerSquareCentimeterInOnePascal, (double)tonneforcepersquarecentimeterQuantity.Value, TonnesForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareCentimeter, tonneforcepersquarecentimeterQuantity.Unit); - - var tonneforcepersquaremeterQuantity = pascal.ToUnit(PressureUnit.TonneForcePerSquareMeter); - AssertEx.EqualTolerance(TonnesForcePerSquareMeterInOnePascal, (double)tonneforcepersquaremeterQuantity.Value, TonnesForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareMeter, tonneforcepersquaremeterQuantity.Unit); - - var tonneforcepersquaremillimeterQuantity = pascal.ToUnit(PressureUnit.TonneForcePerSquareMillimeter); - AssertEx.EqualTolerance(TonnesForcePerSquareMillimeterInOnePascal, (double)tonneforcepersquaremillimeterQuantity.Value, TonnesForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareMillimeter, tonneforcepersquaremillimeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var torrQuantity = pascal.ToUnit(PressureUnit.Torr); - AssertEx.EqualTolerance(TorrsInOnePascal, (double)torrQuantity.Value, TorrsTolerance); - Assert.Equal(PressureUnit.Torr, torrQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(PressureUnit unit) + { + var quantity = Pressure.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PressureUnit unit) { - var quantityInBaseUnit = Pressure.FromPascals(1).ToBaseUnit(); - Assert.Equal(Pressure.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Pressure.Units.FirstOrDefault(u => u != Pressure.BaseUnit && u != PressureUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == PressureUnit.Undefined) + fromUnit = Pressure.BaseUnit; + + var quantity = Pressure.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs index f6e2cd8ff6..41395a85c3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -45,6 +46,22 @@ public abstract partial class RatioChangeRateTestsBase : QuantityTestsBase protected virtual double PercentsPerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RatioChangeRateUnit unit) + { + return unit switch + { + RatioChangeRateUnit.DecimalFractionPerSecond => (DecimalFractionsPerSecondInOneDecimalFractionPerSecond, DecimalFractionsPerSecondTolerance), + RatioChangeRateUnit.PercentPerSecond => (PercentsPerSecondInOneDecimalFractionPerSecond, PercentsPerSecondTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { RatioChangeRateUnit.DecimalFractionPerSecond }, + new object[] { RatioChangeRateUnit.PercentPerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -172,25 +189,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(RatioChangeRateUnit unit) { - var decimalfractionpersecond = RatioChangeRate.FromDecimalFractionsPerSecond(1); + var inBaseUnits = RatioChangeRate.From(1.0, RatioChangeRate.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var decimalfractionpersecondQuantity = decimalfractionpersecond.ToUnit(RatioChangeRateUnit.DecimalFractionPerSecond); - AssertEx.EqualTolerance(DecimalFractionsPerSecondInOneDecimalFractionPerSecond, (double)decimalfractionpersecondQuantity.Value, DecimalFractionsPerSecondTolerance); - Assert.Equal(RatioChangeRateUnit.DecimalFractionPerSecond, decimalfractionpersecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var percentpersecondQuantity = decimalfractionpersecond.ToUnit(RatioChangeRateUnit.PercentPerSecond); - AssertEx.EqualTolerance(PercentsPerSecondInOneDecimalFractionPerSecond, (double)percentpersecondQuantity.Value, PercentsPerSecondTolerance); - Assert.Equal(RatioChangeRateUnit.PercentPerSecond, percentpersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(RatioChangeRateUnit unit) + { + var quantity = RatioChangeRate.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RatioChangeRateUnit unit) { - var quantityInBaseUnit = RatioChangeRate.FromDecimalFractionsPerSecond(1).ToBaseUnit(); - Assert.Equal(RatioChangeRate.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = RatioChangeRate.Units.FirstOrDefault(u => u != RatioChangeRate.BaseUnit && u != RatioChangeRateUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == RatioChangeRateUnit.Undefined) + fromUnit = RatioChangeRate.BaseUnit; + + var quantity = RatioChangeRate.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs index 5f1c730275..58ab0bb668 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -53,6 +54,30 @@ public abstract partial class RatioTestsBase : QuantityTestsBase protected virtual double PercentTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RatioUnit unit) + { + return unit switch + { + RatioUnit.DecimalFraction => (DecimalFractionsInOneDecimalFraction, DecimalFractionsTolerance), + RatioUnit.PartPerBillion => (PartsPerBillionInOneDecimalFraction, PartsPerBillionTolerance), + RatioUnit.PartPerMillion => (PartsPerMillionInOneDecimalFraction, PartsPerMillionTolerance), + RatioUnit.PartPerThousand => (PartsPerThousandInOneDecimalFraction, PartsPerThousandTolerance), + RatioUnit.PartPerTrillion => (PartsPerTrillionInOneDecimalFraction, PartsPerTrillionTolerance), + RatioUnit.Percent => (PercentInOneDecimalFraction, PercentTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { RatioUnit.DecimalFraction }, + new object[] { RatioUnit.PartPerBillion }, + new object[] { RatioUnit.PartPerMillion }, + new object[] { RatioUnit.PartPerThousand }, + new object[] { RatioUnit.PartPerTrillion }, + new object[] { RatioUnit.Percent }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -204,41 +229,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(RatioUnit unit) { - var decimalfraction = Ratio.FromDecimalFractions(1); - - var decimalfractionQuantity = decimalfraction.ToUnit(RatioUnit.DecimalFraction); - AssertEx.EqualTolerance(DecimalFractionsInOneDecimalFraction, (double)decimalfractionQuantity.Value, DecimalFractionsTolerance); - Assert.Equal(RatioUnit.DecimalFraction, decimalfractionQuantity.Unit); + var inBaseUnits = Ratio.From(1.0, Ratio.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var partperbillionQuantity = decimalfraction.ToUnit(RatioUnit.PartPerBillion); - AssertEx.EqualTolerance(PartsPerBillionInOneDecimalFraction, (double)partperbillionQuantity.Value, PartsPerBillionTolerance); - Assert.Equal(RatioUnit.PartPerBillion, partperbillionQuantity.Unit); - - var partpermillionQuantity = decimalfraction.ToUnit(RatioUnit.PartPerMillion); - AssertEx.EqualTolerance(PartsPerMillionInOneDecimalFraction, (double)partpermillionQuantity.Value, PartsPerMillionTolerance); - Assert.Equal(RatioUnit.PartPerMillion, partpermillionQuantity.Unit); - - var partperthousandQuantity = decimalfraction.ToUnit(RatioUnit.PartPerThousand); - AssertEx.EqualTolerance(PartsPerThousandInOneDecimalFraction, (double)partperthousandQuantity.Value, PartsPerThousandTolerance); - Assert.Equal(RatioUnit.PartPerThousand, partperthousandQuantity.Unit); - - var partpertrillionQuantity = decimalfraction.ToUnit(RatioUnit.PartPerTrillion); - AssertEx.EqualTolerance(PartsPerTrillionInOneDecimalFraction, (double)partpertrillionQuantity.Value, PartsPerTrillionTolerance); - Assert.Equal(RatioUnit.PartPerTrillion, partpertrillionQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var percentQuantity = decimalfraction.ToUnit(RatioUnit.Percent); - AssertEx.EqualTolerance(PercentInOneDecimalFraction, (double)percentQuantity.Value, PercentTolerance); - Assert.Equal(RatioUnit.Percent, percentQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(RatioUnit unit) + { + var quantity = Ratio.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RatioUnit unit) { - var quantityInBaseUnit = Ratio.FromDecimalFractions(1).ToBaseUnit(); - Assert.Equal(Ratio.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Ratio.Units.FirstOrDefault(u => u != Ratio.BaseUnit && u != RatioUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == RatioUnit.Undefined) + fromUnit = Ratio.BaseUnit; + + var quantity = Ratio.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs index a5fb420a1b..26420e02ad 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class ReactiveEnergyTestsBase : QuantityTestsBase protected virtual double VoltampereReactiveHoursTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ReactiveEnergyUnit unit) + { + return unit switch + { + ReactiveEnergyUnit.KilovoltampereReactiveHour => (KilovoltampereReactiveHoursInOneVoltampereReactiveHour, KilovoltampereReactiveHoursTolerance), + ReactiveEnergyUnit.MegavoltampereReactiveHour => (MegavoltampereReactiveHoursInOneVoltampereReactiveHour, MegavoltampereReactiveHoursTolerance), + ReactiveEnergyUnit.VoltampereReactiveHour => (VoltampereReactiveHoursInOneVoltampereReactiveHour, VoltampereReactiveHoursTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ReactiveEnergyUnit.KilovoltampereReactiveHour }, + new object[] { ReactiveEnergyUnit.MegavoltampereReactiveHour }, + new object[] { ReactiveEnergyUnit.VoltampereReactiveHour }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ReactiveEnergyUnit unit) { - var voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); + var inBaseUnits = ReactiveEnergy.From(1.0, ReactiveEnergy.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilovoltamperereactivehourQuantity = voltamperereactivehour.ToUnit(ReactiveEnergyUnit.KilovoltampereReactiveHour); - AssertEx.EqualTolerance(KilovoltampereReactiveHoursInOneVoltampereReactiveHour, (double)kilovoltamperereactivehourQuantity.Value, KilovoltampereReactiveHoursTolerance); - Assert.Equal(ReactiveEnergyUnit.KilovoltampereReactiveHour, kilovoltamperereactivehourQuantity.Unit); - - var megavoltamperereactivehourQuantity = voltamperereactivehour.ToUnit(ReactiveEnergyUnit.MegavoltampereReactiveHour); - AssertEx.EqualTolerance(MegavoltampereReactiveHoursInOneVoltampereReactiveHour, (double)megavoltamperereactivehourQuantity.Value, MegavoltampereReactiveHoursTolerance); - Assert.Equal(ReactiveEnergyUnit.MegavoltampereReactiveHour, megavoltamperereactivehourQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var voltamperereactivehourQuantity = voltamperereactivehour.ToUnit(ReactiveEnergyUnit.VoltampereReactiveHour); - AssertEx.EqualTolerance(VoltampereReactiveHoursInOneVoltampereReactiveHour, (double)voltamperereactivehourQuantity.Value, VoltampereReactiveHoursTolerance); - Assert.Equal(ReactiveEnergyUnit.VoltampereReactiveHour, voltamperereactivehourQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ReactiveEnergyUnit unit) + { + var quantity = ReactiveEnergy.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReactiveEnergyUnit unit) { - var quantityInBaseUnit = ReactiveEnergy.FromVoltampereReactiveHours(1).ToBaseUnit(); - Assert.Equal(ReactiveEnergy.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ReactiveEnergy.Units.FirstOrDefault(u => u != ReactiveEnergy.BaseUnit && u != ReactiveEnergyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ReactiveEnergyUnit.Undefined) + fromUnit = ReactiveEnergy.BaseUnit; + + var quantity = ReactiveEnergy.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs index 7d4cb80b6a..9b122787b6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class ReactivePowerTestsBase : QuantityTestsBase protected virtual double VoltamperesReactiveTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ReactivePowerUnit unit) + { + return unit switch + { + ReactivePowerUnit.GigavoltampereReactive => (GigavoltamperesReactiveInOneVoltampereReactive, GigavoltamperesReactiveTolerance), + ReactivePowerUnit.KilovoltampereReactive => (KilovoltamperesReactiveInOneVoltampereReactive, KilovoltamperesReactiveTolerance), + ReactivePowerUnit.MegavoltampereReactive => (MegavoltamperesReactiveInOneVoltampereReactive, MegavoltamperesReactiveTolerance), + ReactivePowerUnit.VoltampereReactive => (VoltamperesReactiveInOneVoltampereReactive, VoltamperesReactiveTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ReactivePowerUnit.GigavoltampereReactive }, + new object[] { ReactivePowerUnit.KilovoltampereReactive }, + new object[] { ReactivePowerUnit.MegavoltampereReactive }, + new object[] { ReactivePowerUnit.VoltampereReactive }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ReactivePowerUnit unit) { - var voltamperereactive = ReactivePower.FromVoltamperesReactive(1); + var inBaseUnits = ReactivePower.From(1.0, ReactivePower.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var gigavoltamperereactiveQuantity = voltamperereactive.ToUnit(ReactivePowerUnit.GigavoltampereReactive); - AssertEx.EqualTolerance(GigavoltamperesReactiveInOneVoltampereReactive, (double)gigavoltamperereactiveQuantity.Value, GigavoltamperesReactiveTolerance); - Assert.Equal(ReactivePowerUnit.GigavoltampereReactive, gigavoltamperereactiveQuantity.Unit); - - var kilovoltamperereactiveQuantity = voltamperereactive.ToUnit(ReactivePowerUnit.KilovoltampereReactive); - AssertEx.EqualTolerance(KilovoltamperesReactiveInOneVoltampereReactive, (double)kilovoltamperereactiveQuantity.Value, KilovoltamperesReactiveTolerance); - Assert.Equal(ReactivePowerUnit.KilovoltampereReactive, kilovoltamperereactiveQuantity.Unit); - - var megavoltamperereactiveQuantity = voltamperereactive.ToUnit(ReactivePowerUnit.MegavoltampereReactive); - AssertEx.EqualTolerance(MegavoltamperesReactiveInOneVoltampereReactive, (double)megavoltamperereactiveQuantity.Value, MegavoltamperesReactiveTolerance); - Assert.Equal(ReactivePowerUnit.MegavoltampereReactive, megavoltamperereactiveQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var voltamperereactiveQuantity = voltamperereactive.ToUnit(ReactivePowerUnit.VoltampereReactive); - AssertEx.EqualTolerance(VoltamperesReactiveInOneVoltampereReactive, (double)voltamperereactiveQuantity.Value, VoltamperesReactiveTolerance); - Assert.Equal(ReactivePowerUnit.VoltampereReactive, voltamperereactiveQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ReactivePowerUnit unit) + { + var quantity = ReactivePower.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReactivePowerUnit unit) { - var quantityInBaseUnit = ReactivePower.FromVoltamperesReactive(1).ToBaseUnit(); - Assert.Equal(ReactivePower.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ReactivePower.Units.FirstOrDefault(u => u != ReactivePower.BaseUnit && u != ReactivePowerUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ReactivePowerUnit.Undefined) + fromUnit = ReactivePower.BaseUnit; + + var quantity = ReactivePower.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs index b64695166c..639244d32b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -63,6 +64,40 @@ public abstract partial class ReciprocalAreaTestsBase : QuantityTestsBase protected virtual double InverseUsSurveySquareFeetTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ReciprocalAreaUnit unit) + { + return unit switch + { + ReciprocalAreaUnit.InverseSquareCentimeter => (InverseSquareCentimetersInOneInverseSquareMeter, InverseSquareCentimetersTolerance), + ReciprocalAreaUnit.InverseSquareDecimeter => (InverseSquareDecimetersInOneInverseSquareMeter, InverseSquareDecimetersTolerance), + ReciprocalAreaUnit.InverseSquareFoot => (InverseSquareFeetInOneInverseSquareMeter, InverseSquareFeetTolerance), + ReciprocalAreaUnit.InverseSquareInch => (InverseSquareInchesInOneInverseSquareMeter, InverseSquareInchesTolerance), + ReciprocalAreaUnit.InverseSquareKilometer => (InverseSquareKilometersInOneInverseSquareMeter, InverseSquareKilometersTolerance), + ReciprocalAreaUnit.InverseSquareMeter => (InverseSquareMetersInOneInverseSquareMeter, InverseSquareMetersTolerance), + ReciprocalAreaUnit.InverseSquareMicrometer => (InverseSquareMicrometersInOneInverseSquareMeter, InverseSquareMicrometersTolerance), + ReciprocalAreaUnit.InverseSquareMile => (InverseSquareMilesInOneInverseSquareMeter, InverseSquareMilesTolerance), + ReciprocalAreaUnit.InverseSquareMillimeter => (InverseSquareMillimetersInOneInverseSquareMeter, InverseSquareMillimetersTolerance), + ReciprocalAreaUnit.InverseSquareYard => (InverseSquareYardsInOneInverseSquareMeter, InverseSquareYardsTolerance), + ReciprocalAreaUnit.InverseUsSurveySquareFoot => (InverseUsSurveySquareFeetInOneInverseSquareMeter, InverseUsSurveySquareFeetTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ReciprocalAreaUnit.InverseSquareCentimeter }, + new object[] { ReciprocalAreaUnit.InverseSquareDecimeter }, + new object[] { ReciprocalAreaUnit.InverseSquareFoot }, + new object[] { ReciprocalAreaUnit.InverseSquareInch }, + new object[] { ReciprocalAreaUnit.InverseSquareKilometer }, + new object[] { ReciprocalAreaUnit.InverseSquareMeter }, + new object[] { ReciprocalAreaUnit.InverseSquareMicrometer }, + new object[] { ReciprocalAreaUnit.InverseSquareMile }, + new object[] { ReciprocalAreaUnit.InverseSquareMillimeter }, + new object[] { ReciprocalAreaUnit.InverseSquareYard }, + new object[] { ReciprocalAreaUnit.InverseUsSurveySquareFoot }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -244,61 +279,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ReciprocalAreaUnit unit) { - var inversesquaremeter = ReciprocalArea.FromInverseSquareMeters(1); - - var inversesquarecentimeterQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareCentimeter); - AssertEx.EqualTolerance(InverseSquareCentimetersInOneInverseSquareMeter, (double)inversesquarecentimeterQuantity.Value, InverseSquareCentimetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareCentimeter, inversesquarecentimeterQuantity.Unit); - - var inversesquaredecimeterQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareDecimeter); - AssertEx.EqualTolerance(InverseSquareDecimetersInOneInverseSquareMeter, (double)inversesquaredecimeterQuantity.Value, InverseSquareDecimetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareDecimeter, inversesquaredecimeterQuantity.Unit); - - var inversesquarefootQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareFoot); - AssertEx.EqualTolerance(InverseSquareFeetInOneInverseSquareMeter, (double)inversesquarefootQuantity.Value, InverseSquareFeetTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareFoot, inversesquarefootQuantity.Unit); - - var inversesquareinchQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareInch); - AssertEx.EqualTolerance(InverseSquareInchesInOneInverseSquareMeter, (double)inversesquareinchQuantity.Value, InverseSquareInchesTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareInch, inversesquareinchQuantity.Unit); - - var inversesquarekilometerQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareKilometer); - AssertEx.EqualTolerance(InverseSquareKilometersInOneInverseSquareMeter, (double)inversesquarekilometerQuantity.Value, InverseSquareKilometersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareKilometer, inversesquarekilometerQuantity.Unit); + var inBaseUnits = ReciprocalArea.From(1.0, ReciprocalArea.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var inversesquaremeterQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareMeter); - AssertEx.EqualTolerance(InverseSquareMetersInOneInverseSquareMeter, (double)inversesquaremeterQuantity.Value, InverseSquareMetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMeter, inversesquaremeterQuantity.Unit); - - var inversesquaremicrometerQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareMicrometer); - AssertEx.EqualTolerance(InverseSquareMicrometersInOneInverseSquareMeter, (double)inversesquaremicrometerQuantity.Value, InverseSquareMicrometersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMicrometer, inversesquaremicrometerQuantity.Unit); - - var inversesquaremileQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareMile); - AssertEx.EqualTolerance(InverseSquareMilesInOneInverseSquareMeter, (double)inversesquaremileQuantity.Value, InverseSquareMilesTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMile, inversesquaremileQuantity.Unit); - - var inversesquaremillimeterQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareMillimeter); - AssertEx.EqualTolerance(InverseSquareMillimetersInOneInverseSquareMeter, (double)inversesquaremillimeterQuantity.Value, InverseSquareMillimetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMillimeter, inversesquaremillimeterQuantity.Unit); - - var inversesquareyardQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseSquareYard); - AssertEx.EqualTolerance(InverseSquareYardsInOneInverseSquareMeter, (double)inversesquareyardQuantity.Value, InverseSquareYardsTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareYard, inversesquareyardQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var inverseussurveysquarefootQuantity = inversesquaremeter.ToUnit(ReciprocalAreaUnit.InverseUsSurveySquareFoot); - AssertEx.EqualTolerance(InverseUsSurveySquareFeetInOneInverseSquareMeter, (double)inverseussurveysquarefootQuantity.Value, InverseUsSurveySquareFeetTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseUsSurveySquareFoot, inverseussurveysquarefootQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ReciprocalAreaUnit unit) + { + var quantity = ReciprocalArea.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReciprocalAreaUnit unit) { - var quantityInBaseUnit = ReciprocalArea.FromInverseSquareMeters(1).ToBaseUnit(); - Assert.Equal(ReciprocalArea.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ReciprocalArea.Units.FirstOrDefault(u => u != ReciprocalArea.BaseUnit && u != ReciprocalAreaUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ReciprocalAreaUnit.Undefined) + fromUnit = ReciprocalArea.BaseUnit; + + var quantity = ReciprocalArea.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs index 682963c9ff..96ae80abdd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -61,6 +62,38 @@ public abstract partial class ReciprocalLengthTestsBase : QuantityTestsBase protected virtual double InverseYardsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ReciprocalLengthUnit unit) + { + return unit switch + { + ReciprocalLengthUnit.InverseCentimeter => (InverseCentimetersInOneInverseMeter, InverseCentimetersTolerance), + ReciprocalLengthUnit.InverseFoot => (InverseFeetInOneInverseMeter, InverseFeetTolerance), + ReciprocalLengthUnit.InverseInch => (InverseInchesInOneInverseMeter, InverseInchesTolerance), + ReciprocalLengthUnit.InverseMeter => (InverseMetersInOneInverseMeter, InverseMetersTolerance), + ReciprocalLengthUnit.InverseMicroinch => (InverseMicroinchesInOneInverseMeter, InverseMicroinchesTolerance), + ReciprocalLengthUnit.InverseMil => (InverseMilsInOneInverseMeter, InverseMilsTolerance), + ReciprocalLengthUnit.InverseMile => (InverseMilesInOneInverseMeter, InverseMilesTolerance), + ReciprocalLengthUnit.InverseMillimeter => (InverseMillimetersInOneInverseMeter, InverseMillimetersTolerance), + ReciprocalLengthUnit.InverseUsSurveyFoot => (InverseUsSurveyFeetInOneInverseMeter, InverseUsSurveyFeetTolerance), + ReciprocalLengthUnit.InverseYard => (InverseYardsInOneInverseMeter, InverseYardsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ReciprocalLengthUnit.InverseCentimeter }, + new object[] { ReciprocalLengthUnit.InverseFoot }, + new object[] { ReciprocalLengthUnit.InverseInch }, + new object[] { ReciprocalLengthUnit.InverseMeter }, + new object[] { ReciprocalLengthUnit.InverseMicroinch }, + new object[] { ReciprocalLengthUnit.InverseMil }, + new object[] { ReciprocalLengthUnit.InverseMile }, + new object[] { ReciprocalLengthUnit.InverseMillimeter }, + new object[] { ReciprocalLengthUnit.InverseUsSurveyFoot }, + new object[] { ReciprocalLengthUnit.InverseYard }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -236,57 +269,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ReciprocalLengthUnit unit) { - var inversemeter = ReciprocalLength.FromInverseMeters(1); - - var inversecentimeterQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseCentimeter); - AssertEx.EqualTolerance(InverseCentimetersInOneInverseMeter, (double)inversecentimeterQuantity.Value, InverseCentimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseCentimeter, inversecentimeterQuantity.Unit); - - var inversefootQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseFoot); - AssertEx.EqualTolerance(InverseFeetInOneInverseMeter, (double)inversefootQuantity.Value, InverseFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseFoot, inversefootQuantity.Unit); - - var inverseinchQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseInch); - AssertEx.EqualTolerance(InverseInchesInOneInverseMeter, (double)inverseinchQuantity.Value, InverseInchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseInch, inverseinchQuantity.Unit); - - var inversemeterQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseMeter); - AssertEx.EqualTolerance(InverseMetersInOneInverseMeter, (double)inversemeterQuantity.Value, InverseMetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMeter, inversemeterQuantity.Unit); - - var inversemicroinchQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseMicroinch); - AssertEx.EqualTolerance(InverseMicroinchesInOneInverseMeter, (double)inversemicroinchQuantity.Value, InverseMicroinchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMicroinch, inversemicroinchQuantity.Unit); + var inBaseUnits = ReciprocalLength.From(1.0, ReciprocalLength.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var inversemilQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseMil); - AssertEx.EqualTolerance(InverseMilsInOneInverseMeter, (double)inversemilQuantity.Value, InverseMilsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMil, inversemilQuantity.Unit); - - var inversemileQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseMile); - AssertEx.EqualTolerance(InverseMilesInOneInverseMeter, (double)inversemileQuantity.Value, InverseMilesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMile, inversemileQuantity.Unit); - - var inversemillimeterQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseMillimeter); - AssertEx.EqualTolerance(InverseMillimetersInOneInverseMeter, (double)inversemillimeterQuantity.Value, InverseMillimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMillimeter, inversemillimeterQuantity.Unit); - - var inverseussurveyfootQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseUsSurveyFoot); - AssertEx.EqualTolerance(InverseUsSurveyFeetInOneInverseMeter, (double)inverseussurveyfootQuantity.Value, InverseUsSurveyFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseUsSurveyFoot, inverseussurveyfootQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var inverseyardQuantity = inversemeter.ToUnit(ReciprocalLengthUnit.InverseYard); - AssertEx.EqualTolerance(InverseYardsInOneInverseMeter, (double)inverseyardQuantity.Value, InverseYardsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseYard, inverseyardQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ReciprocalLengthUnit unit) + { + var quantity = ReciprocalLength.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReciprocalLengthUnit unit) { - var quantityInBaseUnit = ReciprocalLength.FromInverseMeters(1).ToBaseUnit(); - Assert.Equal(ReciprocalLength.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ReciprocalLength.Units.FirstOrDefault(u => u != ReciprocalLength.BaseUnit && u != ReciprocalLengthUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ReciprocalLengthUnit.Undefined) + fromUnit = ReciprocalLength.BaseUnit; + + var quantity = ReciprocalLength.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs index a7ba21d25b..736579b1a4 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class RelativeHumidityTestsBase : QuantityTestsBase protected virtual double PercentTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RelativeHumidityUnit unit) + { + return unit switch + { + RelativeHumidityUnit.Percent => (PercentInOnePercent, PercentTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { RelativeHumidityUnit.Percent }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(RelativeHumidityUnit unit) { - var percent = RelativeHumidity.FromPercent(1); + var inBaseUnits = RelativeHumidity.From(1.0, RelativeHumidity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var percentQuantity = percent.ToUnit(RelativeHumidityUnit.Percent); - AssertEx.EqualTolerance(PercentInOnePercent, (double)percentQuantity.Value, PercentTolerance); - Assert.Equal(RelativeHumidityUnit.Percent, percentQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(RelativeHumidityUnit unit) + { + var quantity = RelativeHumidity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RelativeHumidityUnit unit) { - var quantityInBaseUnit = RelativeHumidity.FromPercent(1).ToBaseUnit(); - Assert.Equal(RelativeHumidity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = RelativeHumidity.Units.FirstOrDefault(u => u != RelativeHumidity.BaseUnit && u != RelativeHumidityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == RelativeHumidityUnit.Undefined) + fromUnit = RelativeHumidity.BaseUnit; + + var quantity = RelativeHumidity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs index 634a40430b..63d84cdbdc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class RotationalAccelerationTestsBase : QuantityTestsBas protected virtual double RevolutionsPerSecondSquaredTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RotationalAccelerationUnit unit) + { + return unit switch + { + RotationalAccelerationUnit.DegreePerSecondSquared => (DegreesPerSecondSquaredInOneRadianPerSecondSquared, DegreesPerSecondSquaredTolerance), + RotationalAccelerationUnit.RadianPerSecondSquared => (RadiansPerSecondSquaredInOneRadianPerSecondSquared, RadiansPerSecondSquaredTolerance), + RotationalAccelerationUnit.RevolutionPerMinutePerSecond => (RevolutionsPerMinutePerSecondInOneRadianPerSecondSquared, RevolutionsPerMinutePerSecondTolerance), + RotationalAccelerationUnit.RevolutionPerSecondSquared => (RevolutionsPerSecondSquaredInOneRadianPerSecondSquared, RevolutionsPerSecondSquaredTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { RotationalAccelerationUnit.DegreePerSecondSquared }, + new object[] { RotationalAccelerationUnit.RadianPerSecondSquared }, + new object[] { RotationalAccelerationUnit.RevolutionPerMinutePerSecond }, + new object[] { RotationalAccelerationUnit.RevolutionPerSecondSquared }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(RotationalAccelerationUnit unit) { - var radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); + var inBaseUnits = RotationalAcceleration.From(1.0, RotationalAcceleration.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var degreepersecondsquaredQuantity = radianpersecondsquared.ToUnit(RotationalAccelerationUnit.DegreePerSecondSquared); - AssertEx.EqualTolerance(DegreesPerSecondSquaredInOneRadianPerSecondSquared, (double)degreepersecondsquaredQuantity.Value, DegreesPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.DegreePerSecondSquared, degreepersecondsquaredQuantity.Unit); - - var radianpersecondsquaredQuantity = radianpersecondsquared.ToUnit(RotationalAccelerationUnit.RadianPerSecondSquared); - AssertEx.EqualTolerance(RadiansPerSecondSquaredInOneRadianPerSecondSquared, (double)radianpersecondsquaredQuantity.Value, RadiansPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.RadianPerSecondSquared, radianpersecondsquaredQuantity.Unit); - - var revolutionperminutepersecondQuantity = radianpersecondsquared.ToUnit(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); - AssertEx.EqualTolerance(RevolutionsPerMinutePerSecondInOneRadianPerSecondSquared, (double)revolutionperminutepersecondQuantity.Value, RevolutionsPerMinutePerSecondTolerance); - Assert.Equal(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, revolutionperminutepersecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var revolutionpersecondsquaredQuantity = radianpersecondsquared.ToUnit(RotationalAccelerationUnit.RevolutionPerSecondSquared); - AssertEx.EqualTolerance(RevolutionsPerSecondSquaredInOneRadianPerSecondSquared, (double)revolutionpersecondsquaredQuantity.Value, RevolutionsPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.RevolutionPerSecondSquared, revolutionpersecondsquaredQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(RotationalAccelerationUnit unit) + { + var quantity = RotationalAcceleration.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalAccelerationUnit unit) { - var quantityInBaseUnit = RotationalAcceleration.FromRadiansPerSecondSquared(1).ToBaseUnit(); - Assert.Equal(RotationalAcceleration.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = RotationalAcceleration.Units.FirstOrDefault(u => u != RotationalAcceleration.BaseUnit && u != RotationalAccelerationUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == RotationalAccelerationUnit.Undefined) + fromUnit = RotationalAcceleration.BaseUnit; + + var quantity = RotationalAcceleration.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs index 93cc2fea10..d6e6f12cf1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -67,6 +68,44 @@ public abstract partial class RotationalSpeedTestsBase : QuantityTestsBase protected virtual double RevolutionsPerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RotationalSpeedUnit unit) + { + return unit switch + { + RotationalSpeedUnit.CentiradianPerSecond => (CentiradiansPerSecondInOneRadianPerSecond, CentiradiansPerSecondTolerance), + RotationalSpeedUnit.DeciradianPerSecond => (DeciradiansPerSecondInOneRadianPerSecond, DeciradiansPerSecondTolerance), + RotationalSpeedUnit.DegreePerMinute => (DegreesPerMinuteInOneRadianPerSecond, DegreesPerMinuteTolerance), + RotationalSpeedUnit.DegreePerSecond => (DegreesPerSecondInOneRadianPerSecond, DegreesPerSecondTolerance), + RotationalSpeedUnit.MicrodegreePerSecond => (MicrodegreesPerSecondInOneRadianPerSecond, MicrodegreesPerSecondTolerance), + RotationalSpeedUnit.MicroradianPerSecond => (MicroradiansPerSecondInOneRadianPerSecond, MicroradiansPerSecondTolerance), + RotationalSpeedUnit.MillidegreePerSecond => (MillidegreesPerSecondInOneRadianPerSecond, MillidegreesPerSecondTolerance), + RotationalSpeedUnit.MilliradianPerSecond => (MilliradiansPerSecondInOneRadianPerSecond, MilliradiansPerSecondTolerance), + RotationalSpeedUnit.NanodegreePerSecond => (NanodegreesPerSecondInOneRadianPerSecond, NanodegreesPerSecondTolerance), + RotationalSpeedUnit.NanoradianPerSecond => (NanoradiansPerSecondInOneRadianPerSecond, NanoradiansPerSecondTolerance), + RotationalSpeedUnit.RadianPerSecond => (RadiansPerSecondInOneRadianPerSecond, RadiansPerSecondTolerance), + RotationalSpeedUnit.RevolutionPerMinute => (RevolutionsPerMinuteInOneRadianPerSecond, RevolutionsPerMinuteTolerance), + RotationalSpeedUnit.RevolutionPerSecond => (RevolutionsPerSecondInOneRadianPerSecond, RevolutionsPerSecondTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { RotationalSpeedUnit.CentiradianPerSecond }, + new object[] { RotationalSpeedUnit.DeciradianPerSecond }, + new object[] { RotationalSpeedUnit.DegreePerMinute }, + new object[] { RotationalSpeedUnit.DegreePerSecond }, + new object[] { RotationalSpeedUnit.MicrodegreePerSecond }, + new object[] { RotationalSpeedUnit.MicroradianPerSecond }, + new object[] { RotationalSpeedUnit.MillidegreePerSecond }, + new object[] { RotationalSpeedUnit.MilliradianPerSecond }, + new object[] { RotationalSpeedUnit.NanodegreePerSecond }, + new object[] { RotationalSpeedUnit.NanoradianPerSecond }, + new object[] { RotationalSpeedUnit.RadianPerSecond }, + new object[] { RotationalSpeedUnit.RevolutionPerMinute }, + new object[] { RotationalSpeedUnit.RevolutionPerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -260,69 +299,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(RotationalSpeedUnit unit) { - var radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - - var centiradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.CentiradianPerSecond); - AssertEx.EqualTolerance(CentiradiansPerSecondInOneRadianPerSecond, (double)centiradianpersecondQuantity.Value, CentiradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.CentiradianPerSecond, centiradianpersecondQuantity.Unit); - - var deciradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.DeciradianPerSecond); - AssertEx.EqualTolerance(DeciradiansPerSecondInOneRadianPerSecond, (double)deciradianpersecondQuantity.Value, DeciradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DeciradianPerSecond, deciradianpersecondQuantity.Unit); - - var degreeperminuteQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.DegreePerMinute); - AssertEx.EqualTolerance(DegreesPerMinuteInOneRadianPerSecond, (double)degreeperminuteQuantity.Value, DegreesPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerMinute, degreeperminuteQuantity.Unit); - - var degreepersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.DegreePerSecond); - AssertEx.EqualTolerance(DegreesPerSecondInOneRadianPerSecond, (double)degreepersecondQuantity.Value, DegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerSecond, degreepersecondQuantity.Unit); - - var microdegreepersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.MicrodegreePerSecond); - AssertEx.EqualTolerance(MicrodegreesPerSecondInOneRadianPerSecond, (double)microdegreepersecondQuantity.Value, MicrodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, microdegreepersecondQuantity.Unit); - - var microradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.MicroradianPerSecond); - AssertEx.EqualTolerance(MicroradiansPerSecondInOneRadianPerSecond, (double)microradianpersecondQuantity.Value, MicroradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicroradianPerSecond, microradianpersecondQuantity.Unit); + var inBaseUnits = RotationalSpeed.From(1.0, RotationalSpeed.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var millidegreepersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.MillidegreePerSecond); - AssertEx.EqualTolerance(MillidegreesPerSecondInOneRadianPerSecond, (double)millidegreepersecondQuantity.Value, MillidegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MillidegreePerSecond, millidegreepersecondQuantity.Unit); - - var milliradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.MilliradianPerSecond); - AssertEx.EqualTolerance(MilliradiansPerSecondInOneRadianPerSecond, (double)milliradianpersecondQuantity.Value, MilliradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MilliradianPerSecond, milliradianpersecondQuantity.Unit); - - var nanodegreepersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.NanodegreePerSecond); - AssertEx.EqualTolerance(NanodegreesPerSecondInOneRadianPerSecond, (double)nanodegreepersecondQuantity.Value, NanodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanodegreePerSecond, nanodegreepersecondQuantity.Unit); - - var nanoradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.NanoradianPerSecond); - AssertEx.EqualTolerance(NanoradiansPerSecondInOneRadianPerSecond, (double)nanoradianpersecondQuantity.Value, NanoradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanoradianPerSecond, nanoradianpersecondQuantity.Unit); - - var radianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.RadianPerSecond); - AssertEx.EqualTolerance(RadiansPerSecondInOneRadianPerSecond, (double)radianpersecondQuantity.Value, RadiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RadianPerSecond, radianpersecondQuantity.Unit); - - var revolutionperminuteQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.RevolutionPerMinute); - AssertEx.EqualTolerance(RevolutionsPerMinuteInOneRadianPerSecond, (double)revolutionperminuteQuantity.Value, RevolutionsPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerMinute, revolutionperminuteQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var revolutionpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.RevolutionPerSecond); - AssertEx.EqualTolerance(RevolutionsPerSecondInOneRadianPerSecond, (double)revolutionpersecondQuantity.Value, RevolutionsPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerSecond, revolutionpersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(RotationalSpeedUnit unit) + { + var quantity = RotationalSpeed.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalSpeedUnit unit) { - var quantityInBaseUnit = RotationalSpeed.FromRadiansPerSecond(1).ToBaseUnit(); - Assert.Equal(RotationalSpeed.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = RotationalSpeed.Units.FirstOrDefault(u => u != RotationalSpeed.BaseUnit && u != RotationalSpeedUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == RotationalSpeedUnit.Undefined) + fromUnit = RotationalSpeed.BaseUnit; + + var quantity = RotationalSpeed.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs index aae2ddea51..763be52685 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -51,6 +52,28 @@ public abstract partial class RotationalStiffnessPerLengthTestsBase : QuantityTe protected virtual double PoundForceFeetPerDegreesPerFeetTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RotationalStiffnessPerLengthUnit unit) + { + return unit switch + { + RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter => (KilonewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance), + RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot => (KilopoundForceFeetPerDegreesPerFeetInOneNewtonMeterPerRadianPerMeter, KilopoundForceFeetPerDegreesPerFeetTolerance), + RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter => (MeganewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance), + RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter => (NewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance), + RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot => (PoundForceFeetPerDegreesPerFeetInOneNewtonMeterPerRadianPerMeter, PoundForceFeetPerDegreesPerFeetTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter }, + new object[] { RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot }, + new object[] { RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter }, + new object[] { RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter }, + new object[] { RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -196,37 +219,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(RotationalStiffnessPerLengthUnit unit) { - var newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - - var kilonewtonmeterperradianpermeterQuantity = newtonmeterperradianpermeter.ToUnit(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); - AssertEx.EqualTolerance(KilonewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, (double)kilonewtonmeterperradianpermeterQuantity.Value, KilonewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, kilonewtonmeterperradianpermeterQuantity.Unit); + var inBaseUnits = RotationalStiffnessPerLength.From(1.0, RotationalStiffnessPerLength.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilopoundforcefootperdegreesperfootQuantity = newtonmeterperradianpermeter.ToUnit(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); - AssertEx.EqualTolerance(KilopoundForceFeetPerDegreesPerFeetInOneNewtonMeterPerRadianPerMeter, (double)kilopoundforcefootperdegreesperfootQuantity.Value, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, kilopoundforcefootperdegreesperfootQuantity.Unit); - - var meganewtonmeterperradianpermeterQuantity = newtonmeterperradianpermeter.ToUnit(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); - AssertEx.EqualTolerance(MeganewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, (double)meganewtonmeterperradianpermeterQuantity.Value, MeganewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, meganewtonmeterperradianpermeterQuantity.Unit); - - var newtonmeterperradianpermeterQuantity = newtonmeterperradianpermeter.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - AssertEx.EqualTolerance(NewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, (double)newtonmeterperradianpermeterQuantity.Value, NewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, newtonmeterperradianpermeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var poundforcefootperdegreesperfootQuantity = newtonmeterperradianpermeter.ToUnit(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); - AssertEx.EqualTolerance(PoundForceFeetPerDegreesPerFeetInOneNewtonMeterPerRadianPerMeter, (double)poundforcefootperdegreesperfootQuantity.Value, PoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, poundforcefootperdegreesperfootQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(RotationalStiffnessPerLengthUnit unit) + { + var quantity = RotationalStiffnessPerLength.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalStiffnessPerLengthUnit unit) { - var quantityInBaseUnit = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1).ToBaseUnit(); - Assert.Equal(RotationalStiffnessPerLength.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = RotationalStiffnessPerLength.Units.FirstOrDefault(u => u != RotationalStiffnessPerLength.BaseUnit && u != RotationalStiffnessPerLengthUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == RotationalStiffnessPerLengthUnit.Undefined) + fromUnit = RotationalStiffnessPerLength.BaseUnit; + + var quantity = RotationalStiffnessPerLength.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs index b5d56b1897..6129bd22c8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -107,6 +108,84 @@ public abstract partial class RotationalStiffnessTestsBase : QuantityTestsBase protected virtual double PoundForceFeetPerDegreesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RotationalStiffnessUnit unit) + { + return unit switch + { + RotationalStiffnessUnit.CentinewtonMeterPerDegree => (CentinewtonMetersPerDegreeInOneNewtonMeterPerRadian, CentinewtonMetersPerDegreeTolerance), + RotationalStiffnessUnit.CentinewtonMillimeterPerDegree => (CentinewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, CentinewtonMillimetersPerDegreeTolerance), + RotationalStiffnessUnit.CentinewtonMillimeterPerRadian => (CentinewtonMillimetersPerRadianInOneNewtonMeterPerRadian, CentinewtonMillimetersPerRadianTolerance), + RotationalStiffnessUnit.DecanewtonMeterPerDegree => (DecanewtonMetersPerDegreeInOneNewtonMeterPerRadian, DecanewtonMetersPerDegreeTolerance), + RotationalStiffnessUnit.DecanewtonMillimeterPerDegree => (DecanewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, DecanewtonMillimetersPerDegreeTolerance), + RotationalStiffnessUnit.DecanewtonMillimeterPerRadian => (DecanewtonMillimetersPerRadianInOneNewtonMeterPerRadian, DecanewtonMillimetersPerRadianTolerance), + RotationalStiffnessUnit.DecinewtonMeterPerDegree => (DecinewtonMetersPerDegreeInOneNewtonMeterPerRadian, DecinewtonMetersPerDegreeTolerance), + RotationalStiffnessUnit.DecinewtonMillimeterPerDegree => (DecinewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, DecinewtonMillimetersPerDegreeTolerance), + RotationalStiffnessUnit.DecinewtonMillimeterPerRadian => (DecinewtonMillimetersPerRadianInOneNewtonMeterPerRadian, DecinewtonMillimetersPerRadianTolerance), + RotationalStiffnessUnit.KilonewtonMeterPerDegree => (KilonewtonMetersPerDegreeInOneNewtonMeterPerRadian, KilonewtonMetersPerDegreeTolerance), + RotationalStiffnessUnit.KilonewtonMeterPerRadian => (KilonewtonMetersPerRadianInOneNewtonMeterPerRadian, KilonewtonMetersPerRadianTolerance), + RotationalStiffnessUnit.KilonewtonMillimeterPerDegree => (KilonewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, KilonewtonMillimetersPerDegreeTolerance), + RotationalStiffnessUnit.KilonewtonMillimeterPerRadian => (KilonewtonMillimetersPerRadianInOneNewtonMeterPerRadian, KilonewtonMillimetersPerRadianTolerance), + RotationalStiffnessUnit.KilopoundForceFootPerDegrees => (KilopoundForceFeetPerDegreesInOneNewtonMeterPerRadian, KilopoundForceFeetPerDegreesTolerance), + RotationalStiffnessUnit.MeganewtonMeterPerDegree => (MeganewtonMetersPerDegreeInOneNewtonMeterPerRadian, MeganewtonMetersPerDegreeTolerance), + RotationalStiffnessUnit.MeganewtonMeterPerRadian => (MeganewtonMetersPerRadianInOneNewtonMeterPerRadian, MeganewtonMetersPerRadianTolerance), + RotationalStiffnessUnit.MeganewtonMillimeterPerDegree => (MeganewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, MeganewtonMillimetersPerDegreeTolerance), + RotationalStiffnessUnit.MeganewtonMillimeterPerRadian => (MeganewtonMillimetersPerRadianInOneNewtonMeterPerRadian, MeganewtonMillimetersPerRadianTolerance), + RotationalStiffnessUnit.MicronewtonMeterPerDegree => (MicronewtonMetersPerDegreeInOneNewtonMeterPerRadian, MicronewtonMetersPerDegreeTolerance), + RotationalStiffnessUnit.MicronewtonMillimeterPerDegree => (MicronewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, MicronewtonMillimetersPerDegreeTolerance), + RotationalStiffnessUnit.MicronewtonMillimeterPerRadian => (MicronewtonMillimetersPerRadianInOneNewtonMeterPerRadian, MicronewtonMillimetersPerRadianTolerance), + RotationalStiffnessUnit.MillinewtonMeterPerDegree => (MillinewtonMetersPerDegreeInOneNewtonMeterPerRadian, MillinewtonMetersPerDegreeTolerance), + RotationalStiffnessUnit.MillinewtonMillimeterPerDegree => (MillinewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, MillinewtonMillimetersPerDegreeTolerance), + RotationalStiffnessUnit.MillinewtonMillimeterPerRadian => (MillinewtonMillimetersPerRadianInOneNewtonMeterPerRadian, MillinewtonMillimetersPerRadianTolerance), + RotationalStiffnessUnit.NanonewtonMeterPerDegree => (NanonewtonMetersPerDegreeInOneNewtonMeterPerRadian, NanonewtonMetersPerDegreeTolerance), + RotationalStiffnessUnit.NanonewtonMillimeterPerDegree => (NanonewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, NanonewtonMillimetersPerDegreeTolerance), + RotationalStiffnessUnit.NanonewtonMillimeterPerRadian => (NanonewtonMillimetersPerRadianInOneNewtonMeterPerRadian, NanonewtonMillimetersPerRadianTolerance), + RotationalStiffnessUnit.NewtonMeterPerDegree => (NewtonMetersPerDegreeInOneNewtonMeterPerRadian, NewtonMetersPerDegreeTolerance), + RotationalStiffnessUnit.NewtonMeterPerRadian => (NewtonMetersPerRadianInOneNewtonMeterPerRadian, NewtonMetersPerRadianTolerance), + RotationalStiffnessUnit.NewtonMillimeterPerDegree => (NewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, NewtonMillimetersPerDegreeTolerance), + RotationalStiffnessUnit.NewtonMillimeterPerRadian => (NewtonMillimetersPerRadianInOneNewtonMeterPerRadian, NewtonMillimetersPerRadianTolerance), + RotationalStiffnessUnit.PoundForceFeetPerRadian => (PoundForceFeetPerRadianInOneNewtonMeterPerRadian, PoundForceFeetPerRadianTolerance), + RotationalStiffnessUnit.PoundForceFootPerDegrees => (PoundForceFeetPerDegreesInOneNewtonMeterPerRadian, PoundForceFeetPerDegreesTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { RotationalStiffnessUnit.CentinewtonMeterPerDegree }, + new object[] { RotationalStiffnessUnit.CentinewtonMillimeterPerDegree }, + new object[] { RotationalStiffnessUnit.CentinewtonMillimeterPerRadian }, + new object[] { RotationalStiffnessUnit.DecanewtonMeterPerDegree }, + new object[] { RotationalStiffnessUnit.DecanewtonMillimeterPerDegree }, + new object[] { RotationalStiffnessUnit.DecanewtonMillimeterPerRadian }, + new object[] { RotationalStiffnessUnit.DecinewtonMeterPerDegree }, + new object[] { RotationalStiffnessUnit.DecinewtonMillimeterPerDegree }, + new object[] { RotationalStiffnessUnit.DecinewtonMillimeterPerRadian }, + new object[] { RotationalStiffnessUnit.KilonewtonMeterPerDegree }, + new object[] { RotationalStiffnessUnit.KilonewtonMeterPerRadian }, + new object[] { RotationalStiffnessUnit.KilonewtonMillimeterPerDegree }, + new object[] { RotationalStiffnessUnit.KilonewtonMillimeterPerRadian }, + new object[] { RotationalStiffnessUnit.KilopoundForceFootPerDegrees }, + new object[] { RotationalStiffnessUnit.MeganewtonMeterPerDegree }, + new object[] { RotationalStiffnessUnit.MeganewtonMeterPerRadian }, + new object[] { RotationalStiffnessUnit.MeganewtonMillimeterPerDegree }, + new object[] { RotationalStiffnessUnit.MeganewtonMillimeterPerRadian }, + new object[] { RotationalStiffnessUnit.MicronewtonMeterPerDegree }, + new object[] { RotationalStiffnessUnit.MicronewtonMillimeterPerDegree }, + new object[] { RotationalStiffnessUnit.MicronewtonMillimeterPerRadian }, + new object[] { RotationalStiffnessUnit.MillinewtonMeterPerDegree }, + new object[] { RotationalStiffnessUnit.MillinewtonMillimeterPerDegree }, + new object[] { RotationalStiffnessUnit.MillinewtonMillimeterPerRadian }, + new object[] { RotationalStiffnessUnit.NanonewtonMeterPerDegree }, + new object[] { RotationalStiffnessUnit.NanonewtonMillimeterPerDegree }, + new object[] { RotationalStiffnessUnit.NanonewtonMillimeterPerRadian }, + new object[] { RotationalStiffnessUnit.NewtonMeterPerDegree }, + new object[] { RotationalStiffnessUnit.NewtonMeterPerRadian }, + new object[] { RotationalStiffnessUnit.NewtonMillimeterPerDegree }, + new object[] { RotationalStiffnessUnit.NewtonMillimeterPerRadian }, + new object[] { RotationalStiffnessUnit.PoundForceFeetPerRadian }, + new object[] { RotationalStiffnessUnit.PoundForceFootPerDegrees }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -420,149 +499,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(RotationalStiffnessUnit unit) { - var newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - - var centinewtonmeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.CentinewtonMeterPerDegree); - AssertEx.EqualTolerance(CentinewtonMetersPerDegreeInOneNewtonMeterPerRadian, (double)centinewtonmeterperdegreeQuantity.Value, CentinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, centinewtonmeterperdegreeQuantity.Unit); - - var centinewtonmillimeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); - AssertEx.EqualTolerance(CentinewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, (double)centinewtonmillimeterperdegreeQuantity.Value, CentinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, centinewtonmillimeterperdegreeQuantity.Unit); - - var centinewtonmillimeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); - AssertEx.EqualTolerance(CentinewtonMillimetersPerRadianInOneNewtonMeterPerRadian, (double)centinewtonmillimeterperradianQuantity.Value, CentinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, centinewtonmillimeterperradianQuantity.Unit); - - var decanewtonmeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.DecanewtonMeterPerDegree); - AssertEx.EqualTolerance(DecanewtonMetersPerDegreeInOneNewtonMeterPerRadian, (double)decanewtonmeterperdegreeQuantity.Value, DecanewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, decanewtonmeterperdegreeQuantity.Unit); - - var decanewtonmillimeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); - AssertEx.EqualTolerance(DecanewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, (double)decanewtonmillimeterperdegreeQuantity.Value, DecanewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, decanewtonmillimeterperdegreeQuantity.Unit); - - var decanewtonmillimeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); - AssertEx.EqualTolerance(DecanewtonMillimetersPerRadianInOneNewtonMeterPerRadian, (double)decanewtonmillimeterperradianQuantity.Value, DecanewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, decanewtonmillimeterperradianQuantity.Unit); - - var decinewtonmeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.DecinewtonMeterPerDegree); - AssertEx.EqualTolerance(DecinewtonMetersPerDegreeInOneNewtonMeterPerRadian, (double)decinewtonmeterperdegreeQuantity.Value, DecinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, decinewtonmeterperdegreeQuantity.Unit); - - var decinewtonmillimeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); - AssertEx.EqualTolerance(DecinewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, (double)decinewtonmillimeterperdegreeQuantity.Value, DecinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, decinewtonmillimeterperdegreeQuantity.Unit); - - var decinewtonmillimeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); - AssertEx.EqualTolerance(DecinewtonMillimetersPerRadianInOneNewtonMeterPerRadian, (double)decinewtonmillimeterperradianQuantity.Value, DecinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, decinewtonmillimeterperradianQuantity.Unit); - - var kilonewtonmeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.KilonewtonMeterPerDegree); - AssertEx.EqualTolerance(KilonewtonMetersPerDegreeInOneNewtonMeterPerRadian, (double)kilonewtonmeterperdegreeQuantity.Value, KilonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, kilonewtonmeterperdegreeQuantity.Unit); - - var kilonewtonmeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.KilonewtonMeterPerRadian); - AssertEx.EqualTolerance(KilonewtonMetersPerRadianInOneNewtonMeterPerRadian, (double)kilonewtonmeterperradianQuantity.Value, KilonewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerRadian, kilonewtonmeterperradianQuantity.Unit); - - var kilonewtonmillimeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); - AssertEx.EqualTolerance(KilonewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, (double)kilonewtonmillimeterperdegreeQuantity.Value, KilonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, kilonewtonmillimeterperdegreeQuantity.Unit); - - var kilonewtonmillimeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); - AssertEx.EqualTolerance(KilonewtonMillimetersPerRadianInOneNewtonMeterPerRadian, (double)kilonewtonmillimeterperradianQuantity.Value, KilonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, kilonewtonmillimeterperradianQuantity.Unit); - - var kilopoundforcefootperdegreesQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.KilopoundForceFootPerDegrees); - AssertEx.EqualTolerance(KilopoundForceFeetPerDegreesInOneNewtonMeterPerRadian, (double)kilopoundforcefootperdegreesQuantity.Value, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, kilopoundforcefootperdegreesQuantity.Unit); - - var meganewtonmeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MeganewtonMeterPerDegree); - AssertEx.EqualTolerance(MeganewtonMetersPerDegreeInOneNewtonMeterPerRadian, (double)meganewtonmeterperdegreeQuantity.Value, MeganewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerDegree, meganewtonmeterperdegreeQuantity.Unit); + var inBaseUnits = RotationalStiffness.From(1.0, RotationalStiffness.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var meganewtonmeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MeganewtonMeterPerRadian); - AssertEx.EqualTolerance(MeganewtonMetersPerRadianInOneNewtonMeterPerRadian, (double)meganewtonmeterperradianQuantity.Value, MeganewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerRadian, meganewtonmeterperradianQuantity.Unit); - - var meganewtonmillimeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); - AssertEx.EqualTolerance(MeganewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, (double)meganewtonmillimeterperdegreeQuantity.Value, MeganewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, meganewtonmillimeterperdegreeQuantity.Unit); - - var meganewtonmillimeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); - AssertEx.EqualTolerance(MeganewtonMillimetersPerRadianInOneNewtonMeterPerRadian, (double)meganewtonmillimeterperradianQuantity.Value, MeganewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, meganewtonmillimeterperradianQuantity.Unit); - - var micronewtonmeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MicronewtonMeterPerDegree); - AssertEx.EqualTolerance(MicronewtonMetersPerDegreeInOneNewtonMeterPerRadian, (double)micronewtonmeterperdegreeQuantity.Value, MicronewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, micronewtonmeterperdegreeQuantity.Unit); - - var micronewtonmillimeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); - AssertEx.EqualTolerance(MicronewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, (double)micronewtonmillimeterperdegreeQuantity.Value, MicronewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, micronewtonmillimeterperdegreeQuantity.Unit); - - var micronewtonmillimeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); - AssertEx.EqualTolerance(MicronewtonMillimetersPerRadianInOneNewtonMeterPerRadian, (double)micronewtonmillimeterperradianQuantity.Value, MicronewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, micronewtonmillimeterperradianQuantity.Unit); - - var millinewtonmeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MillinewtonMeterPerDegree); - AssertEx.EqualTolerance(MillinewtonMetersPerDegreeInOneNewtonMeterPerRadian, (double)millinewtonmeterperdegreeQuantity.Value, MillinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMeterPerDegree, millinewtonmeterperdegreeQuantity.Unit); - - var millinewtonmillimeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); - AssertEx.EqualTolerance(MillinewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, (double)millinewtonmillimeterperdegreeQuantity.Value, MillinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, millinewtonmillimeterperdegreeQuantity.Unit); - - var millinewtonmillimeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); - AssertEx.EqualTolerance(MillinewtonMillimetersPerRadianInOneNewtonMeterPerRadian, (double)millinewtonmillimeterperradianQuantity.Value, MillinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, millinewtonmillimeterperradianQuantity.Unit); - - var nanonewtonmeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.NanonewtonMeterPerDegree); - AssertEx.EqualTolerance(NanonewtonMetersPerDegreeInOneNewtonMeterPerRadian, (double)nanonewtonmeterperdegreeQuantity.Value, NanonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, nanonewtonmeterperdegreeQuantity.Unit); - - var nanonewtonmillimeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); - AssertEx.EqualTolerance(NanonewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, (double)nanonewtonmillimeterperdegreeQuantity.Value, NanonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, nanonewtonmillimeterperdegreeQuantity.Unit); - - var nanonewtonmillimeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); - AssertEx.EqualTolerance(NanonewtonMillimetersPerRadianInOneNewtonMeterPerRadian, (double)nanonewtonmillimeterperradianQuantity.Value, NanonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, nanonewtonmillimeterperradianQuantity.Unit); - - var newtonmeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.NewtonMeterPerDegree); - AssertEx.EqualTolerance(NewtonMetersPerDegreeInOneNewtonMeterPerRadian, (double)newtonmeterperdegreeQuantity.Value, NewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, newtonmeterperdegreeQuantity.Unit); - - var newtonmeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian); - AssertEx.EqualTolerance(NewtonMetersPerRadianInOneNewtonMeterPerRadian, (double)newtonmeterperradianQuantity.Value, NewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerRadian, newtonmeterperradianQuantity.Unit); - - var newtonmillimeterperdegreeQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.NewtonMillimeterPerDegree); - AssertEx.EqualTolerance(NewtonMillimetersPerDegreeInOneNewtonMeterPerRadian, (double)newtonmillimeterperdegreeQuantity.Value, NewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, newtonmillimeterperdegreeQuantity.Unit); - - var newtonmillimeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.NewtonMillimeterPerRadian); - AssertEx.EqualTolerance(NewtonMillimetersPerRadianInOneNewtonMeterPerRadian, (double)newtonmillimeterperradianQuantity.Value, NewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerRadian, newtonmillimeterperradianQuantity.Unit); - - var poundforcefeetperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.PoundForceFeetPerRadian); - AssertEx.EqualTolerance(PoundForceFeetPerRadianInOneNewtonMeterPerRadian, (double)poundforcefeetperradianQuantity.Value, PoundForceFeetPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.PoundForceFeetPerRadian, poundforcefeetperradianQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var poundforcefootperdegreesQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.PoundForceFootPerDegrees); - AssertEx.EqualTolerance(PoundForceFeetPerDegreesInOneNewtonMeterPerRadian, (double)poundforcefootperdegreesQuantity.Value, PoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.PoundForceFootPerDegrees, poundforcefootperdegreesQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(RotationalStiffnessUnit unit) + { + var quantity = RotationalStiffness.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalStiffnessUnit unit) { - var quantityInBaseUnit = RotationalStiffness.FromNewtonMetersPerRadian(1).ToBaseUnit(); - Assert.Equal(RotationalStiffness.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = RotationalStiffness.Units.FirstOrDefault(u => u != RotationalStiffness.BaseUnit && u != RotationalStiffnessUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == RotationalStiffnessUnit.Undefined) + fromUnit = RotationalStiffness.BaseUnit; + + var quantity = RotationalStiffness.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs index d01595760c..0a1f6c8422 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class ScalarTestsBase : QuantityTestsBase protected virtual double AmountTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ScalarUnit unit) + { + return unit switch + { + ScalarUnit.Amount => (AmountInOneAmount, AmountTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ScalarUnit.Amount }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ScalarUnit unit) { - var amount = Scalar.FromAmount(1); + var inBaseUnits = Scalar.From(1.0, Scalar.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var amountQuantity = amount.ToUnit(ScalarUnit.Amount); - AssertEx.EqualTolerance(AmountInOneAmount, (double)amountQuantity.Value, AmountTolerance); - Assert.Equal(ScalarUnit.Amount, amountQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ScalarUnit unit) + { + var quantity = Scalar.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ScalarUnit unit) { - var quantityInBaseUnit = Scalar.FromAmount(1).ToBaseUnit(); - Assert.Equal(Scalar.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Scalar.Units.FirstOrDefault(u => u != Scalar.BaseUnit && u != ScalarUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ScalarUnit.Undefined) + fromUnit = Scalar.BaseUnit; + + var quantity = Scalar.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs index 5c9b1a4ebb..505594fca5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class SolidAngleTestsBase : QuantityTestsBase protected virtual double SteradiansTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SolidAngleUnit unit) + { + return unit switch + { + SolidAngleUnit.Steradian => (SteradiansInOneSteradian, SteradiansTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { SolidAngleUnit.Steradian }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(SolidAngleUnit unit) { - var steradian = SolidAngle.FromSteradians(1); + var inBaseUnits = SolidAngle.From(1.0, SolidAngle.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var steradianQuantity = steradian.ToUnit(SolidAngleUnit.Steradian); - AssertEx.EqualTolerance(SteradiansInOneSteradian, (double)steradianQuantity.Value, SteradiansTolerance); - Assert.Equal(SolidAngleUnit.Steradian, steradianQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(SolidAngleUnit unit) + { + var quantity = SolidAngle.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SolidAngleUnit unit) { - var quantityInBaseUnit = SolidAngle.FromSteradians(1).ToBaseUnit(); - Assert.Equal(SolidAngle.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = SolidAngle.Units.FirstOrDefault(u => u != SolidAngle.BaseUnit && u != SolidAngleUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == SolidAngleUnit.Undefined) + fromUnit = SolidAngle.BaseUnit; + + var quantity = SolidAngle.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs index 4a59195ae3..00999677a8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -91,6 +92,68 @@ public abstract partial class SpecificEnergyTestsBase : QuantityTestsBase protected virtual double WattHoursPerKilogramTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificEnergyUnit unit) + { + return unit switch + { + SpecificEnergyUnit.BtuPerPound => (BtuPerPoundInOneJoulePerKilogram, BtuPerPoundTolerance), + SpecificEnergyUnit.CaloriePerGram => (CaloriesPerGramInOneJoulePerKilogram, CaloriesPerGramTolerance), + SpecificEnergyUnit.GigawattDayPerKilogram => (GigawattDaysPerKilogramInOneJoulePerKilogram, GigawattDaysPerKilogramTolerance), + SpecificEnergyUnit.GigawattDayPerShortTon => (GigawattDaysPerShortTonInOneJoulePerKilogram, GigawattDaysPerShortTonTolerance), + SpecificEnergyUnit.GigawattDayPerTonne => (GigawattDaysPerTonneInOneJoulePerKilogram, GigawattDaysPerTonneTolerance), + SpecificEnergyUnit.GigawattHourPerKilogram => (GigawattHoursPerKilogramInOneJoulePerKilogram, GigawattHoursPerKilogramTolerance), + SpecificEnergyUnit.JoulePerKilogram => (JoulesPerKilogramInOneJoulePerKilogram, JoulesPerKilogramTolerance), + SpecificEnergyUnit.KilocaloriePerGram => (KilocaloriesPerGramInOneJoulePerKilogram, KilocaloriesPerGramTolerance), + SpecificEnergyUnit.KilojoulePerKilogram => (KilojoulesPerKilogramInOneJoulePerKilogram, KilojoulesPerKilogramTolerance), + SpecificEnergyUnit.KilowattDayPerKilogram => (KilowattDaysPerKilogramInOneJoulePerKilogram, KilowattDaysPerKilogramTolerance), + SpecificEnergyUnit.KilowattDayPerShortTon => (KilowattDaysPerShortTonInOneJoulePerKilogram, KilowattDaysPerShortTonTolerance), + SpecificEnergyUnit.KilowattDayPerTonne => (KilowattDaysPerTonneInOneJoulePerKilogram, KilowattDaysPerTonneTolerance), + SpecificEnergyUnit.KilowattHourPerKilogram => (KilowattHoursPerKilogramInOneJoulePerKilogram, KilowattHoursPerKilogramTolerance), + SpecificEnergyUnit.MegajoulePerKilogram => (MegajoulesPerKilogramInOneJoulePerKilogram, MegajoulesPerKilogramTolerance), + SpecificEnergyUnit.MegawattDayPerKilogram => (MegawattDaysPerKilogramInOneJoulePerKilogram, MegawattDaysPerKilogramTolerance), + SpecificEnergyUnit.MegawattDayPerShortTon => (MegawattDaysPerShortTonInOneJoulePerKilogram, MegawattDaysPerShortTonTolerance), + SpecificEnergyUnit.MegawattDayPerTonne => (MegawattDaysPerTonneInOneJoulePerKilogram, MegawattDaysPerTonneTolerance), + SpecificEnergyUnit.MegawattHourPerKilogram => (MegawattHoursPerKilogramInOneJoulePerKilogram, MegawattHoursPerKilogramTolerance), + SpecificEnergyUnit.TerawattDayPerKilogram => (TerawattDaysPerKilogramInOneJoulePerKilogram, TerawattDaysPerKilogramTolerance), + SpecificEnergyUnit.TerawattDayPerShortTon => (TerawattDaysPerShortTonInOneJoulePerKilogram, TerawattDaysPerShortTonTolerance), + SpecificEnergyUnit.TerawattDayPerTonne => (TerawattDaysPerTonneInOneJoulePerKilogram, TerawattDaysPerTonneTolerance), + SpecificEnergyUnit.WattDayPerKilogram => (WattDaysPerKilogramInOneJoulePerKilogram, WattDaysPerKilogramTolerance), + SpecificEnergyUnit.WattDayPerShortTon => (WattDaysPerShortTonInOneJoulePerKilogram, WattDaysPerShortTonTolerance), + SpecificEnergyUnit.WattDayPerTonne => (WattDaysPerTonneInOneJoulePerKilogram, WattDaysPerTonneTolerance), + SpecificEnergyUnit.WattHourPerKilogram => (WattHoursPerKilogramInOneJoulePerKilogram, WattHoursPerKilogramTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { SpecificEnergyUnit.BtuPerPound }, + new object[] { SpecificEnergyUnit.CaloriePerGram }, + new object[] { SpecificEnergyUnit.GigawattDayPerKilogram }, + new object[] { SpecificEnergyUnit.GigawattDayPerShortTon }, + new object[] { SpecificEnergyUnit.GigawattDayPerTonne }, + new object[] { SpecificEnergyUnit.GigawattHourPerKilogram }, + new object[] { SpecificEnergyUnit.JoulePerKilogram }, + new object[] { SpecificEnergyUnit.KilocaloriePerGram }, + new object[] { SpecificEnergyUnit.KilojoulePerKilogram }, + new object[] { SpecificEnergyUnit.KilowattDayPerKilogram }, + new object[] { SpecificEnergyUnit.KilowattDayPerShortTon }, + new object[] { SpecificEnergyUnit.KilowattDayPerTonne }, + new object[] { SpecificEnergyUnit.KilowattHourPerKilogram }, + new object[] { SpecificEnergyUnit.MegajoulePerKilogram }, + new object[] { SpecificEnergyUnit.MegawattDayPerKilogram }, + new object[] { SpecificEnergyUnit.MegawattDayPerShortTon }, + new object[] { SpecificEnergyUnit.MegawattDayPerTonne }, + new object[] { SpecificEnergyUnit.MegawattHourPerKilogram }, + new object[] { SpecificEnergyUnit.TerawattDayPerKilogram }, + new object[] { SpecificEnergyUnit.TerawattDayPerShortTon }, + new object[] { SpecificEnergyUnit.TerawattDayPerTonne }, + new object[] { SpecificEnergyUnit.WattDayPerKilogram }, + new object[] { SpecificEnergyUnit.WattDayPerShortTon }, + new object[] { SpecificEnergyUnit.WattDayPerTonne }, + new object[] { SpecificEnergyUnit.WattHourPerKilogram }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -356,117 +419,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(SpecificEnergyUnit unit) { - var jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - - var btuperpoundQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.BtuPerPound); - AssertEx.EqualTolerance(BtuPerPoundInOneJoulePerKilogram, (double)btuperpoundQuantity.Value, BtuPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.BtuPerPound, btuperpoundQuantity.Unit); - - var caloriepergramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.CaloriePerGram); - AssertEx.EqualTolerance(CaloriesPerGramInOneJoulePerKilogram, (double)caloriepergramQuantity.Value, CaloriesPerGramTolerance); - Assert.Equal(SpecificEnergyUnit.CaloriePerGram, caloriepergramQuantity.Unit); - - var gigawattdayperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.GigawattDayPerKilogram); - AssertEx.EqualTolerance(GigawattDaysPerKilogramInOneJoulePerKilogram, (double)gigawattdayperkilogramQuantity.Value, GigawattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattDayPerKilogram, gigawattdayperkilogramQuantity.Unit); - - var gigawattdaypershorttonQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.GigawattDayPerShortTon); - AssertEx.EqualTolerance(GigawattDaysPerShortTonInOneJoulePerKilogram, (double)gigawattdaypershorttonQuantity.Value, GigawattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattDayPerShortTon, gigawattdaypershorttonQuantity.Unit); - - var gigawattdaypertonneQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.GigawattDayPerTonne); - AssertEx.EqualTolerance(GigawattDaysPerTonneInOneJoulePerKilogram, (double)gigawattdaypertonneQuantity.Value, GigawattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattDayPerTonne, gigawattdaypertonneQuantity.Unit); - - var gigawatthourperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.GigawattHourPerKilogram); - AssertEx.EqualTolerance(GigawattHoursPerKilogramInOneJoulePerKilogram, (double)gigawatthourperkilogramQuantity.Value, GigawattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattHourPerKilogram, gigawatthourperkilogramQuantity.Unit); - - var jouleperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.JoulePerKilogram); - AssertEx.EqualTolerance(JoulesPerKilogramInOneJoulePerKilogram, (double)jouleperkilogramQuantity.Value, JoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.JoulePerKilogram, jouleperkilogramQuantity.Unit); - - var kilocaloriepergramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.KilocaloriePerGram); - AssertEx.EqualTolerance(KilocaloriesPerGramInOneJoulePerKilogram, (double)kilocaloriepergramQuantity.Value, KilocaloriesPerGramTolerance); - Assert.Equal(SpecificEnergyUnit.KilocaloriePerGram, kilocaloriepergramQuantity.Unit); - - var kilojouleperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.KilojoulePerKilogram); - AssertEx.EqualTolerance(KilojoulesPerKilogramInOneJoulePerKilogram, (double)kilojouleperkilogramQuantity.Value, KilojoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilojoulePerKilogram, kilojouleperkilogramQuantity.Unit); - - var kilowattdayperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.KilowattDayPerKilogram); - AssertEx.EqualTolerance(KilowattDaysPerKilogramInOneJoulePerKilogram, (double)kilowattdayperkilogramQuantity.Value, KilowattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattDayPerKilogram, kilowattdayperkilogramQuantity.Unit); - - var kilowattdaypershorttonQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.KilowattDayPerShortTon); - AssertEx.EqualTolerance(KilowattDaysPerShortTonInOneJoulePerKilogram, (double)kilowattdaypershorttonQuantity.Value, KilowattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattDayPerShortTon, kilowattdaypershorttonQuantity.Unit); - - var kilowattdaypertonneQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.KilowattDayPerTonne); - AssertEx.EqualTolerance(KilowattDaysPerTonneInOneJoulePerKilogram, (double)kilowattdaypertonneQuantity.Value, KilowattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattDayPerTonne, kilowattdaypertonneQuantity.Unit); + var inBaseUnits = SpecificEnergy.From(1.0, SpecificEnergy.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilowatthourperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.KilowattHourPerKilogram); - AssertEx.EqualTolerance(KilowattHoursPerKilogramInOneJoulePerKilogram, (double)kilowatthourperkilogramQuantity.Value, KilowattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattHourPerKilogram, kilowatthourperkilogramQuantity.Unit); - - var megajouleperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.MegajoulePerKilogram); - AssertEx.EqualTolerance(MegajoulesPerKilogramInOneJoulePerKilogram, (double)megajouleperkilogramQuantity.Value, MegajoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegajoulePerKilogram, megajouleperkilogramQuantity.Unit); - - var megawattdayperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.MegawattDayPerKilogram); - AssertEx.EqualTolerance(MegawattDaysPerKilogramInOneJoulePerKilogram, (double)megawattdayperkilogramQuantity.Value, MegawattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattDayPerKilogram, megawattdayperkilogramQuantity.Unit); - - var megawattdaypershorttonQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.MegawattDayPerShortTon); - AssertEx.EqualTolerance(MegawattDaysPerShortTonInOneJoulePerKilogram, (double)megawattdaypershorttonQuantity.Value, MegawattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattDayPerShortTon, megawattdaypershorttonQuantity.Unit); - - var megawattdaypertonneQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.MegawattDayPerTonne); - AssertEx.EqualTolerance(MegawattDaysPerTonneInOneJoulePerKilogram, (double)megawattdaypertonneQuantity.Value, MegawattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattDayPerTonne, megawattdaypertonneQuantity.Unit); - - var megawatthourperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.MegawattHourPerKilogram); - AssertEx.EqualTolerance(MegawattHoursPerKilogramInOneJoulePerKilogram, (double)megawatthourperkilogramQuantity.Value, MegawattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattHourPerKilogram, megawatthourperkilogramQuantity.Unit); - - var terawattdayperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.TerawattDayPerKilogram); - AssertEx.EqualTolerance(TerawattDaysPerKilogramInOneJoulePerKilogram, (double)terawattdayperkilogramQuantity.Value, TerawattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.TerawattDayPerKilogram, terawattdayperkilogramQuantity.Unit); - - var terawattdaypershorttonQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.TerawattDayPerShortTon); - AssertEx.EqualTolerance(TerawattDaysPerShortTonInOneJoulePerKilogram, (double)terawattdaypershorttonQuantity.Value, TerawattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.TerawattDayPerShortTon, terawattdaypershorttonQuantity.Unit); - - var terawattdaypertonneQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.TerawattDayPerTonne); - AssertEx.EqualTolerance(TerawattDaysPerTonneInOneJoulePerKilogram, (double)terawattdaypertonneQuantity.Value, TerawattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.TerawattDayPerTonne, terawattdaypertonneQuantity.Unit); - - var wattdayperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.WattDayPerKilogram); - AssertEx.EqualTolerance(WattDaysPerKilogramInOneJoulePerKilogram, (double)wattdayperkilogramQuantity.Value, WattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.WattDayPerKilogram, wattdayperkilogramQuantity.Unit); - - var wattdaypershorttonQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.WattDayPerShortTon); - AssertEx.EqualTolerance(WattDaysPerShortTonInOneJoulePerKilogram, (double)wattdaypershorttonQuantity.Value, WattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.WattDayPerShortTon, wattdaypershorttonQuantity.Unit); - - var wattdaypertonneQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.WattDayPerTonne); - AssertEx.EqualTolerance(WattDaysPerTonneInOneJoulePerKilogram, (double)wattdaypertonneQuantity.Value, WattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.WattDayPerTonne, wattdaypertonneQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var watthourperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.WattHourPerKilogram); - AssertEx.EqualTolerance(WattHoursPerKilogramInOneJoulePerKilogram, (double)watthourperkilogramQuantity.Value, WattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.WattHourPerKilogram, watthourperkilogramQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(SpecificEnergyUnit unit) + { + var quantity = SpecificEnergy.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificEnergyUnit unit) { - var quantityInBaseUnit = SpecificEnergy.FromJoulesPerKilogram(1).ToBaseUnit(); - Assert.Equal(SpecificEnergy.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = SpecificEnergy.Units.FirstOrDefault(u => u != SpecificEnergy.BaseUnit && u != SpecificEnergyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == SpecificEnergyUnit.Undefined) + fromUnit = SpecificEnergy.BaseUnit; + + var quantity = SpecificEnergy.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs index d46d26509b..9c9f018be4 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -59,6 +60,36 @@ public abstract partial class SpecificEntropyTestsBase : QuantityTestsBase protected virtual double MegajoulesPerKilogramKelvinTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificEntropyUnit unit) + { + return unit switch + { + SpecificEntropyUnit.BtuPerPoundFahrenheit => (BtusPerPoundFahrenheitInOneJoulePerKilogramKelvin, BtusPerPoundFahrenheitTolerance), + SpecificEntropyUnit.CaloriePerGramKelvin => (CaloriesPerGramKelvinInOneJoulePerKilogramKelvin, CaloriesPerGramKelvinTolerance), + SpecificEntropyUnit.JoulePerKilogramDegreeCelsius => (JoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, JoulesPerKilogramDegreeCelsiusTolerance), + SpecificEntropyUnit.JoulePerKilogramKelvin => (JoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, JoulesPerKilogramKelvinTolerance), + SpecificEntropyUnit.KilocaloriePerGramKelvin => (KilocaloriesPerGramKelvinInOneJoulePerKilogramKelvin, KilocaloriesPerGramKelvinTolerance), + SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius => (KilojoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, KilojoulesPerKilogramDegreeCelsiusTolerance), + SpecificEntropyUnit.KilojoulePerKilogramKelvin => (KilojoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, KilojoulesPerKilogramKelvinTolerance), + SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius => (MegajoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, MegajoulesPerKilogramDegreeCelsiusTolerance), + SpecificEntropyUnit.MegajoulePerKilogramKelvin => (MegajoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, MegajoulesPerKilogramKelvinTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { SpecificEntropyUnit.BtuPerPoundFahrenheit }, + new object[] { SpecificEntropyUnit.CaloriePerGramKelvin }, + new object[] { SpecificEntropyUnit.JoulePerKilogramDegreeCelsius }, + new object[] { SpecificEntropyUnit.JoulePerKilogramKelvin }, + new object[] { SpecificEntropyUnit.KilocaloriePerGramKelvin }, + new object[] { SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius }, + new object[] { SpecificEntropyUnit.KilojoulePerKilogramKelvin }, + new object[] { SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius }, + new object[] { SpecificEntropyUnit.MegajoulePerKilogramKelvin }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -228,53 +259,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(SpecificEntropyUnit unit) { - var jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - - var btuperpoundfahrenheitQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.BtuPerPoundFahrenheit); - AssertEx.EqualTolerance(BtusPerPoundFahrenheitInOneJoulePerKilogramKelvin, (double)btuperpoundfahrenheitQuantity.Value, BtusPerPoundFahrenheitTolerance); - Assert.Equal(SpecificEntropyUnit.BtuPerPoundFahrenheit, btuperpoundfahrenheitQuantity.Unit); - - var caloriepergramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.CaloriePerGramKelvin); - AssertEx.EqualTolerance(CaloriesPerGramKelvinInOneJoulePerKilogramKelvin, (double)caloriepergramkelvinQuantity.Value, CaloriesPerGramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.CaloriePerGramKelvin, caloriepergramkelvinQuantity.Unit); - - var jouleperkilogramdegreecelsiusQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); - AssertEx.EqualTolerance(JoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, (double)jouleperkilogramdegreecelsiusQuantity.Value, JoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, jouleperkilogramdegreecelsiusQuantity.Unit); - - var jouleperkilogramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin); - AssertEx.EqualTolerance(JoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, (double)jouleperkilogramkelvinQuantity.Value, JoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.JoulePerKilogramKelvin, jouleperkilogramkelvinQuantity.Unit); + var inBaseUnits = SpecificEntropy.From(1.0, SpecificEntropy.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilocaloriepergramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.KilocaloriePerGramKelvin); - AssertEx.EqualTolerance(KilocaloriesPerGramKelvinInOneJoulePerKilogramKelvin, (double)kilocaloriepergramkelvinQuantity.Value, KilocaloriesPerGramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.KilocaloriePerGramKelvin, kilocaloriepergramkelvinQuantity.Unit); - - var kilojouleperkilogramdegreecelsiusQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); - AssertEx.EqualTolerance(KilojoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, (double)kilojouleperkilogramdegreecelsiusQuantity.Value, KilojoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, kilojouleperkilogramdegreecelsiusQuantity.Unit); - - var kilojouleperkilogramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramKelvin); - AssertEx.EqualTolerance(KilojoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, (double)kilojouleperkilogramkelvinQuantity.Value, KilojoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramKelvin, kilojouleperkilogramkelvinQuantity.Unit); - - var megajouleperkilogramdegreecelsiusQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); - AssertEx.EqualTolerance(MegajoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, (double)megajouleperkilogramdegreecelsiusQuantity.Value, MegajoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, megajouleperkilogramdegreecelsiusQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var megajouleperkilogramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramKelvin); - AssertEx.EqualTolerance(MegajoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, (double)megajouleperkilogramkelvinQuantity.Value, MegajoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramKelvin, megajouleperkilogramkelvinQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(SpecificEntropyUnit unit) + { + var quantity = SpecificEntropy.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificEntropyUnit unit) { - var quantityInBaseUnit = SpecificEntropy.FromJoulesPerKilogramKelvin(1).ToBaseUnit(); - Assert.Equal(SpecificEntropy.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = SpecificEntropy.Units.FirstOrDefault(u => u != SpecificEntropy.BaseUnit && u != SpecificEntropyUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == SpecificEntropyUnit.Undefined) + fromUnit = SpecificEntropy.BaseUnit; + + var quantity = SpecificEntropy.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs index aa43b0b7fa..99dca952d1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class SpecificFuelConsumptionTestsBase : QuantityTestsBa protected virtual double PoundsMassPerPoundForceHourTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificFuelConsumptionUnit unit) + { + return unit switch + { + SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond => (GramsPerKiloNewtonSecondInOneGramPerKiloNewtonSecond, GramsPerKiloNewtonSecondTolerance), + SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour => (KilogramsPerKilogramForceHourInOneGramPerKiloNewtonSecond, KilogramsPerKilogramForceHourTolerance), + SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond => (KilogramsPerKiloNewtonSecondInOneGramPerKiloNewtonSecond, KilogramsPerKiloNewtonSecondTolerance), + SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour => (PoundsMassPerPoundForceHourInOneGramPerKiloNewtonSecond, PoundsMassPerPoundForceHourTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond }, + new object[] { SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour }, + new object[] { SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond }, + new object[] { SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(SpecificFuelConsumptionUnit unit) { - var gramperkilonewtonsecond = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1); + var inBaseUnits = SpecificFuelConsumption.From(1.0, SpecificFuelConsumption.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var gramperkilonewtonsecondQuantity = gramperkilonewtonsecond.ToUnit(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond); - AssertEx.EqualTolerance(GramsPerKiloNewtonSecondInOneGramPerKiloNewtonSecond, (double)gramperkilonewtonsecondQuantity.Value, GramsPerKiloNewtonSecondTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, gramperkilonewtonsecondQuantity.Unit); - - var kilogramperkilogramforcehourQuantity = gramperkilonewtonsecond.ToUnit(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); - AssertEx.EqualTolerance(KilogramsPerKilogramForceHourInOneGramPerKiloNewtonSecond, (double)kilogramperkilogramforcehourQuantity.Value, KilogramsPerKilogramForceHourTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, kilogramperkilogramforcehourQuantity.Unit); - - var kilogramperkilonewtonsecondQuantity = gramperkilonewtonsecond.ToUnit(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond); - AssertEx.EqualTolerance(KilogramsPerKiloNewtonSecondInOneGramPerKiloNewtonSecond, (double)kilogramperkilonewtonsecondQuantity.Value, KilogramsPerKiloNewtonSecondTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, kilogramperkilonewtonsecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var poundmassperpoundforcehourQuantity = gramperkilonewtonsecond.ToUnit(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); - AssertEx.EqualTolerance(PoundsMassPerPoundForceHourInOneGramPerKiloNewtonSecond, (double)poundmassperpoundforcehourQuantity.Value, PoundsMassPerPoundForceHourTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, poundmassperpoundforcehourQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(SpecificFuelConsumptionUnit unit) + { + var quantity = SpecificFuelConsumption.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificFuelConsumptionUnit unit) { - var quantityInBaseUnit = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1).ToBaseUnit(); - Assert.Equal(SpecificFuelConsumption.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = SpecificFuelConsumption.Units.FirstOrDefault(u => u != SpecificFuelConsumption.BaseUnit && u != SpecificFuelConsumptionUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == SpecificFuelConsumptionUnit.Undefined) + fromUnit = SpecificFuelConsumption.BaseUnit; + + var quantity = SpecificFuelConsumption.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs index 198913ba08..3547c01001 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -47,6 +48,24 @@ public abstract partial class SpecificVolumeTestsBase : QuantityTestsBase protected virtual double MillicubicMetersPerKilogramTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificVolumeUnit unit) + { + return unit switch + { + SpecificVolumeUnit.CubicFootPerPound => (CubicFeetPerPoundInOneCubicMeterPerKilogram, CubicFeetPerPoundTolerance), + SpecificVolumeUnit.CubicMeterPerKilogram => (CubicMetersPerKilogramInOneCubicMeterPerKilogram, CubicMetersPerKilogramTolerance), + SpecificVolumeUnit.MillicubicMeterPerKilogram => (MillicubicMetersPerKilogramInOneCubicMeterPerKilogram, MillicubicMetersPerKilogramTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { SpecificVolumeUnit.CubicFootPerPound }, + new object[] { SpecificVolumeUnit.CubicMeterPerKilogram }, + new object[] { SpecificVolumeUnit.MillicubicMeterPerKilogram }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -180,29 +199,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(SpecificVolumeUnit unit) { - var cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); + var inBaseUnits = SpecificVolume.From(1.0, SpecificVolume.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var cubicfootperpoundQuantity = cubicmeterperkilogram.ToUnit(SpecificVolumeUnit.CubicFootPerPound); - AssertEx.EqualTolerance(CubicFeetPerPoundInOneCubicMeterPerKilogram, (double)cubicfootperpoundQuantity.Value, CubicFeetPerPoundTolerance); - Assert.Equal(SpecificVolumeUnit.CubicFootPerPound, cubicfootperpoundQuantity.Unit); - - var cubicmeterperkilogramQuantity = cubicmeterperkilogram.ToUnit(SpecificVolumeUnit.CubicMeterPerKilogram); - AssertEx.EqualTolerance(CubicMetersPerKilogramInOneCubicMeterPerKilogram, (double)cubicmeterperkilogramQuantity.Value, CubicMetersPerKilogramTolerance); - Assert.Equal(SpecificVolumeUnit.CubicMeterPerKilogram, cubicmeterperkilogramQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var millicubicmeterperkilogramQuantity = cubicmeterperkilogram.ToUnit(SpecificVolumeUnit.MillicubicMeterPerKilogram); - AssertEx.EqualTolerance(MillicubicMetersPerKilogramInOneCubicMeterPerKilogram, (double)millicubicmeterperkilogramQuantity.Value, MillicubicMetersPerKilogramTolerance); - Assert.Equal(SpecificVolumeUnit.MillicubicMeterPerKilogram, millicubicmeterperkilogramQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(SpecificVolumeUnit unit) + { + var quantity = SpecificVolume.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificVolumeUnit unit) { - var quantityInBaseUnit = SpecificVolume.FromCubicMetersPerKilogram(1).ToBaseUnit(); - Assert.Equal(SpecificVolume.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = SpecificVolume.Units.FirstOrDefault(u => u != SpecificVolume.BaseUnit && u != SpecificVolumeUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == SpecificVolumeUnit.Undefined) + fromUnit = SpecificVolume.BaseUnit; + + var quantity = SpecificVolume.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs index 6c6288dcbb..631236e82c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -75,6 +76,52 @@ public abstract partial class SpecificWeightTestsBase : QuantityTestsBase protected virtual double TonnesForcePerCubicMillimeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificWeightUnit unit) + { + return unit switch + { + SpecificWeightUnit.KilogramForcePerCubicCentimeter => (KilogramsForcePerCubicCentimeterInOneNewtonPerCubicMeter, KilogramsForcePerCubicCentimeterTolerance), + SpecificWeightUnit.KilogramForcePerCubicMeter => (KilogramsForcePerCubicMeterInOneNewtonPerCubicMeter, KilogramsForcePerCubicMeterTolerance), + SpecificWeightUnit.KilogramForcePerCubicMillimeter => (KilogramsForcePerCubicMillimeterInOneNewtonPerCubicMeter, KilogramsForcePerCubicMillimeterTolerance), + SpecificWeightUnit.KilonewtonPerCubicCentimeter => (KilonewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, KilonewtonsPerCubicCentimeterTolerance), + SpecificWeightUnit.KilonewtonPerCubicMeter => (KilonewtonsPerCubicMeterInOneNewtonPerCubicMeter, KilonewtonsPerCubicMeterTolerance), + SpecificWeightUnit.KilonewtonPerCubicMillimeter => (KilonewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, KilonewtonsPerCubicMillimeterTolerance), + SpecificWeightUnit.KilopoundForcePerCubicFoot => (KilopoundsForcePerCubicFootInOneNewtonPerCubicMeter, KilopoundsForcePerCubicFootTolerance), + SpecificWeightUnit.KilopoundForcePerCubicInch => (KilopoundsForcePerCubicInchInOneNewtonPerCubicMeter, KilopoundsForcePerCubicInchTolerance), + SpecificWeightUnit.MeganewtonPerCubicMeter => (MeganewtonsPerCubicMeterInOneNewtonPerCubicMeter, MeganewtonsPerCubicMeterTolerance), + SpecificWeightUnit.NewtonPerCubicCentimeter => (NewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, NewtonsPerCubicCentimeterTolerance), + SpecificWeightUnit.NewtonPerCubicMeter => (NewtonsPerCubicMeterInOneNewtonPerCubicMeter, NewtonsPerCubicMeterTolerance), + SpecificWeightUnit.NewtonPerCubicMillimeter => (NewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, NewtonsPerCubicMillimeterTolerance), + SpecificWeightUnit.PoundForcePerCubicFoot => (PoundsForcePerCubicFootInOneNewtonPerCubicMeter, PoundsForcePerCubicFootTolerance), + SpecificWeightUnit.PoundForcePerCubicInch => (PoundsForcePerCubicInchInOneNewtonPerCubicMeter, PoundsForcePerCubicInchTolerance), + SpecificWeightUnit.TonneForcePerCubicCentimeter => (TonnesForcePerCubicCentimeterInOneNewtonPerCubicMeter, TonnesForcePerCubicCentimeterTolerance), + SpecificWeightUnit.TonneForcePerCubicMeter => (TonnesForcePerCubicMeterInOneNewtonPerCubicMeter, TonnesForcePerCubicMeterTolerance), + SpecificWeightUnit.TonneForcePerCubicMillimeter => (TonnesForcePerCubicMillimeterInOneNewtonPerCubicMeter, TonnesForcePerCubicMillimeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { SpecificWeightUnit.KilogramForcePerCubicCentimeter }, + new object[] { SpecificWeightUnit.KilogramForcePerCubicMeter }, + new object[] { SpecificWeightUnit.KilogramForcePerCubicMillimeter }, + new object[] { SpecificWeightUnit.KilonewtonPerCubicCentimeter }, + new object[] { SpecificWeightUnit.KilonewtonPerCubicMeter }, + new object[] { SpecificWeightUnit.KilonewtonPerCubicMillimeter }, + new object[] { SpecificWeightUnit.KilopoundForcePerCubicFoot }, + new object[] { SpecificWeightUnit.KilopoundForcePerCubicInch }, + new object[] { SpecificWeightUnit.MeganewtonPerCubicMeter }, + new object[] { SpecificWeightUnit.NewtonPerCubicCentimeter }, + new object[] { SpecificWeightUnit.NewtonPerCubicMeter }, + new object[] { SpecificWeightUnit.NewtonPerCubicMillimeter }, + new object[] { SpecificWeightUnit.PoundForcePerCubicFoot }, + new object[] { SpecificWeightUnit.PoundForcePerCubicInch }, + new object[] { SpecificWeightUnit.TonneForcePerCubicCentimeter }, + new object[] { SpecificWeightUnit.TonneForcePerCubicMeter }, + new object[] { SpecificWeightUnit.TonneForcePerCubicMillimeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -292,85 +339,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(SpecificWeightUnit unit) { - var newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - - var kilogramforcepercubiccentimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilogramForcePerCubicCentimeter); - AssertEx.EqualTolerance(KilogramsForcePerCubicCentimeterInOneNewtonPerCubicMeter, (double)kilogramforcepercubiccentimeterQuantity.Value, KilogramsForcePerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicCentimeter, kilogramforcepercubiccentimeterQuantity.Unit); - - var kilogramforcepercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMeter); - AssertEx.EqualTolerance(KilogramsForcePerCubicMeterInOneNewtonPerCubicMeter, (double)kilogramforcepercubicmeterQuantity.Value, KilogramsForcePerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMeter, kilogramforcepercubicmeterQuantity.Unit); - - var kilogramforcepercubicmillimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMillimeter); - AssertEx.EqualTolerance(KilogramsForcePerCubicMillimeterInOneNewtonPerCubicMeter, (double)kilogramforcepercubicmillimeterQuantity.Value, KilogramsForcePerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMillimeter, kilogramforcepercubicmillimeterQuantity.Unit); - - var kilonewtonpercubiccentimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilonewtonPerCubicCentimeter); - AssertEx.EqualTolerance(KilonewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, (double)kilonewtonpercubiccentimeterQuantity.Value, KilonewtonsPerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicCentimeter, kilonewtonpercubiccentimeterQuantity.Unit); - - var kilonewtonpercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMeter); - AssertEx.EqualTolerance(KilonewtonsPerCubicMeterInOneNewtonPerCubicMeter, (double)kilonewtonpercubicmeterQuantity.Value, KilonewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMeter, kilonewtonpercubicmeterQuantity.Unit); - - var kilonewtonpercubicmillimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMillimeter); - AssertEx.EqualTolerance(KilonewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, (double)kilonewtonpercubicmillimeterQuantity.Value, KilonewtonsPerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMillimeter, kilonewtonpercubicmillimeterQuantity.Unit); - - var kilopoundforcepercubicfootQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicFoot); - AssertEx.EqualTolerance(KilopoundsForcePerCubicFootInOneNewtonPerCubicMeter, (double)kilopoundforcepercubicfootQuantity.Value, KilopoundsForcePerCubicFootTolerance); - Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicFoot, kilopoundforcepercubicfootQuantity.Unit); - - var kilopoundforcepercubicinchQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicInch); - AssertEx.EqualTolerance(KilopoundsForcePerCubicInchInOneNewtonPerCubicMeter, (double)kilopoundforcepercubicinchQuantity.Value, KilopoundsForcePerCubicInchTolerance); - Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicInch, kilopoundforcepercubicinchQuantity.Unit); + var inBaseUnits = SpecificWeight.From(1.0, SpecificWeight.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var meganewtonpercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.MeganewtonPerCubicMeter); - AssertEx.EqualTolerance(MeganewtonsPerCubicMeterInOneNewtonPerCubicMeter, (double)meganewtonpercubicmeterQuantity.Value, MeganewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.MeganewtonPerCubicMeter, meganewtonpercubicmeterQuantity.Unit); - - var newtonpercubiccentimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.NewtonPerCubicCentimeter); - AssertEx.EqualTolerance(NewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, (double)newtonpercubiccentimeterQuantity.Value, NewtonsPerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicCentimeter, newtonpercubiccentimeterQuantity.Unit); - - var newtonpercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter); - AssertEx.EqualTolerance(NewtonsPerCubicMeterInOneNewtonPerCubicMeter, (double)newtonpercubicmeterQuantity.Value, NewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicMeter, newtonpercubicmeterQuantity.Unit); - - var newtonpercubicmillimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.NewtonPerCubicMillimeter); - AssertEx.EqualTolerance(NewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, (double)newtonpercubicmillimeterQuantity.Value, NewtonsPerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicMillimeter, newtonpercubicmillimeterQuantity.Unit); - - var poundforcepercubicfootQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.PoundForcePerCubicFoot); - AssertEx.EqualTolerance(PoundsForcePerCubicFootInOneNewtonPerCubicMeter, (double)poundforcepercubicfootQuantity.Value, PoundsForcePerCubicFootTolerance); - Assert.Equal(SpecificWeightUnit.PoundForcePerCubicFoot, poundforcepercubicfootQuantity.Unit); - - var poundforcepercubicinchQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.PoundForcePerCubicInch); - AssertEx.EqualTolerance(PoundsForcePerCubicInchInOneNewtonPerCubicMeter, (double)poundforcepercubicinchQuantity.Value, PoundsForcePerCubicInchTolerance); - Assert.Equal(SpecificWeightUnit.PoundForcePerCubicInch, poundforcepercubicinchQuantity.Unit); - - var tonneforcepercubiccentimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.TonneForcePerCubicCentimeter); - AssertEx.EqualTolerance(TonnesForcePerCubicCentimeterInOneNewtonPerCubicMeter, (double)tonneforcepercubiccentimeterQuantity.Value, TonnesForcePerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicCentimeter, tonneforcepercubiccentimeterQuantity.Unit); - - var tonneforcepercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.TonneForcePerCubicMeter); - AssertEx.EqualTolerance(TonnesForcePerCubicMeterInOneNewtonPerCubicMeter, (double)tonneforcepercubicmeterQuantity.Value, TonnesForcePerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMeter, tonneforcepercubicmeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonneforcepercubicmillimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.TonneForcePerCubicMillimeter); - AssertEx.EqualTolerance(TonnesForcePerCubicMillimeterInOneNewtonPerCubicMeter, (double)tonneforcepercubicmillimeterQuantity.Value, TonnesForcePerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMillimeter, tonneforcepercubicmillimeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(SpecificWeightUnit unit) + { + var quantity = SpecificWeight.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificWeightUnit unit) { - var quantityInBaseUnit = SpecificWeight.FromNewtonsPerCubicMeter(1).ToBaseUnit(); - Assert.Equal(SpecificWeight.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = SpecificWeight.Units.FirstOrDefault(u => u != SpecificWeight.BaseUnit && u != SpecificWeightUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == SpecificWeightUnit.Undefined) + fromUnit = SpecificWeight.BaseUnit; + + var quantity = SpecificWeight.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs index fb9fd1ea9d..d1ba6b077a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -105,6 +106,82 @@ public abstract partial class SpeedTestsBase : QuantityTestsBase protected virtual double YardsPerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpeedUnit unit) + { + return unit switch + { + SpeedUnit.CentimeterPerHour => (CentimetersPerHourInOneMeterPerSecond, CentimetersPerHourTolerance), + SpeedUnit.CentimeterPerMinute => (CentimetersPerMinutesInOneMeterPerSecond, CentimetersPerMinutesTolerance), + SpeedUnit.CentimeterPerSecond => (CentimetersPerSecondInOneMeterPerSecond, CentimetersPerSecondTolerance), + SpeedUnit.DecimeterPerMinute => (DecimetersPerMinutesInOneMeterPerSecond, DecimetersPerMinutesTolerance), + SpeedUnit.DecimeterPerSecond => (DecimetersPerSecondInOneMeterPerSecond, DecimetersPerSecondTolerance), + SpeedUnit.FootPerHour => (FeetPerHourInOneMeterPerSecond, FeetPerHourTolerance), + SpeedUnit.FootPerMinute => (FeetPerMinuteInOneMeterPerSecond, FeetPerMinuteTolerance), + SpeedUnit.FootPerSecond => (FeetPerSecondInOneMeterPerSecond, FeetPerSecondTolerance), + SpeedUnit.InchPerHour => (InchesPerHourInOneMeterPerSecond, InchesPerHourTolerance), + SpeedUnit.InchPerMinute => (InchesPerMinuteInOneMeterPerSecond, InchesPerMinuteTolerance), + SpeedUnit.InchPerSecond => (InchesPerSecondInOneMeterPerSecond, InchesPerSecondTolerance), + SpeedUnit.KilometerPerHour => (KilometersPerHourInOneMeterPerSecond, KilometersPerHourTolerance), + SpeedUnit.KilometerPerMinute => (KilometersPerMinutesInOneMeterPerSecond, KilometersPerMinutesTolerance), + SpeedUnit.KilometerPerSecond => (KilometersPerSecondInOneMeterPerSecond, KilometersPerSecondTolerance), + SpeedUnit.Knot => (KnotsInOneMeterPerSecond, KnotsTolerance), + SpeedUnit.MeterPerHour => (MetersPerHourInOneMeterPerSecond, MetersPerHourTolerance), + SpeedUnit.MeterPerMinute => (MetersPerMinutesInOneMeterPerSecond, MetersPerMinutesTolerance), + SpeedUnit.MeterPerSecond => (MetersPerSecondInOneMeterPerSecond, MetersPerSecondTolerance), + SpeedUnit.MicrometerPerMinute => (MicrometersPerMinutesInOneMeterPerSecond, MicrometersPerMinutesTolerance), + SpeedUnit.MicrometerPerSecond => (MicrometersPerSecondInOneMeterPerSecond, MicrometersPerSecondTolerance), + SpeedUnit.MilePerHour => (MilesPerHourInOneMeterPerSecond, MilesPerHourTolerance), + SpeedUnit.MillimeterPerHour => (MillimetersPerHourInOneMeterPerSecond, MillimetersPerHourTolerance), + SpeedUnit.MillimeterPerMinute => (MillimetersPerMinutesInOneMeterPerSecond, MillimetersPerMinutesTolerance), + SpeedUnit.MillimeterPerSecond => (MillimetersPerSecondInOneMeterPerSecond, MillimetersPerSecondTolerance), + SpeedUnit.NanometerPerMinute => (NanometersPerMinutesInOneMeterPerSecond, NanometersPerMinutesTolerance), + SpeedUnit.NanometerPerSecond => (NanometersPerSecondInOneMeterPerSecond, NanometersPerSecondTolerance), + SpeedUnit.UsSurveyFootPerHour => (UsSurveyFeetPerHourInOneMeterPerSecond, UsSurveyFeetPerHourTolerance), + SpeedUnit.UsSurveyFootPerMinute => (UsSurveyFeetPerMinuteInOneMeterPerSecond, UsSurveyFeetPerMinuteTolerance), + SpeedUnit.UsSurveyFootPerSecond => (UsSurveyFeetPerSecondInOneMeterPerSecond, UsSurveyFeetPerSecondTolerance), + SpeedUnit.YardPerHour => (YardsPerHourInOneMeterPerSecond, YardsPerHourTolerance), + SpeedUnit.YardPerMinute => (YardsPerMinuteInOneMeterPerSecond, YardsPerMinuteTolerance), + SpeedUnit.YardPerSecond => (YardsPerSecondInOneMeterPerSecond, YardsPerSecondTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { SpeedUnit.CentimeterPerHour }, + new object[] { SpeedUnit.CentimeterPerMinute }, + new object[] { SpeedUnit.CentimeterPerSecond }, + new object[] { SpeedUnit.DecimeterPerMinute }, + new object[] { SpeedUnit.DecimeterPerSecond }, + new object[] { SpeedUnit.FootPerHour }, + new object[] { SpeedUnit.FootPerMinute }, + new object[] { SpeedUnit.FootPerSecond }, + new object[] { SpeedUnit.InchPerHour }, + new object[] { SpeedUnit.InchPerMinute }, + new object[] { SpeedUnit.InchPerSecond }, + new object[] { SpeedUnit.KilometerPerHour }, + new object[] { SpeedUnit.KilometerPerMinute }, + new object[] { SpeedUnit.KilometerPerSecond }, + new object[] { SpeedUnit.Knot }, + new object[] { SpeedUnit.MeterPerHour }, + new object[] { SpeedUnit.MeterPerMinute }, + new object[] { SpeedUnit.MeterPerSecond }, + new object[] { SpeedUnit.MicrometerPerMinute }, + new object[] { SpeedUnit.MicrometerPerSecond }, + new object[] { SpeedUnit.MilePerHour }, + new object[] { SpeedUnit.MillimeterPerHour }, + new object[] { SpeedUnit.MillimeterPerMinute }, + new object[] { SpeedUnit.MillimeterPerSecond }, + new object[] { SpeedUnit.NanometerPerMinute }, + new object[] { SpeedUnit.NanometerPerSecond }, + new object[] { SpeedUnit.UsSurveyFootPerHour }, + new object[] { SpeedUnit.UsSurveyFootPerMinute }, + new object[] { SpeedUnit.UsSurveyFootPerSecond }, + new object[] { SpeedUnit.YardPerHour }, + new object[] { SpeedUnit.YardPerMinute }, + new object[] { SpeedUnit.YardPerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -412,145 +489,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(SpeedUnit unit) { - var meterpersecond = Speed.FromMetersPerSecond(1); - - var centimeterperhourQuantity = meterpersecond.ToUnit(SpeedUnit.CentimeterPerHour); - AssertEx.EqualTolerance(CentimetersPerHourInOneMeterPerSecond, (double)centimeterperhourQuantity.Value, CentimetersPerHourTolerance); - Assert.Equal(SpeedUnit.CentimeterPerHour, centimeterperhourQuantity.Unit); - - var centimeterperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.CentimeterPerMinute); - AssertEx.EqualTolerance(CentimetersPerMinutesInOneMeterPerSecond, (double)centimeterperminuteQuantity.Value, CentimetersPerMinutesTolerance); - Assert.Equal(SpeedUnit.CentimeterPerMinute, centimeterperminuteQuantity.Unit); - - var centimeterpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.CentimeterPerSecond); - AssertEx.EqualTolerance(CentimetersPerSecondInOneMeterPerSecond, (double)centimeterpersecondQuantity.Value, CentimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.CentimeterPerSecond, centimeterpersecondQuantity.Unit); - - var decimeterperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.DecimeterPerMinute); - AssertEx.EqualTolerance(DecimetersPerMinutesInOneMeterPerSecond, (double)decimeterperminuteQuantity.Value, DecimetersPerMinutesTolerance); - Assert.Equal(SpeedUnit.DecimeterPerMinute, decimeterperminuteQuantity.Unit); - - var decimeterpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.DecimeterPerSecond); - AssertEx.EqualTolerance(DecimetersPerSecondInOneMeterPerSecond, (double)decimeterpersecondQuantity.Value, DecimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.DecimeterPerSecond, decimeterpersecondQuantity.Unit); - - var footperhourQuantity = meterpersecond.ToUnit(SpeedUnit.FootPerHour); - AssertEx.EqualTolerance(FeetPerHourInOneMeterPerSecond, (double)footperhourQuantity.Value, FeetPerHourTolerance); - Assert.Equal(SpeedUnit.FootPerHour, footperhourQuantity.Unit); - - var footperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.FootPerMinute); - AssertEx.EqualTolerance(FeetPerMinuteInOneMeterPerSecond, (double)footperminuteQuantity.Value, FeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.FootPerMinute, footperminuteQuantity.Unit); - - var footpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.FootPerSecond); - AssertEx.EqualTolerance(FeetPerSecondInOneMeterPerSecond, (double)footpersecondQuantity.Value, FeetPerSecondTolerance); - Assert.Equal(SpeedUnit.FootPerSecond, footpersecondQuantity.Unit); - - var inchperhourQuantity = meterpersecond.ToUnit(SpeedUnit.InchPerHour); - AssertEx.EqualTolerance(InchesPerHourInOneMeterPerSecond, (double)inchperhourQuantity.Value, InchesPerHourTolerance); - Assert.Equal(SpeedUnit.InchPerHour, inchperhourQuantity.Unit); - - var inchperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.InchPerMinute); - AssertEx.EqualTolerance(InchesPerMinuteInOneMeterPerSecond, (double)inchperminuteQuantity.Value, InchesPerMinuteTolerance); - Assert.Equal(SpeedUnit.InchPerMinute, inchperminuteQuantity.Unit); - - var inchpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.InchPerSecond); - AssertEx.EqualTolerance(InchesPerSecondInOneMeterPerSecond, (double)inchpersecondQuantity.Value, InchesPerSecondTolerance); - Assert.Equal(SpeedUnit.InchPerSecond, inchpersecondQuantity.Unit); - - var kilometerperhourQuantity = meterpersecond.ToUnit(SpeedUnit.KilometerPerHour); - AssertEx.EqualTolerance(KilometersPerHourInOneMeterPerSecond, (double)kilometerperhourQuantity.Value, KilometersPerHourTolerance); - Assert.Equal(SpeedUnit.KilometerPerHour, kilometerperhourQuantity.Unit); - - var kilometerperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.KilometerPerMinute); - AssertEx.EqualTolerance(KilometersPerMinutesInOneMeterPerSecond, (double)kilometerperminuteQuantity.Value, KilometersPerMinutesTolerance); - Assert.Equal(SpeedUnit.KilometerPerMinute, kilometerperminuteQuantity.Unit); - - var kilometerpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.KilometerPerSecond); - AssertEx.EqualTolerance(KilometersPerSecondInOneMeterPerSecond, (double)kilometerpersecondQuantity.Value, KilometersPerSecondTolerance); - Assert.Equal(SpeedUnit.KilometerPerSecond, kilometerpersecondQuantity.Unit); - - var knotQuantity = meterpersecond.ToUnit(SpeedUnit.Knot); - AssertEx.EqualTolerance(KnotsInOneMeterPerSecond, (double)knotQuantity.Value, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, knotQuantity.Unit); - - var meterperhourQuantity = meterpersecond.ToUnit(SpeedUnit.MeterPerHour); - AssertEx.EqualTolerance(MetersPerHourInOneMeterPerSecond, (double)meterperhourQuantity.Value, MetersPerHourTolerance); - Assert.Equal(SpeedUnit.MeterPerHour, meterperhourQuantity.Unit); + var inBaseUnits = Speed.From(1.0, Speed.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var meterperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.MeterPerMinute); - AssertEx.EqualTolerance(MetersPerMinutesInOneMeterPerSecond, (double)meterperminuteQuantity.Value, MetersPerMinutesTolerance); - Assert.Equal(SpeedUnit.MeterPerMinute, meterperminuteQuantity.Unit); - - var meterpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.MeterPerSecond); - AssertEx.EqualTolerance(MetersPerSecondInOneMeterPerSecond, (double)meterpersecondQuantity.Value, MetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MeterPerSecond, meterpersecondQuantity.Unit); - - var micrometerperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.MicrometerPerMinute); - AssertEx.EqualTolerance(MicrometersPerMinutesInOneMeterPerSecond, (double)micrometerperminuteQuantity.Value, MicrometersPerMinutesTolerance); - Assert.Equal(SpeedUnit.MicrometerPerMinute, micrometerperminuteQuantity.Unit); - - var micrometerpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.MicrometerPerSecond); - AssertEx.EqualTolerance(MicrometersPerSecondInOneMeterPerSecond, (double)micrometerpersecondQuantity.Value, MicrometersPerSecondTolerance); - Assert.Equal(SpeedUnit.MicrometerPerSecond, micrometerpersecondQuantity.Unit); - - var mileperhourQuantity = meterpersecond.ToUnit(SpeedUnit.MilePerHour); - AssertEx.EqualTolerance(MilesPerHourInOneMeterPerSecond, (double)mileperhourQuantity.Value, MilesPerHourTolerance); - Assert.Equal(SpeedUnit.MilePerHour, mileperhourQuantity.Unit); - - var millimeterperhourQuantity = meterpersecond.ToUnit(SpeedUnit.MillimeterPerHour); - AssertEx.EqualTolerance(MillimetersPerHourInOneMeterPerSecond, (double)millimeterperhourQuantity.Value, MillimetersPerHourTolerance); - Assert.Equal(SpeedUnit.MillimeterPerHour, millimeterperhourQuantity.Unit); - - var millimeterperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.MillimeterPerMinute); - AssertEx.EqualTolerance(MillimetersPerMinutesInOneMeterPerSecond, (double)millimeterperminuteQuantity.Value, MillimetersPerMinutesTolerance); - Assert.Equal(SpeedUnit.MillimeterPerMinute, millimeterperminuteQuantity.Unit); - - var millimeterpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.MillimeterPerSecond); - AssertEx.EqualTolerance(MillimetersPerSecondInOneMeterPerSecond, (double)millimeterpersecondQuantity.Value, MillimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MillimeterPerSecond, millimeterpersecondQuantity.Unit); - - var nanometerperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.NanometerPerMinute); - AssertEx.EqualTolerance(NanometersPerMinutesInOneMeterPerSecond, (double)nanometerperminuteQuantity.Value, NanometersPerMinutesTolerance); - Assert.Equal(SpeedUnit.NanometerPerMinute, nanometerperminuteQuantity.Unit); - - var nanometerpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.NanometerPerSecond); - AssertEx.EqualTolerance(NanometersPerSecondInOneMeterPerSecond, (double)nanometerpersecondQuantity.Value, NanometersPerSecondTolerance); - Assert.Equal(SpeedUnit.NanometerPerSecond, nanometerpersecondQuantity.Unit); - - var ussurveyfootperhourQuantity = meterpersecond.ToUnit(SpeedUnit.UsSurveyFootPerHour); - AssertEx.EqualTolerance(UsSurveyFeetPerHourInOneMeterPerSecond, (double)ussurveyfootperhourQuantity.Value, UsSurveyFeetPerHourTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerHour, ussurveyfootperhourQuantity.Unit); - - var ussurveyfootperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.UsSurveyFootPerMinute); - AssertEx.EqualTolerance(UsSurveyFeetPerMinuteInOneMeterPerSecond, (double)ussurveyfootperminuteQuantity.Value, UsSurveyFeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerMinute, ussurveyfootperminuteQuantity.Unit); - - var ussurveyfootpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.UsSurveyFootPerSecond); - AssertEx.EqualTolerance(UsSurveyFeetPerSecondInOneMeterPerSecond, (double)ussurveyfootpersecondQuantity.Value, UsSurveyFeetPerSecondTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerSecond, ussurveyfootpersecondQuantity.Unit); - - var yardperhourQuantity = meterpersecond.ToUnit(SpeedUnit.YardPerHour); - AssertEx.EqualTolerance(YardsPerHourInOneMeterPerSecond, (double)yardperhourQuantity.Value, YardsPerHourTolerance); - Assert.Equal(SpeedUnit.YardPerHour, yardperhourQuantity.Unit); - - var yardperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.YardPerMinute); - AssertEx.EqualTolerance(YardsPerMinuteInOneMeterPerSecond, (double)yardperminuteQuantity.Value, YardsPerMinuteTolerance); - Assert.Equal(SpeedUnit.YardPerMinute, yardperminuteQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var yardpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.YardPerSecond); - AssertEx.EqualTolerance(YardsPerSecondInOneMeterPerSecond, (double)yardpersecondQuantity.Value, YardsPerSecondTolerance); - Assert.Equal(SpeedUnit.YardPerSecond, yardpersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(SpeedUnit unit) + { + var quantity = Speed.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpeedUnit unit) { - var quantityInBaseUnit = Speed.FromMetersPerSecond(1).ToBaseUnit(); - Assert.Equal(Speed.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Speed.Units.FirstOrDefault(u => u != Speed.BaseUnit && u != SpeedUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == SpeedUnit.Undefined) + fromUnit = Speed.BaseUnit; + + var quantity = Speed.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs index db667fcf5c..eabb7fd0f9 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -59,6 +60,36 @@ public abstract partial class StandardVolumeFlowTestsBase : QuantityTestsBase protected virtual double StandardLitersPerMinuteTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(StandardVolumeFlowUnit unit) + { + return unit switch + { + StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute => (StandardCubicCentimetersPerMinuteInOneStandardCubicMeterPerSecond, StandardCubicCentimetersPerMinuteTolerance), + StandardVolumeFlowUnit.StandardCubicFootPerHour => (StandardCubicFeetPerHourInOneStandardCubicMeterPerSecond, StandardCubicFeetPerHourTolerance), + StandardVolumeFlowUnit.StandardCubicFootPerMinute => (StandardCubicFeetPerMinuteInOneStandardCubicMeterPerSecond, StandardCubicFeetPerMinuteTolerance), + StandardVolumeFlowUnit.StandardCubicFootPerSecond => (StandardCubicFeetPerSecondInOneStandardCubicMeterPerSecond, StandardCubicFeetPerSecondTolerance), + StandardVolumeFlowUnit.StandardCubicMeterPerDay => (StandardCubicMetersPerDayInOneStandardCubicMeterPerSecond, StandardCubicMetersPerDayTolerance), + StandardVolumeFlowUnit.StandardCubicMeterPerHour => (StandardCubicMetersPerHourInOneStandardCubicMeterPerSecond, StandardCubicMetersPerHourTolerance), + StandardVolumeFlowUnit.StandardCubicMeterPerMinute => (StandardCubicMetersPerMinuteInOneStandardCubicMeterPerSecond, StandardCubicMetersPerMinuteTolerance), + StandardVolumeFlowUnit.StandardCubicMeterPerSecond => (StandardCubicMetersPerSecondInOneStandardCubicMeterPerSecond, StandardCubicMetersPerSecondTolerance), + StandardVolumeFlowUnit.StandardLiterPerMinute => (StandardLitersPerMinuteInOneStandardCubicMeterPerSecond, StandardLitersPerMinuteTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute }, + new object[] { StandardVolumeFlowUnit.StandardCubicFootPerHour }, + new object[] { StandardVolumeFlowUnit.StandardCubicFootPerMinute }, + new object[] { StandardVolumeFlowUnit.StandardCubicFootPerSecond }, + new object[] { StandardVolumeFlowUnit.StandardCubicMeterPerDay }, + new object[] { StandardVolumeFlowUnit.StandardCubicMeterPerHour }, + new object[] { StandardVolumeFlowUnit.StandardCubicMeterPerMinute }, + new object[] { StandardVolumeFlowUnit.StandardCubicMeterPerSecond }, + new object[] { StandardVolumeFlowUnit.StandardLiterPerMinute }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -228,53 +259,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(StandardVolumeFlowUnit unit) { - var standardcubicmeterpersecond = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - - var standardcubiccentimeterperminuteQuantity = standardcubicmeterpersecond.ToUnit(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); - AssertEx.EqualTolerance(StandardCubicCentimetersPerMinuteInOneStandardCubicMeterPerSecond, (double)standardcubiccentimeterperminuteQuantity.Value, StandardCubicCentimetersPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, standardcubiccentimeterperminuteQuantity.Unit); - - var standardcubicfootperhourQuantity = standardcubicmeterpersecond.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerHour); - AssertEx.EqualTolerance(StandardCubicFeetPerHourInOneStandardCubicMeterPerSecond, (double)standardcubicfootperhourQuantity.Value, StandardCubicFeetPerHourTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerHour, standardcubicfootperhourQuantity.Unit); - - var standardcubicfootperminuteQuantity = standardcubicmeterpersecond.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerMinute); - AssertEx.EqualTolerance(StandardCubicFeetPerMinuteInOneStandardCubicMeterPerSecond, (double)standardcubicfootperminuteQuantity.Value, StandardCubicFeetPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerMinute, standardcubicfootperminuteQuantity.Unit); - - var standardcubicfootpersecondQuantity = standardcubicmeterpersecond.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerSecond); - AssertEx.EqualTolerance(StandardCubicFeetPerSecondInOneStandardCubicMeterPerSecond, (double)standardcubicfootpersecondQuantity.Value, StandardCubicFeetPerSecondTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerSecond, standardcubicfootpersecondQuantity.Unit); + var inBaseUnits = StandardVolumeFlow.From(1.0, StandardVolumeFlow.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var standardcubicmeterperdayQuantity = standardcubicmeterpersecond.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerDay); - AssertEx.EqualTolerance(StandardCubicMetersPerDayInOneStandardCubicMeterPerSecond, (double)standardcubicmeterperdayQuantity.Value, StandardCubicMetersPerDayTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerDay, standardcubicmeterperdayQuantity.Unit); - - var standardcubicmeterperhourQuantity = standardcubicmeterpersecond.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerHour); - AssertEx.EqualTolerance(StandardCubicMetersPerHourInOneStandardCubicMeterPerSecond, (double)standardcubicmeterperhourQuantity.Value, StandardCubicMetersPerHourTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerHour, standardcubicmeterperhourQuantity.Unit); - - var standardcubicmeterperminuteQuantity = standardcubicmeterpersecond.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerMinute); - AssertEx.EqualTolerance(StandardCubicMetersPerMinuteInOneStandardCubicMeterPerSecond, (double)standardcubicmeterperminuteQuantity.Value, StandardCubicMetersPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, standardcubicmeterperminuteQuantity.Unit); - - var standardcubicmeterpersecondQuantity = standardcubicmeterpersecond.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond); - AssertEx.EqualTolerance(StandardCubicMetersPerSecondInOneStandardCubicMeterPerSecond, (double)standardcubicmeterpersecondQuantity.Value, StandardCubicMetersPerSecondTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, standardcubicmeterpersecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var standardliterperminuteQuantity = standardcubicmeterpersecond.ToUnit(StandardVolumeFlowUnit.StandardLiterPerMinute); - AssertEx.EqualTolerance(StandardLitersPerMinuteInOneStandardCubicMeterPerSecond, (double)standardliterperminuteQuantity.Value, StandardLitersPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardLiterPerMinute, standardliterperminuteQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(StandardVolumeFlowUnit unit) + { + var quantity = StandardVolumeFlow.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(StandardVolumeFlowUnit unit) { - var quantityInBaseUnit = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1).ToBaseUnit(); - Assert.Equal(StandardVolumeFlow.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = StandardVolumeFlow.Units.FirstOrDefault(u => u != StandardVolumeFlow.BaseUnit && u != StandardVolumeFlowUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == StandardVolumeFlowUnit.Undefined) + fromUnit = StandardVolumeFlow.BaseUnit; + + var quantity = StandardVolumeFlow.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs index 3986719461..8af86a0b20 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -61,6 +62,38 @@ public abstract partial class TemperatureChangeRateTestsBase : QuantityTestsBase protected virtual double NanodegreesCelsiusPerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TemperatureChangeRateUnit unit) + { + return unit switch + { + TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond => (CentidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, CentidegreesCelsiusPerSecondTolerance), + TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond => (DecadegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, DecadegreesCelsiusPerSecondTolerance), + TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond => (DecidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, DecidegreesCelsiusPerSecondTolerance), + TemperatureChangeRateUnit.DegreeCelsiusPerMinute => (DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond, DegreesCelsiusPerMinuteTolerance), + TemperatureChangeRateUnit.DegreeCelsiusPerSecond => (DegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, DegreesCelsiusPerSecondTolerance), + TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond => (HectodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, HectodegreesCelsiusPerSecondTolerance), + TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond => (KilodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, KilodegreesCelsiusPerSecondTolerance), + TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond => (MicrodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, MicrodegreesCelsiusPerSecondTolerance), + TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond => (MillidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, MillidegreesCelsiusPerSecondTolerance), + TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond => (NanodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, NanodegreesCelsiusPerSecondTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond }, + new object[] { TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond }, + new object[] { TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond }, + new object[] { TemperatureChangeRateUnit.DegreeCelsiusPerMinute }, + new object[] { TemperatureChangeRateUnit.DegreeCelsiusPerSecond }, + new object[] { TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond }, + new object[] { TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond }, + new object[] { TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond }, + new object[] { TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond }, + new object[] { TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -236,57 +269,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(TemperatureChangeRateUnit unit) { - var degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - - var centidegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); - AssertEx.EqualTolerance(CentidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)centidegreecelsiuspersecondQuantity.Value, CentidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, centidegreecelsiuspersecondQuantity.Unit); - - var decadegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); - AssertEx.EqualTolerance(DecadegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)decadegreecelsiuspersecondQuantity.Value, DecadegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, decadegreecelsiuspersecondQuantity.Unit); - - var decidegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); - AssertEx.EqualTolerance(DecidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)decidegreecelsiuspersecondQuantity.Value, DecidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, decidegreecelsiuspersecondQuantity.Unit); - - var degreecelsiusperminuteQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); - AssertEx.EqualTolerance(DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond, (double)degreecelsiusperminuteQuantity.Value, DegreesCelsiusPerMinuteTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, degreecelsiusperminuteQuantity.Unit); - - var degreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - AssertEx.EqualTolerance(DegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)degreecelsiuspersecondQuantity.Value, DegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, degreecelsiuspersecondQuantity.Unit); + var inBaseUnits = TemperatureChangeRate.From(1.0, TemperatureChangeRate.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var hectodegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(HectodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)hectodegreecelsiuspersecondQuantity.Value, HectodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, hectodegreecelsiuspersecondQuantity.Unit); - - var kilodegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(KilodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)kilodegreecelsiuspersecondQuantity.Value, KilodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, kilodegreecelsiuspersecondQuantity.Unit); - - var microdegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(MicrodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)microdegreecelsiuspersecondQuantity.Value, MicrodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, microdegreecelsiuspersecondQuantity.Unit); - - var millidegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); - AssertEx.EqualTolerance(MillidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)millidegreecelsiuspersecondQuantity.Value, MillidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, millidegreecelsiuspersecondQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var nanodegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(NanodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)nanodegreecelsiuspersecondQuantity.Value, NanodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, nanodegreecelsiuspersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(TemperatureChangeRateUnit unit) + { + var quantity = TemperatureChangeRate.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureChangeRateUnit unit) { - var quantityInBaseUnit = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1).ToBaseUnit(); - Assert.Equal(TemperatureChangeRate.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = TemperatureChangeRate.Units.FirstOrDefault(u => u != TemperatureChangeRate.BaseUnit && u != TemperatureChangeRateUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == TemperatureChangeRateUnit.Undefined) + fromUnit = TemperatureChangeRate.BaseUnit; + + var quantity = TemperatureChangeRate.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs index bd811703eb..8c51fb93b6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -59,6 +60,36 @@ public abstract partial class TemperatureDeltaTestsBase : QuantityTestsBase protected virtual double MillidegreesCelsiusTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TemperatureDeltaUnit unit) + { + return unit switch + { + TemperatureDeltaUnit.DegreeCelsius => (DegreesCelsiusInOneKelvin, DegreesCelsiusTolerance), + TemperatureDeltaUnit.DegreeDelisle => (DegreesDelisleInOneKelvin, DegreesDelisleTolerance), + TemperatureDeltaUnit.DegreeFahrenheit => (DegreesFahrenheitInOneKelvin, DegreesFahrenheitTolerance), + TemperatureDeltaUnit.DegreeNewton => (DegreesNewtonInOneKelvin, DegreesNewtonTolerance), + TemperatureDeltaUnit.DegreeRankine => (DegreesRankineInOneKelvin, DegreesRankineTolerance), + TemperatureDeltaUnit.DegreeReaumur => (DegreesReaumurInOneKelvin, DegreesReaumurTolerance), + TemperatureDeltaUnit.DegreeRoemer => (DegreesRoemerInOneKelvin, DegreesRoemerTolerance), + TemperatureDeltaUnit.Kelvin => (KelvinsInOneKelvin, KelvinsTolerance), + TemperatureDeltaUnit.MillidegreeCelsius => (MillidegreesCelsiusInOneKelvin, MillidegreesCelsiusTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { TemperatureDeltaUnit.DegreeCelsius }, + new object[] { TemperatureDeltaUnit.DegreeDelisle }, + new object[] { TemperatureDeltaUnit.DegreeFahrenheit }, + new object[] { TemperatureDeltaUnit.DegreeNewton }, + new object[] { TemperatureDeltaUnit.DegreeRankine }, + new object[] { TemperatureDeltaUnit.DegreeReaumur }, + new object[] { TemperatureDeltaUnit.DegreeRoemer }, + new object[] { TemperatureDeltaUnit.Kelvin }, + new object[] { TemperatureDeltaUnit.MillidegreeCelsius }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -228,53 +259,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(TemperatureDeltaUnit unit) { - var kelvin = TemperatureDelta.FromKelvins(1); - - var degreecelsiusQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeCelsius); - AssertEx.EqualTolerance(DegreesCelsiusInOneKelvin, (double)degreecelsiusQuantity.Value, DegreesCelsiusTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeCelsius, degreecelsiusQuantity.Unit); - - var degreedelisleQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeDelisle); - AssertEx.EqualTolerance(DegreesDelisleInOneKelvin, (double)degreedelisleQuantity.Value, DegreesDelisleTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeDelisle, degreedelisleQuantity.Unit); - - var degreefahrenheitQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeFahrenheit); - AssertEx.EqualTolerance(DegreesFahrenheitInOneKelvin, (double)degreefahrenheitQuantity.Value, DegreesFahrenheitTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeFahrenheit, degreefahrenheitQuantity.Unit); - - var degreenewtonQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeNewton); - AssertEx.EqualTolerance(DegreesNewtonInOneKelvin, (double)degreenewtonQuantity.Value, DegreesNewtonTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeNewton, degreenewtonQuantity.Unit); + var inBaseUnits = TemperatureDelta.From(1.0, TemperatureDelta.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var degreerankineQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeRankine); - AssertEx.EqualTolerance(DegreesRankineInOneKelvin, (double)degreerankineQuantity.Value, DegreesRankineTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRankine, degreerankineQuantity.Unit); - - var degreereaumurQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeReaumur); - AssertEx.EqualTolerance(DegreesReaumurInOneKelvin, (double)degreereaumurQuantity.Value, DegreesReaumurTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeReaumur, degreereaumurQuantity.Unit); - - var degreeroemerQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeRoemer); - AssertEx.EqualTolerance(DegreesRoemerInOneKelvin, (double)degreeroemerQuantity.Value, DegreesRoemerTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRoemer, degreeroemerQuantity.Unit); - - var kelvinQuantity = kelvin.ToUnit(TemperatureDeltaUnit.Kelvin); - AssertEx.EqualTolerance(KelvinsInOneKelvin, (double)kelvinQuantity.Value, KelvinsTolerance); - Assert.Equal(TemperatureDeltaUnit.Kelvin, kelvinQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var millidegreecelsiusQuantity = kelvin.ToUnit(TemperatureDeltaUnit.MillidegreeCelsius); - AssertEx.EqualTolerance(MillidegreesCelsiusInOneKelvin, (double)millidegreecelsiusQuantity.Value, MillidegreesCelsiusTolerance); - Assert.Equal(TemperatureDeltaUnit.MillidegreeCelsius, millidegreecelsiusQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(TemperatureDeltaUnit unit) + { + var quantity = TemperatureDelta.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureDeltaUnit unit) { - var quantityInBaseUnit = TemperatureDelta.FromKelvins(1).ToBaseUnit(); - Assert.Equal(TemperatureDelta.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = TemperatureDelta.Units.FirstOrDefault(u => u != TemperatureDelta.BaseUnit && u != TemperatureDeltaUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == TemperatureDeltaUnit.Undefined) + fromUnit = TemperatureDelta.BaseUnit; + + var quantity = TemperatureDelta.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs index 76f37cdd67..75372fd4e2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -49,6 +50,26 @@ public abstract partial class TemperatureGradientTestsBase : QuantityTestsBase protected virtual double KelvinsPerMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TemperatureGradientUnit unit) + { + return unit switch + { + TemperatureGradientUnit.DegreeCelsiusPerKilometer => (DegreesCelciusPerKilometerInOneKelvinPerMeter, DegreesCelciusPerKilometerTolerance), + TemperatureGradientUnit.DegreeCelsiusPerMeter => (DegreesCelciusPerMeterInOneKelvinPerMeter, DegreesCelciusPerMeterTolerance), + TemperatureGradientUnit.DegreeFahrenheitPerFoot => (DegreesFahrenheitPerFootInOneKelvinPerMeter, DegreesFahrenheitPerFootTolerance), + TemperatureGradientUnit.KelvinPerMeter => (KelvinsPerMeterInOneKelvinPerMeter, KelvinsPerMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { TemperatureGradientUnit.DegreeCelsiusPerKilometer }, + new object[] { TemperatureGradientUnit.DegreeCelsiusPerMeter }, + new object[] { TemperatureGradientUnit.DegreeFahrenheitPerFoot }, + new object[] { TemperatureGradientUnit.KelvinPerMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -188,33 +209,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(TemperatureGradientUnit unit) { - var kelvinpermeter = TemperatureGradient.FromKelvinsPerMeter(1); + var inBaseUnits = TemperatureGradient.From(1.0, TemperatureGradient.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var degreecelsiusperkilometerQuantity = kelvinpermeter.ToUnit(TemperatureGradientUnit.DegreeCelsiusPerKilometer); - AssertEx.EqualTolerance(DegreesCelciusPerKilometerInOneKelvinPerMeter, (double)degreecelsiusperkilometerQuantity.Value, DegreesCelciusPerKilometerTolerance); - Assert.Equal(TemperatureGradientUnit.DegreeCelsiusPerKilometer, degreecelsiusperkilometerQuantity.Unit); - - var degreecelsiuspermeterQuantity = kelvinpermeter.ToUnit(TemperatureGradientUnit.DegreeCelsiusPerMeter); - AssertEx.EqualTolerance(DegreesCelciusPerMeterInOneKelvinPerMeter, (double)degreecelsiuspermeterQuantity.Value, DegreesCelciusPerMeterTolerance); - Assert.Equal(TemperatureGradientUnit.DegreeCelsiusPerMeter, degreecelsiuspermeterQuantity.Unit); - - var degreefahrenheitperfootQuantity = kelvinpermeter.ToUnit(TemperatureGradientUnit.DegreeFahrenheitPerFoot); - AssertEx.EqualTolerance(DegreesFahrenheitPerFootInOneKelvinPerMeter, (double)degreefahrenheitperfootQuantity.Value, DegreesFahrenheitPerFootTolerance); - Assert.Equal(TemperatureGradientUnit.DegreeFahrenheitPerFoot, degreefahrenheitperfootQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var kelvinpermeterQuantity = kelvinpermeter.ToUnit(TemperatureGradientUnit.KelvinPerMeter); - AssertEx.EqualTolerance(KelvinsPerMeterInOneKelvinPerMeter, (double)kelvinpermeterQuantity.Value, KelvinsPerMeterTolerance); - Assert.Equal(TemperatureGradientUnit.KelvinPerMeter, kelvinpermeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(TemperatureGradientUnit unit) + { + var quantity = TemperatureGradient.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureGradientUnit unit) { - var quantityInBaseUnit = TemperatureGradient.FromKelvinsPerMeter(1).ToBaseUnit(); - Assert.Equal(TemperatureGradient.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = TemperatureGradient.Units.FirstOrDefault(u => u != TemperatureGradient.BaseUnit && u != TemperatureGradientUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == TemperatureGradientUnit.Undefined) + fromUnit = TemperatureGradient.BaseUnit; + + var quantity = TemperatureGradient.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs index d9cc05adff..9e0c160da4 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -61,6 +62,38 @@ public abstract partial class TemperatureTestsBase : QuantityTestsBase protected virtual double SolarTemperaturesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TemperatureUnit unit) + { + return unit switch + { + TemperatureUnit.DegreeCelsius => (DegreesCelsiusInOneKelvin, DegreesCelsiusTolerance), + TemperatureUnit.DegreeDelisle => (DegreesDelisleInOneKelvin, DegreesDelisleTolerance), + TemperatureUnit.DegreeFahrenheit => (DegreesFahrenheitInOneKelvin, DegreesFahrenheitTolerance), + TemperatureUnit.DegreeNewton => (DegreesNewtonInOneKelvin, DegreesNewtonTolerance), + TemperatureUnit.DegreeRankine => (DegreesRankineInOneKelvin, DegreesRankineTolerance), + TemperatureUnit.DegreeReaumur => (DegreesReaumurInOneKelvin, DegreesReaumurTolerance), + TemperatureUnit.DegreeRoemer => (DegreesRoemerInOneKelvin, DegreesRoemerTolerance), + TemperatureUnit.Kelvin => (KelvinsInOneKelvin, KelvinsTolerance), + TemperatureUnit.MillidegreeCelsius => (MillidegreesCelsiusInOneKelvin, MillidegreesCelsiusTolerance), + TemperatureUnit.SolarTemperature => (SolarTemperaturesInOneKelvin, SolarTemperaturesTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { TemperatureUnit.DegreeCelsius }, + new object[] { TemperatureUnit.DegreeDelisle }, + new object[] { TemperatureUnit.DegreeFahrenheit }, + new object[] { TemperatureUnit.DegreeNewton }, + new object[] { TemperatureUnit.DegreeRankine }, + new object[] { TemperatureUnit.DegreeReaumur }, + new object[] { TemperatureUnit.DegreeRoemer }, + new object[] { TemperatureUnit.Kelvin }, + new object[] { TemperatureUnit.MillidegreeCelsius }, + new object[] { TemperatureUnit.SolarTemperature }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -236,57 +269,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(TemperatureUnit unit) { - var kelvin = Temperature.FromKelvins(1); - - var degreecelsiusQuantity = kelvin.ToUnit(TemperatureUnit.DegreeCelsius); - AssertEx.EqualTolerance(DegreesCelsiusInOneKelvin, (double)degreecelsiusQuantity.Value, DegreesCelsiusTolerance); - Assert.Equal(TemperatureUnit.DegreeCelsius, degreecelsiusQuantity.Unit); - - var degreedelisleQuantity = kelvin.ToUnit(TemperatureUnit.DegreeDelisle); - AssertEx.EqualTolerance(DegreesDelisleInOneKelvin, (double)degreedelisleQuantity.Value, DegreesDelisleTolerance); - Assert.Equal(TemperatureUnit.DegreeDelisle, degreedelisleQuantity.Unit); - - var degreefahrenheitQuantity = kelvin.ToUnit(TemperatureUnit.DegreeFahrenheit); - AssertEx.EqualTolerance(DegreesFahrenheitInOneKelvin, (double)degreefahrenheitQuantity.Value, DegreesFahrenheitTolerance); - Assert.Equal(TemperatureUnit.DegreeFahrenheit, degreefahrenheitQuantity.Unit); - - var degreenewtonQuantity = kelvin.ToUnit(TemperatureUnit.DegreeNewton); - AssertEx.EqualTolerance(DegreesNewtonInOneKelvin, (double)degreenewtonQuantity.Value, DegreesNewtonTolerance); - Assert.Equal(TemperatureUnit.DegreeNewton, degreenewtonQuantity.Unit); + var inBaseUnits = Temperature.From(1.0, Temperature.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var degreerankineQuantity = kelvin.ToUnit(TemperatureUnit.DegreeRankine); - AssertEx.EqualTolerance(DegreesRankineInOneKelvin, (double)degreerankineQuantity.Value, DegreesRankineTolerance); - Assert.Equal(TemperatureUnit.DegreeRankine, degreerankineQuantity.Unit); - - var degreereaumurQuantity = kelvin.ToUnit(TemperatureUnit.DegreeReaumur); - AssertEx.EqualTolerance(DegreesReaumurInOneKelvin, (double)degreereaumurQuantity.Value, DegreesReaumurTolerance); - Assert.Equal(TemperatureUnit.DegreeReaumur, degreereaumurQuantity.Unit); - - var degreeroemerQuantity = kelvin.ToUnit(TemperatureUnit.DegreeRoemer); - AssertEx.EqualTolerance(DegreesRoemerInOneKelvin, (double)degreeroemerQuantity.Value, DegreesRoemerTolerance); - Assert.Equal(TemperatureUnit.DegreeRoemer, degreeroemerQuantity.Unit); - - var kelvinQuantity = kelvin.ToUnit(TemperatureUnit.Kelvin); - AssertEx.EqualTolerance(KelvinsInOneKelvin, (double)kelvinQuantity.Value, KelvinsTolerance); - Assert.Equal(TemperatureUnit.Kelvin, kelvinQuantity.Unit); - - var millidegreecelsiusQuantity = kelvin.ToUnit(TemperatureUnit.MillidegreeCelsius); - AssertEx.EqualTolerance(MillidegreesCelsiusInOneKelvin, (double)millidegreecelsiusQuantity.Value, MillidegreesCelsiusTolerance); - Assert.Equal(TemperatureUnit.MillidegreeCelsius, millidegreecelsiusQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var solartemperatureQuantity = kelvin.ToUnit(TemperatureUnit.SolarTemperature); - AssertEx.EqualTolerance(SolarTemperaturesInOneKelvin, (double)solartemperatureQuantity.Value, SolarTemperaturesTolerance); - Assert.Equal(TemperatureUnit.SolarTemperature, solartemperatureQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(TemperatureUnit unit) + { + var quantity = Temperature.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureUnit unit) { - var quantityInBaseUnit = Temperature.FromKelvins(1).ToBaseUnit(); - Assert.Equal(Temperature.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Temperature.Units.FirstOrDefault(u => u != Temperature.BaseUnit && u != TemperatureUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == TemperatureUnit.Undefined) + fromUnit = Temperature.BaseUnit; + + var quantity = Temperature.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs index 1d5122321a..2fd369651a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -45,6 +46,22 @@ public abstract partial class ThermalConductivityTestsBase : QuantityTestsBase protected virtual double WattsPerMeterKelvinTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ThermalConductivityUnit unit) + { + return unit switch + { + ThermalConductivityUnit.BtuPerHourFootFahrenheit => (BtusPerHourFootFahrenheitInOneWattPerMeterKelvin, BtusPerHourFootFahrenheitTolerance), + ThermalConductivityUnit.WattPerMeterKelvin => (WattsPerMeterKelvinInOneWattPerMeterKelvin, WattsPerMeterKelvinTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ThermalConductivityUnit.BtuPerHourFootFahrenheit }, + new object[] { ThermalConductivityUnit.WattPerMeterKelvin }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -172,25 +189,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ThermalConductivityUnit unit) { - var wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); + var inBaseUnits = ThermalConductivity.From(1.0, ThermalConductivity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var btuperhourfootfahrenheitQuantity = wattpermeterkelvin.ToUnit(ThermalConductivityUnit.BtuPerHourFootFahrenheit); - AssertEx.EqualTolerance(BtusPerHourFootFahrenheitInOneWattPerMeterKelvin, (double)btuperhourfootfahrenheitQuantity.Value, BtusPerHourFootFahrenheitTolerance); - Assert.Equal(ThermalConductivityUnit.BtuPerHourFootFahrenheit, btuperhourfootfahrenheitQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var wattpermeterkelvinQuantity = wattpermeterkelvin.ToUnit(ThermalConductivityUnit.WattPerMeterKelvin); - AssertEx.EqualTolerance(WattsPerMeterKelvinInOneWattPerMeterKelvin, (double)wattpermeterkelvinQuantity.Value, WattsPerMeterKelvinTolerance); - Assert.Equal(ThermalConductivityUnit.WattPerMeterKelvin, wattpermeterkelvinQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ThermalConductivityUnit unit) + { + var quantity = ThermalConductivity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ThermalConductivityUnit unit) { - var quantityInBaseUnit = ThermalConductivity.FromWattsPerMeterKelvin(1).ToBaseUnit(); - Assert.Equal(ThermalConductivity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ThermalConductivity.Units.FirstOrDefault(u => u != ThermalConductivity.BaseUnit && u != ThermalConductivityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ThermalConductivityUnit.Undefined) + fromUnit = ThermalConductivity.BaseUnit; + + var quantity = ThermalConductivity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs index 2008dd27a2..213aea5006 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -53,6 +54,30 @@ public abstract partial class ThermalResistanceTestsBase : QuantityTestsBase protected virtual double SquareMeterKelvinsPerWattTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ThermalResistanceUnit unit) + { + return unit switch + { + ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu => (HourSquareFeetDegreesFahrenheitPerBtuInOneSquareMeterKelvinPerKilowatt, HourSquareFeetDegreesFahrenheitPerBtuTolerance), + ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie => (SquareCentimeterHourDegreesCelsiusPerKilocalorieInOneSquareMeterKelvinPerKilowatt, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance), + ThermalResistanceUnit.SquareCentimeterKelvinPerWatt => (SquareCentimeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt, SquareCentimeterKelvinsPerWattTolerance), + ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt => (SquareMeterDegreesCelsiusPerWattInOneSquareMeterKelvinPerKilowatt, SquareMeterDegreesCelsiusPerWattTolerance), + ThermalResistanceUnit.SquareMeterKelvinPerKilowatt => (SquareMeterKelvinsPerKilowattInOneSquareMeterKelvinPerKilowatt, SquareMeterKelvinsPerKilowattTolerance), + ThermalResistanceUnit.SquareMeterKelvinPerWatt => (SquareMeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt, SquareMeterKelvinsPerWattTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu }, + new object[] { ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie }, + new object[] { ThermalResistanceUnit.SquareCentimeterKelvinPerWatt }, + new object[] { ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt }, + new object[] { ThermalResistanceUnit.SquareMeterKelvinPerKilowatt }, + new object[] { ThermalResistanceUnit.SquareMeterKelvinPerWatt }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -204,41 +229,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(ThermalResistanceUnit unit) { - var squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - - var hoursquarefeetdegreefahrenheitperbtuQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); - AssertEx.EqualTolerance(HourSquareFeetDegreesFahrenheitPerBtuInOneSquareMeterKelvinPerKilowatt, (double)hoursquarefeetdegreefahrenheitperbtuQuantity.Value, HourSquareFeetDegreesFahrenheitPerBtuTolerance); - Assert.Equal(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, hoursquarefeetdegreefahrenheitperbtuQuantity.Unit); + var inBaseUnits = ThermalResistance.From(1.0, ThermalResistance.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var squarecentimeterhourdegreecelsiusperkilocalorieQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); - AssertEx.EqualTolerance(SquareCentimeterHourDegreesCelsiusPerKilocalorieInOneSquareMeterKelvinPerKilowatt, (double)squarecentimeterhourdegreecelsiusperkilocalorieQuantity.Value, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); - Assert.Equal(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, squarecentimeterhourdegreecelsiusperkilocalorieQuantity.Unit); - - var squarecentimeterkelvinperwattQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); - AssertEx.EqualTolerance(SquareCentimeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt, (double)squarecentimeterkelvinperwattQuantity.Value, SquareCentimeterKelvinsPerWattTolerance); - Assert.Equal(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, squarecentimeterkelvinperwattQuantity.Unit); - - var squaremeterdegreecelsiusperwattQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); - AssertEx.EqualTolerance(SquareMeterDegreesCelsiusPerWattInOneSquareMeterKelvinPerKilowatt, (double)squaremeterdegreecelsiusperwattQuantity.Value, SquareMeterDegreesCelsiusPerWattTolerance); - Assert.Equal(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, squaremeterdegreecelsiusperwattQuantity.Unit); - - var squaremeterkelvinperkilowattQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); - AssertEx.EqualTolerance(SquareMeterKelvinsPerKilowattInOneSquareMeterKelvinPerKilowatt, (double)squaremeterkelvinperkilowattQuantity.Value, SquareMeterKelvinsPerKilowattTolerance); - Assert.Equal(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowattQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var squaremeterkelvinperwattQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerWatt); - AssertEx.EqualTolerance(SquareMeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt, (double)squaremeterkelvinperwattQuantity.Value, SquareMeterKelvinsPerWattTolerance); - Assert.Equal(ThermalResistanceUnit.SquareMeterKelvinPerWatt, squaremeterkelvinperwattQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(ThermalResistanceUnit unit) + { + var quantity = ThermalResistance.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ThermalResistanceUnit unit) { - var quantityInBaseUnit = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1).ToBaseUnit(); - Assert.Equal(ThermalResistance.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = ThermalResistance.Units.FirstOrDefault(u => u != ThermalResistance.BaseUnit && u != ThermalResistanceUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == ThermalResistanceUnit.Undefined) + fromUnit = ThermalResistance.BaseUnit; + + var quantity = ThermalResistance.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs index 5bf790acfe..96315802a1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -83,6 +84,60 @@ public abstract partial class TorquePerLengthTestsBase : QuantityTestsBase protected virtual double TonneForceMillimetersPerMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TorquePerLengthUnit unit) + { + return unit switch + { + TorquePerLengthUnit.KilogramForceCentimeterPerMeter => (KilogramForceCentimetersPerMeterInOneNewtonMeterPerMeter, KilogramForceCentimetersPerMeterTolerance), + TorquePerLengthUnit.KilogramForceMeterPerMeter => (KilogramForceMetersPerMeterInOneNewtonMeterPerMeter, KilogramForceMetersPerMeterTolerance), + TorquePerLengthUnit.KilogramForceMillimeterPerMeter => (KilogramForceMillimetersPerMeterInOneNewtonMeterPerMeter, KilogramForceMillimetersPerMeterTolerance), + TorquePerLengthUnit.KilonewtonCentimeterPerMeter => (KilonewtonCentimetersPerMeterInOneNewtonMeterPerMeter, KilonewtonCentimetersPerMeterTolerance), + TorquePerLengthUnit.KilonewtonMeterPerMeter => (KilonewtonMetersPerMeterInOneNewtonMeterPerMeter, KilonewtonMetersPerMeterTolerance), + TorquePerLengthUnit.KilonewtonMillimeterPerMeter => (KilonewtonMillimetersPerMeterInOneNewtonMeterPerMeter, KilonewtonMillimetersPerMeterTolerance), + TorquePerLengthUnit.KilopoundForceFootPerFoot => (KilopoundForceFeetPerFootInOneNewtonMeterPerMeter, KilopoundForceFeetPerFootTolerance), + TorquePerLengthUnit.KilopoundForceInchPerFoot => (KilopoundForceInchesPerFootInOneNewtonMeterPerMeter, KilopoundForceInchesPerFootTolerance), + TorquePerLengthUnit.MeganewtonCentimeterPerMeter => (MeganewtonCentimetersPerMeterInOneNewtonMeterPerMeter, MeganewtonCentimetersPerMeterTolerance), + TorquePerLengthUnit.MeganewtonMeterPerMeter => (MeganewtonMetersPerMeterInOneNewtonMeterPerMeter, MeganewtonMetersPerMeterTolerance), + TorquePerLengthUnit.MeganewtonMillimeterPerMeter => (MeganewtonMillimetersPerMeterInOneNewtonMeterPerMeter, MeganewtonMillimetersPerMeterTolerance), + TorquePerLengthUnit.MegapoundForceFootPerFoot => (MegapoundForceFeetPerFootInOneNewtonMeterPerMeter, MegapoundForceFeetPerFootTolerance), + TorquePerLengthUnit.MegapoundForceInchPerFoot => (MegapoundForceInchesPerFootInOneNewtonMeterPerMeter, MegapoundForceInchesPerFootTolerance), + TorquePerLengthUnit.NewtonCentimeterPerMeter => (NewtonCentimetersPerMeterInOneNewtonMeterPerMeter, NewtonCentimetersPerMeterTolerance), + TorquePerLengthUnit.NewtonMeterPerMeter => (NewtonMetersPerMeterInOneNewtonMeterPerMeter, NewtonMetersPerMeterTolerance), + TorquePerLengthUnit.NewtonMillimeterPerMeter => (NewtonMillimetersPerMeterInOneNewtonMeterPerMeter, NewtonMillimetersPerMeterTolerance), + TorquePerLengthUnit.PoundForceFootPerFoot => (PoundForceFeetPerFootInOneNewtonMeterPerMeter, PoundForceFeetPerFootTolerance), + TorquePerLengthUnit.PoundForceInchPerFoot => (PoundForceInchesPerFootInOneNewtonMeterPerMeter, PoundForceInchesPerFootTolerance), + TorquePerLengthUnit.TonneForceCentimeterPerMeter => (TonneForceCentimetersPerMeterInOneNewtonMeterPerMeter, TonneForceCentimetersPerMeterTolerance), + TorquePerLengthUnit.TonneForceMeterPerMeter => (TonneForceMetersPerMeterInOneNewtonMeterPerMeter, TonneForceMetersPerMeterTolerance), + TorquePerLengthUnit.TonneForceMillimeterPerMeter => (TonneForceMillimetersPerMeterInOneNewtonMeterPerMeter, TonneForceMillimetersPerMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { TorquePerLengthUnit.KilogramForceCentimeterPerMeter }, + new object[] { TorquePerLengthUnit.KilogramForceMeterPerMeter }, + new object[] { TorquePerLengthUnit.KilogramForceMillimeterPerMeter }, + new object[] { TorquePerLengthUnit.KilonewtonCentimeterPerMeter }, + new object[] { TorquePerLengthUnit.KilonewtonMeterPerMeter }, + new object[] { TorquePerLengthUnit.KilonewtonMillimeterPerMeter }, + new object[] { TorquePerLengthUnit.KilopoundForceFootPerFoot }, + new object[] { TorquePerLengthUnit.KilopoundForceInchPerFoot }, + new object[] { TorquePerLengthUnit.MeganewtonCentimeterPerMeter }, + new object[] { TorquePerLengthUnit.MeganewtonMeterPerMeter }, + new object[] { TorquePerLengthUnit.MeganewtonMillimeterPerMeter }, + new object[] { TorquePerLengthUnit.MegapoundForceFootPerFoot }, + new object[] { TorquePerLengthUnit.MegapoundForceInchPerFoot }, + new object[] { TorquePerLengthUnit.NewtonCentimeterPerMeter }, + new object[] { TorquePerLengthUnit.NewtonMeterPerMeter }, + new object[] { TorquePerLengthUnit.NewtonMillimeterPerMeter }, + new object[] { TorquePerLengthUnit.PoundForceFootPerFoot }, + new object[] { TorquePerLengthUnit.PoundForceInchPerFoot }, + new object[] { TorquePerLengthUnit.TonneForceCentimeterPerMeter }, + new object[] { TorquePerLengthUnit.TonneForceMeterPerMeter }, + new object[] { TorquePerLengthUnit.TonneForceMillimeterPerMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -324,101 +379,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(TorquePerLengthUnit unit) { - var newtonmeterpermeter = TorquePerLength.FromNewtonMetersPerMeter(1); - - var kilogramforcecentimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.KilogramForceCentimeterPerMeter); - AssertEx.EqualTolerance(KilogramForceCentimetersPerMeterInOneNewtonMeterPerMeter, (double)kilogramforcecentimeterpermeterQuantity.Value, KilogramForceCentimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.KilogramForceCentimeterPerMeter, kilogramforcecentimeterpermeterQuantity.Unit); - - var kilogramforcemeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.KilogramForceMeterPerMeter); - AssertEx.EqualTolerance(KilogramForceMetersPerMeterInOneNewtonMeterPerMeter, (double)kilogramforcemeterpermeterQuantity.Value, KilogramForceMetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.KilogramForceMeterPerMeter, kilogramforcemeterpermeterQuantity.Unit); - - var kilogramforcemillimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.KilogramForceMillimeterPerMeter); - AssertEx.EqualTolerance(KilogramForceMillimetersPerMeterInOneNewtonMeterPerMeter, (double)kilogramforcemillimeterpermeterQuantity.Value, KilogramForceMillimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.KilogramForceMillimeterPerMeter, kilogramforcemillimeterpermeterQuantity.Unit); - - var kilonewtoncentimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.KilonewtonCentimeterPerMeter); - AssertEx.EqualTolerance(KilonewtonCentimetersPerMeterInOneNewtonMeterPerMeter, (double)kilonewtoncentimeterpermeterQuantity.Value, KilonewtonCentimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.KilonewtonCentimeterPerMeter, kilonewtoncentimeterpermeterQuantity.Unit); - - var kilonewtonmeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.KilonewtonMeterPerMeter); - AssertEx.EqualTolerance(KilonewtonMetersPerMeterInOneNewtonMeterPerMeter, (double)kilonewtonmeterpermeterQuantity.Value, KilonewtonMetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.KilonewtonMeterPerMeter, kilonewtonmeterpermeterQuantity.Unit); - - var kilonewtonmillimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.KilonewtonMillimeterPerMeter); - AssertEx.EqualTolerance(KilonewtonMillimetersPerMeterInOneNewtonMeterPerMeter, (double)kilonewtonmillimeterpermeterQuantity.Value, KilonewtonMillimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.KilonewtonMillimeterPerMeter, kilonewtonmillimeterpermeterQuantity.Unit); - - var kilopoundforcefootperfootQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.KilopoundForceFootPerFoot); - AssertEx.EqualTolerance(KilopoundForceFeetPerFootInOneNewtonMeterPerMeter, (double)kilopoundforcefootperfootQuantity.Value, KilopoundForceFeetPerFootTolerance); - Assert.Equal(TorquePerLengthUnit.KilopoundForceFootPerFoot, kilopoundforcefootperfootQuantity.Unit); - - var kilopoundforceinchperfootQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.KilopoundForceInchPerFoot); - AssertEx.EqualTolerance(KilopoundForceInchesPerFootInOneNewtonMeterPerMeter, (double)kilopoundforceinchperfootQuantity.Value, KilopoundForceInchesPerFootTolerance); - Assert.Equal(TorquePerLengthUnit.KilopoundForceInchPerFoot, kilopoundforceinchperfootQuantity.Unit); - - var meganewtoncentimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.MeganewtonCentimeterPerMeter); - AssertEx.EqualTolerance(MeganewtonCentimetersPerMeterInOneNewtonMeterPerMeter, (double)meganewtoncentimeterpermeterQuantity.Value, MeganewtonCentimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.MeganewtonCentimeterPerMeter, meganewtoncentimeterpermeterQuantity.Unit); - - var meganewtonmeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.MeganewtonMeterPerMeter); - AssertEx.EqualTolerance(MeganewtonMetersPerMeterInOneNewtonMeterPerMeter, (double)meganewtonmeterpermeterQuantity.Value, MeganewtonMetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.MeganewtonMeterPerMeter, meganewtonmeterpermeterQuantity.Unit); + var inBaseUnits = TorquePerLength.From(1.0, TorquePerLength.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var meganewtonmillimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.MeganewtonMillimeterPerMeter); - AssertEx.EqualTolerance(MeganewtonMillimetersPerMeterInOneNewtonMeterPerMeter, (double)meganewtonmillimeterpermeterQuantity.Value, MeganewtonMillimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.MeganewtonMillimeterPerMeter, meganewtonmillimeterpermeterQuantity.Unit); - - var megapoundforcefootperfootQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.MegapoundForceFootPerFoot); - AssertEx.EqualTolerance(MegapoundForceFeetPerFootInOneNewtonMeterPerMeter, (double)megapoundforcefootperfootQuantity.Value, MegapoundForceFeetPerFootTolerance); - Assert.Equal(TorquePerLengthUnit.MegapoundForceFootPerFoot, megapoundforcefootperfootQuantity.Unit); - - var megapoundforceinchperfootQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.MegapoundForceInchPerFoot); - AssertEx.EqualTolerance(MegapoundForceInchesPerFootInOneNewtonMeterPerMeter, (double)megapoundforceinchperfootQuantity.Value, MegapoundForceInchesPerFootTolerance); - Assert.Equal(TorquePerLengthUnit.MegapoundForceInchPerFoot, megapoundforceinchperfootQuantity.Unit); - - var newtoncentimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.NewtonCentimeterPerMeter); - AssertEx.EqualTolerance(NewtonCentimetersPerMeterInOneNewtonMeterPerMeter, (double)newtoncentimeterpermeterQuantity.Value, NewtonCentimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.NewtonCentimeterPerMeter, newtoncentimeterpermeterQuantity.Unit); - - var newtonmeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter); - AssertEx.EqualTolerance(NewtonMetersPerMeterInOneNewtonMeterPerMeter, (double)newtonmeterpermeterQuantity.Value, NewtonMetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.NewtonMeterPerMeter, newtonmeterpermeterQuantity.Unit); - - var newtonmillimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.NewtonMillimeterPerMeter); - AssertEx.EqualTolerance(NewtonMillimetersPerMeterInOneNewtonMeterPerMeter, (double)newtonmillimeterpermeterQuantity.Value, NewtonMillimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.NewtonMillimeterPerMeter, newtonmillimeterpermeterQuantity.Unit); - - var poundforcefootperfootQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.PoundForceFootPerFoot); - AssertEx.EqualTolerance(PoundForceFeetPerFootInOneNewtonMeterPerMeter, (double)poundforcefootperfootQuantity.Value, PoundForceFeetPerFootTolerance); - Assert.Equal(TorquePerLengthUnit.PoundForceFootPerFoot, poundforcefootperfootQuantity.Unit); - - var poundforceinchperfootQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.PoundForceInchPerFoot); - AssertEx.EqualTolerance(PoundForceInchesPerFootInOneNewtonMeterPerMeter, (double)poundforceinchperfootQuantity.Value, PoundForceInchesPerFootTolerance); - Assert.Equal(TorquePerLengthUnit.PoundForceInchPerFoot, poundforceinchperfootQuantity.Unit); - - var tonneforcecentimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.TonneForceCentimeterPerMeter); - AssertEx.EqualTolerance(TonneForceCentimetersPerMeterInOneNewtonMeterPerMeter, (double)tonneforcecentimeterpermeterQuantity.Value, TonneForceCentimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.TonneForceCentimeterPerMeter, tonneforcecentimeterpermeterQuantity.Unit); - - var tonneforcemeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.TonneForceMeterPerMeter); - AssertEx.EqualTolerance(TonneForceMetersPerMeterInOneNewtonMeterPerMeter, (double)tonneforcemeterpermeterQuantity.Value, TonneForceMetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.TonneForceMeterPerMeter, tonneforcemeterpermeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonneforcemillimeterpermeterQuantity = newtonmeterpermeter.ToUnit(TorquePerLengthUnit.TonneForceMillimeterPerMeter); - AssertEx.EqualTolerance(TonneForceMillimetersPerMeterInOneNewtonMeterPerMeter, (double)tonneforcemillimeterpermeterQuantity.Value, TonneForceMillimetersPerMeterTolerance); - Assert.Equal(TorquePerLengthUnit.TonneForceMillimeterPerMeter, tonneforcemillimeterpermeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(TorquePerLengthUnit unit) + { + var quantity = TorquePerLength.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TorquePerLengthUnit unit) { - var quantityInBaseUnit = TorquePerLength.FromNewtonMetersPerMeter(1).ToBaseUnit(); - Assert.Equal(TorquePerLength.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = TorquePerLength.Units.FirstOrDefault(u => u != TorquePerLength.BaseUnit && u != TorquePerLengthUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == TorquePerLengthUnit.Undefined) + fromUnit = TorquePerLength.BaseUnit; + + var quantity = TorquePerLength.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs index 2086b3fde6..6f91770d4b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -91,6 +92,68 @@ public abstract partial class TorqueTestsBase : QuantityTestsBase protected virtual double TonneForceMillimetersTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TorqueUnit unit) + { + return unit switch + { + TorqueUnit.GramForceCentimeter => (GramForceCentimetersInOneNewtonMeter, GramForceCentimetersTolerance), + TorqueUnit.GramForceMeter => (GramForceMetersInOneNewtonMeter, GramForceMetersTolerance), + TorqueUnit.GramForceMillimeter => (GramForceMillimetersInOneNewtonMeter, GramForceMillimetersTolerance), + TorqueUnit.KilogramForceCentimeter => (KilogramForceCentimetersInOneNewtonMeter, KilogramForceCentimetersTolerance), + TorqueUnit.KilogramForceMeter => (KilogramForceMetersInOneNewtonMeter, KilogramForceMetersTolerance), + TorqueUnit.KilogramForceMillimeter => (KilogramForceMillimetersInOneNewtonMeter, KilogramForceMillimetersTolerance), + TorqueUnit.KilonewtonCentimeter => (KilonewtonCentimetersInOneNewtonMeter, KilonewtonCentimetersTolerance), + TorqueUnit.KilonewtonMeter => (KilonewtonMetersInOneNewtonMeter, KilonewtonMetersTolerance), + TorqueUnit.KilonewtonMillimeter => (KilonewtonMillimetersInOneNewtonMeter, KilonewtonMillimetersTolerance), + TorqueUnit.KilopoundForceFoot => (KilopoundForceFeetInOneNewtonMeter, KilopoundForceFeetTolerance), + TorqueUnit.KilopoundForceInch => (KilopoundForceInchesInOneNewtonMeter, KilopoundForceInchesTolerance), + TorqueUnit.MeganewtonCentimeter => (MeganewtonCentimetersInOneNewtonMeter, MeganewtonCentimetersTolerance), + TorqueUnit.MeganewtonMeter => (MeganewtonMetersInOneNewtonMeter, MeganewtonMetersTolerance), + TorqueUnit.MeganewtonMillimeter => (MeganewtonMillimetersInOneNewtonMeter, MeganewtonMillimetersTolerance), + TorqueUnit.MegapoundForceFoot => (MegapoundForceFeetInOneNewtonMeter, MegapoundForceFeetTolerance), + TorqueUnit.MegapoundForceInch => (MegapoundForceInchesInOneNewtonMeter, MegapoundForceInchesTolerance), + TorqueUnit.NewtonCentimeter => (NewtonCentimetersInOneNewtonMeter, NewtonCentimetersTolerance), + TorqueUnit.NewtonMeter => (NewtonMetersInOneNewtonMeter, NewtonMetersTolerance), + TorqueUnit.NewtonMillimeter => (NewtonMillimetersInOneNewtonMeter, NewtonMillimetersTolerance), + TorqueUnit.PoundalFoot => (PoundalFeetInOneNewtonMeter, PoundalFeetTolerance), + TorqueUnit.PoundForceFoot => (PoundForceFeetInOneNewtonMeter, PoundForceFeetTolerance), + TorqueUnit.PoundForceInch => (PoundForceInchesInOneNewtonMeter, PoundForceInchesTolerance), + TorqueUnit.TonneForceCentimeter => (TonneForceCentimetersInOneNewtonMeter, TonneForceCentimetersTolerance), + TorqueUnit.TonneForceMeter => (TonneForceMetersInOneNewtonMeter, TonneForceMetersTolerance), + TorqueUnit.TonneForceMillimeter => (TonneForceMillimetersInOneNewtonMeter, TonneForceMillimetersTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { TorqueUnit.GramForceCentimeter }, + new object[] { TorqueUnit.GramForceMeter }, + new object[] { TorqueUnit.GramForceMillimeter }, + new object[] { TorqueUnit.KilogramForceCentimeter }, + new object[] { TorqueUnit.KilogramForceMeter }, + new object[] { TorqueUnit.KilogramForceMillimeter }, + new object[] { TorqueUnit.KilonewtonCentimeter }, + new object[] { TorqueUnit.KilonewtonMeter }, + new object[] { TorqueUnit.KilonewtonMillimeter }, + new object[] { TorqueUnit.KilopoundForceFoot }, + new object[] { TorqueUnit.KilopoundForceInch }, + new object[] { TorqueUnit.MeganewtonCentimeter }, + new object[] { TorqueUnit.MeganewtonMeter }, + new object[] { TorqueUnit.MeganewtonMillimeter }, + new object[] { TorqueUnit.MegapoundForceFoot }, + new object[] { TorqueUnit.MegapoundForceInch }, + new object[] { TorqueUnit.NewtonCentimeter }, + new object[] { TorqueUnit.NewtonMeter }, + new object[] { TorqueUnit.NewtonMillimeter }, + new object[] { TorqueUnit.PoundalFoot }, + new object[] { TorqueUnit.PoundForceFoot }, + new object[] { TorqueUnit.PoundForceInch }, + new object[] { TorqueUnit.TonneForceCentimeter }, + new object[] { TorqueUnit.TonneForceMeter }, + new object[] { TorqueUnit.TonneForceMillimeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -356,117 +419,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(TorqueUnit unit) { - var newtonmeter = Torque.FromNewtonMeters(1); - - var gramforcecentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.GramForceCentimeter); - AssertEx.EqualTolerance(GramForceCentimetersInOneNewtonMeter, (double)gramforcecentimeterQuantity.Value, GramForceCentimetersTolerance); - Assert.Equal(TorqueUnit.GramForceCentimeter, gramforcecentimeterQuantity.Unit); - - var gramforcemeterQuantity = newtonmeter.ToUnit(TorqueUnit.GramForceMeter); - AssertEx.EqualTolerance(GramForceMetersInOneNewtonMeter, (double)gramforcemeterQuantity.Value, GramForceMetersTolerance); - Assert.Equal(TorqueUnit.GramForceMeter, gramforcemeterQuantity.Unit); - - var gramforcemillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.GramForceMillimeter); - AssertEx.EqualTolerance(GramForceMillimetersInOneNewtonMeter, (double)gramforcemillimeterQuantity.Value, GramForceMillimetersTolerance); - Assert.Equal(TorqueUnit.GramForceMillimeter, gramforcemillimeterQuantity.Unit); - - var kilogramforcecentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilogramForceCentimeter); - AssertEx.EqualTolerance(KilogramForceCentimetersInOneNewtonMeter, (double)kilogramforcecentimeterQuantity.Value, KilogramForceCentimetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceCentimeter, kilogramforcecentimeterQuantity.Unit); - - var kilogramforcemeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilogramForceMeter); - AssertEx.EqualTolerance(KilogramForceMetersInOneNewtonMeter, (double)kilogramforcemeterQuantity.Value, KilogramForceMetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceMeter, kilogramforcemeterQuantity.Unit); - - var kilogramforcemillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilogramForceMillimeter); - AssertEx.EqualTolerance(KilogramForceMillimetersInOneNewtonMeter, (double)kilogramforcemillimeterQuantity.Value, KilogramForceMillimetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceMillimeter, kilogramforcemillimeterQuantity.Unit); - - var kilonewtoncentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilonewtonCentimeter); - AssertEx.EqualTolerance(KilonewtonCentimetersInOneNewtonMeter, (double)kilonewtoncentimeterQuantity.Value, KilonewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonCentimeter, kilonewtoncentimeterQuantity.Unit); - - var kilonewtonmeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilonewtonMeter); - AssertEx.EqualTolerance(KilonewtonMetersInOneNewtonMeter, (double)kilonewtonmeterQuantity.Value, KilonewtonMetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMeter, kilonewtonmeterQuantity.Unit); - - var kilonewtonmillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilonewtonMillimeter); - AssertEx.EqualTolerance(KilonewtonMillimetersInOneNewtonMeter, (double)kilonewtonmillimeterQuantity.Value, KilonewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMillimeter, kilonewtonmillimeterQuantity.Unit); - - var kilopoundforcefootQuantity = newtonmeter.ToUnit(TorqueUnit.KilopoundForceFoot); - AssertEx.EqualTolerance(KilopoundForceFeetInOneNewtonMeter, (double)kilopoundforcefootQuantity.Value, KilopoundForceFeetTolerance); - Assert.Equal(TorqueUnit.KilopoundForceFoot, kilopoundforcefootQuantity.Unit); - - var kilopoundforceinchQuantity = newtonmeter.ToUnit(TorqueUnit.KilopoundForceInch); - AssertEx.EqualTolerance(KilopoundForceInchesInOneNewtonMeter, (double)kilopoundforceinchQuantity.Value, KilopoundForceInchesTolerance); - Assert.Equal(TorqueUnit.KilopoundForceInch, kilopoundforceinchQuantity.Unit); - - var meganewtoncentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.MeganewtonCentimeter); - AssertEx.EqualTolerance(MeganewtonCentimetersInOneNewtonMeter, (double)meganewtoncentimeterQuantity.Value, MeganewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonCentimeter, meganewtoncentimeterQuantity.Unit); + var inBaseUnits = Torque.From(1.0, Torque.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var meganewtonmeterQuantity = newtonmeter.ToUnit(TorqueUnit.MeganewtonMeter); - AssertEx.EqualTolerance(MeganewtonMetersInOneNewtonMeter, (double)meganewtonmeterQuantity.Value, MeganewtonMetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMeter, meganewtonmeterQuantity.Unit); - - var meganewtonmillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.MeganewtonMillimeter); - AssertEx.EqualTolerance(MeganewtonMillimetersInOneNewtonMeter, (double)meganewtonmillimeterQuantity.Value, MeganewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMillimeter, meganewtonmillimeterQuantity.Unit); - - var megapoundforcefootQuantity = newtonmeter.ToUnit(TorqueUnit.MegapoundForceFoot); - AssertEx.EqualTolerance(MegapoundForceFeetInOneNewtonMeter, (double)megapoundforcefootQuantity.Value, MegapoundForceFeetTolerance); - Assert.Equal(TorqueUnit.MegapoundForceFoot, megapoundforcefootQuantity.Unit); - - var megapoundforceinchQuantity = newtonmeter.ToUnit(TorqueUnit.MegapoundForceInch); - AssertEx.EqualTolerance(MegapoundForceInchesInOneNewtonMeter, (double)megapoundforceinchQuantity.Value, MegapoundForceInchesTolerance); - Assert.Equal(TorqueUnit.MegapoundForceInch, megapoundforceinchQuantity.Unit); - - var newtoncentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.NewtonCentimeter); - AssertEx.EqualTolerance(NewtonCentimetersInOneNewtonMeter, (double)newtoncentimeterQuantity.Value, NewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.NewtonCentimeter, newtoncentimeterQuantity.Unit); - - var newtonmeterQuantity = newtonmeter.ToUnit(TorqueUnit.NewtonMeter); - AssertEx.EqualTolerance(NewtonMetersInOneNewtonMeter, (double)newtonmeterQuantity.Value, NewtonMetersTolerance); - Assert.Equal(TorqueUnit.NewtonMeter, newtonmeterQuantity.Unit); - - var newtonmillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.NewtonMillimeter); - AssertEx.EqualTolerance(NewtonMillimetersInOneNewtonMeter, (double)newtonmillimeterQuantity.Value, NewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.NewtonMillimeter, newtonmillimeterQuantity.Unit); - - var poundalfootQuantity = newtonmeter.ToUnit(TorqueUnit.PoundalFoot); - AssertEx.EqualTolerance(PoundalFeetInOneNewtonMeter, (double)poundalfootQuantity.Value, PoundalFeetTolerance); - Assert.Equal(TorqueUnit.PoundalFoot, poundalfootQuantity.Unit); - - var poundforcefootQuantity = newtonmeter.ToUnit(TorqueUnit.PoundForceFoot); - AssertEx.EqualTolerance(PoundForceFeetInOneNewtonMeter, (double)poundforcefootQuantity.Value, PoundForceFeetTolerance); - Assert.Equal(TorqueUnit.PoundForceFoot, poundforcefootQuantity.Unit); - - var poundforceinchQuantity = newtonmeter.ToUnit(TorqueUnit.PoundForceInch); - AssertEx.EqualTolerance(PoundForceInchesInOneNewtonMeter, (double)poundforceinchQuantity.Value, PoundForceInchesTolerance); - Assert.Equal(TorqueUnit.PoundForceInch, poundforceinchQuantity.Unit); - - var tonneforcecentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.TonneForceCentimeter); - AssertEx.EqualTolerance(TonneForceCentimetersInOneNewtonMeter, (double)tonneforcecentimeterQuantity.Value, TonneForceCentimetersTolerance); - Assert.Equal(TorqueUnit.TonneForceCentimeter, tonneforcecentimeterQuantity.Unit); - - var tonneforcemeterQuantity = newtonmeter.ToUnit(TorqueUnit.TonneForceMeter); - AssertEx.EqualTolerance(TonneForceMetersInOneNewtonMeter, (double)tonneforcemeterQuantity.Value, TonneForceMetersTolerance); - Assert.Equal(TorqueUnit.TonneForceMeter, tonneforcemeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var tonneforcemillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.TonneForceMillimeter); - AssertEx.EqualTolerance(TonneForceMillimetersInOneNewtonMeter, (double)tonneforcemillimeterQuantity.Value, TonneForceMillimetersTolerance); - Assert.Equal(TorqueUnit.TonneForceMillimeter, tonneforcemillimeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(TorqueUnit unit) + { + var quantity = Torque.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TorqueUnit unit) { - var quantityInBaseUnit = Torque.FromNewtonMeters(1).ToBaseUnit(); - Assert.Equal(Torque.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Torque.Units.FirstOrDefault(u => u != Torque.BaseUnit && u != TorqueUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == TorqueUnit.Undefined) + fromUnit = Torque.BaseUnit; + + var quantity = Torque.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs index f4b6eac73c..808250da97 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class TurbidityTestsBase : QuantityTestsBase protected virtual double NTUTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TurbidityUnit unit) + { + return unit switch + { + TurbidityUnit.NTU => (NTUInOneNTU, NTUTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { TurbidityUnit.NTU }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(TurbidityUnit unit) { - var ntu = Turbidity.FromNTU(1); + var inBaseUnits = Turbidity.From(1.0, Turbidity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var ntuQuantity = ntu.ToUnit(TurbidityUnit.NTU); - AssertEx.EqualTolerance(NTUInOneNTU, (double)ntuQuantity.Value, NTUTolerance); - Assert.Equal(TurbidityUnit.NTU, ntuQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(TurbidityUnit unit) + { + var quantity = Turbidity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TurbidityUnit unit) { - var quantityInBaseUnit = Turbidity.FromNTU(1).ToBaseUnit(); - Assert.Equal(Turbidity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Turbidity.Units.FirstOrDefault(u => u != Turbidity.BaseUnit && u != TurbidityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == TurbidityUnit.Undefined) + fromUnit = Turbidity.BaseUnit; + + var quantity = Turbidity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs index 8e774dac97..0858d5e41e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -43,6 +44,20 @@ public abstract partial class VitaminATestsBase : QuantityTestsBase protected virtual double InternationalUnitsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VitaminAUnit unit) + { + return unit switch + { + VitaminAUnit.InternationalUnit => (InternationalUnitsInOneInternationalUnit, InternationalUnitsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { VitaminAUnit.InternationalUnit }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -164,21 +179,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(VitaminAUnit unit) { - var internationalunit = VitaminA.FromInternationalUnits(1); + var inBaseUnits = VitaminA.From(1.0, VitaminA.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var internationalunitQuantity = internationalunit.ToUnit(VitaminAUnit.InternationalUnit); - AssertEx.EqualTolerance(InternationalUnitsInOneInternationalUnit, (double)internationalunitQuantity.Value, InternationalUnitsTolerance); - Assert.Equal(VitaminAUnit.InternationalUnit, internationalunitQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(VitaminAUnit unit) + { + var quantity = VitaminA.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VitaminAUnit unit) { - var quantityInBaseUnit = VitaminA.FromInternationalUnits(1).ToBaseUnit(); - Assert.Equal(VitaminA.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = VitaminA.Units.FirstOrDefault(u => u != VitaminA.BaseUnit && u != VitaminAUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == VitaminAUnit.Undefined) + fromUnit = VitaminA.BaseUnit; + + var quantity = VitaminA.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs index 085e791a32..9db1eea2be 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -81,6 +82,58 @@ public abstract partial class VolumeConcentrationTestsBase : QuantityTestsBase protected virtual double PicolitersPerMililiterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumeConcentrationUnit unit) + { + return unit switch + { + VolumeConcentrationUnit.CentilitersPerLiter => (CentilitersPerLiterInOneDecimalFraction, CentilitersPerLiterTolerance), + VolumeConcentrationUnit.CentilitersPerMililiter => (CentilitersPerMililiterInOneDecimalFraction, CentilitersPerMililiterTolerance), + VolumeConcentrationUnit.DecilitersPerLiter => (DecilitersPerLiterInOneDecimalFraction, DecilitersPerLiterTolerance), + VolumeConcentrationUnit.DecilitersPerMililiter => (DecilitersPerMililiterInOneDecimalFraction, DecilitersPerMililiterTolerance), + VolumeConcentrationUnit.DecimalFraction => (DecimalFractionsInOneDecimalFraction, DecimalFractionsTolerance), + VolumeConcentrationUnit.LitersPerLiter => (LitersPerLiterInOneDecimalFraction, LitersPerLiterTolerance), + VolumeConcentrationUnit.LitersPerMililiter => (LitersPerMililiterInOneDecimalFraction, LitersPerMililiterTolerance), + VolumeConcentrationUnit.MicrolitersPerLiter => (MicrolitersPerLiterInOneDecimalFraction, MicrolitersPerLiterTolerance), + VolumeConcentrationUnit.MicrolitersPerMililiter => (MicrolitersPerMililiterInOneDecimalFraction, MicrolitersPerMililiterTolerance), + VolumeConcentrationUnit.MillilitersPerLiter => (MillilitersPerLiterInOneDecimalFraction, MillilitersPerLiterTolerance), + VolumeConcentrationUnit.MillilitersPerMililiter => (MillilitersPerMililiterInOneDecimalFraction, MillilitersPerMililiterTolerance), + VolumeConcentrationUnit.NanolitersPerLiter => (NanolitersPerLiterInOneDecimalFraction, NanolitersPerLiterTolerance), + VolumeConcentrationUnit.NanolitersPerMililiter => (NanolitersPerMililiterInOneDecimalFraction, NanolitersPerMililiterTolerance), + VolumeConcentrationUnit.PartPerBillion => (PartsPerBillionInOneDecimalFraction, PartsPerBillionTolerance), + VolumeConcentrationUnit.PartPerMillion => (PartsPerMillionInOneDecimalFraction, PartsPerMillionTolerance), + VolumeConcentrationUnit.PartPerThousand => (PartsPerThousandInOneDecimalFraction, PartsPerThousandTolerance), + VolumeConcentrationUnit.PartPerTrillion => (PartsPerTrillionInOneDecimalFraction, PartsPerTrillionTolerance), + VolumeConcentrationUnit.Percent => (PercentInOneDecimalFraction, PercentTolerance), + VolumeConcentrationUnit.PicolitersPerLiter => (PicolitersPerLiterInOneDecimalFraction, PicolitersPerLiterTolerance), + VolumeConcentrationUnit.PicolitersPerMililiter => (PicolitersPerMililiterInOneDecimalFraction, PicolitersPerMililiterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { VolumeConcentrationUnit.CentilitersPerLiter }, + new object[] { VolumeConcentrationUnit.CentilitersPerMililiter }, + new object[] { VolumeConcentrationUnit.DecilitersPerLiter }, + new object[] { VolumeConcentrationUnit.DecilitersPerMililiter }, + new object[] { VolumeConcentrationUnit.DecimalFraction }, + new object[] { VolumeConcentrationUnit.LitersPerLiter }, + new object[] { VolumeConcentrationUnit.LitersPerMililiter }, + new object[] { VolumeConcentrationUnit.MicrolitersPerLiter }, + new object[] { VolumeConcentrationUnit.MicrolitersPerMililiter }, + new object[] { VolumeConcentrationUnit.MillilitersPerLiter }, + new object[] { VolumeConcentrationUnit.MillilitersPerMililiter }, + new object[] { VolumeConcentrationUnit.NanolitersPerLiter }, + new object[] { VolumeConcentrationUnit.NanolitersPerMililiter }, + new object[] { VolumeConcentrationUnit.PartPerBillion }, + new object[] { VolumeConcentrationUnit.PartPerMillion }, + new object[] { VolumeConcentrationUnit.PartPerThousand }, + new object[] { VolumeConcentrationUnit.PartPerTrillion }, + new object[] { VolumeConcentrationUnit.Percent }, + new object[] { VolumeConcentrationUnit.PicolitersPerLiter }, + new object[] { VolumeConcentrationUnit.PicolitersPerMililiter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -316,97 +369,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(VolumeConcentrationUnit unit) { - var decimalfraction = VolumeConcentration.FromDecimalFractions(1); - - var centilitersperliterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.CentilitersPerLiter); - AssertEx.EqualTolerance(CentilitersPerLiterInOneDecimalFraction, (double)centilitersperliterQuantity.Value, CentilitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.CentilitersPerLiter, centilitersperliterQuantity.Unit); - - var centiliterspermililiterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.CentilitersPerMililiter); - AssertEx.EqualTolerance(CentilitersPerMililiterInOneDecimalFraction, (double)centiliterspermililiterQuantity.Value, CentilitersPerMililiterTolerance); - Assert.Equal(VolumeConcentrationUnit.CentilitersPerMililiter, centiliterspermililiterQuantity.Unit); - - var decilitersperliterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.DecilitersPerLiter); - AssertEx.EqualTolerance(DecilitersPerLiterInOneDecimalFraction, (double)decilitersperliterQuantity.Value, DecilitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.DecilitersPerLiter, decilitersperliterQuantity.Unit); - - var deciliterspermililiterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.DecilitersPerMililiter); - AssertEx.EqualTolerance(DecilitersPerMililiterInOneDecimalFraction, (double)deciliterspermililiterQuantity.Value, DecilitersPerMililiterTolerance); - Assert.Equal(VolumeConcentrationUnit.DecilitersPerMililiter, deciliterspermililiterQuantity.Unit); - - var decimalfractionQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.DecimalFraction); - AssertEx.EqualTolerance(DecimalFractionsInOneDecimalFraction, (double)decimalfractionQuantity.Value, DecimalFractionsTolerance); - Assert.Equal(VolumeConcentrationUnit.DecimalFraction, decimalfractionQuantity.Unit); - - var litersperliterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.LitersPerLiter); - AssertEx.EqualTolerance(LitersPerLiterInOneDecimalFraction, (double)litersperliterQuantity.Value, LitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.LitersPerLiter, litersperliterQuantity.Unit); - - var literspermililiterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.LitersPerMililiter); - AssertEx.EqualTolerance(LitersPerMililiterInOneDecimalFraction, (double)literspermililiterQuantity.Value, LitersPerMililiterTolerance); - Assert.Equal(VolumeConcentrationUnit.LitersPerMililiter, literspermililiterQuantity.Unit); - - var microlitersperliterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.MicrolitersPerLiter); - AssertEx.EqualTolerance(MicrolitersPerLiterInOneDecimalFraction, (double)microlitersperliterQuantity.Value, MicrolitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.MicrolitersPerLiter, microlitersperliterQuantity.Unit); - - var microliterspermililiterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.MicrolitersPerMililiter); - AssertEx.EqualTolerance(MicrolitersPerMililiterInOneDecimalFraction, (double)microliterspermililiterQuantity.Value, MicrolitersPerMililiterTolerance); - Assert.Equal(VolumeConcentrationUnit.MicrolitersPerMililiter, microliterspermililiterQuantity.Unit); - - var millilitersperliterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.MillilitersPerLiter); - AssertEx.EqualTolerance(MillilitersPerLiterInOneDecimalFraction, (double)millilitersperliterQuantity.Value, MillilitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.MillilitersPerLiter, millilitersperliterQuantity.Unit); + var inBaseUnits = VolumeConcentration.From(1.0, VolumeConcentration.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var milliliterspermililiterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.MillilitersPerMililiter); - AssertEx.EqualTolerance(MillilitersPerMililiterInOneDecimalFraction, (double)milliliterspermililiterQuantity.Value, MillilitersPerMililiterTolerance); - Assert.Equal(VolumeConcentrationUnit.MillilitersPerMililiter, milliliterspermililiterQuantity.Unit); - - var nanolitersperliterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.NanolitersPerLiter); - AssertEx.EqualTolerance(NanolitersPerLiterInOneDecimalFraction, (double)nanolitersperliterQuantity.Value, NanolitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.NanolitersPerLiter, nanolitersperliterQuantity.Unit); - - var nanoliterspermililiterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.NanolitersPerMililiter); - AssertEx.EqualTolerance(NanolitersPerMililiterInOneDecimalFraction, (double)nanoliterspermililiterQuantity.Value, NanolitersPerMililiterTolerance); - Assert.Equal(VolumeConcentrationUnit.NanolitersPerMililiter, nanoliterspermililiterQuantity.Unit); - - var partperbillionQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.PartPerBillion); - AssertEx.EqualTolerance(PartsPerBillionInOneDecimalFraction, (double)partperbillionQuantity.Value, PartsPerBillionTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerBillion, partperbillionQuantity.Unit); - - var partpermillionQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.PartPerMillion); - AssertEx.EqualTolerance(PartsPerMillionInOneDecimalFraction, (double)partpermillionQuantity.Value, PartsPerMillionTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerMillion, partpermillionQuantity.Unit); - - var partperthousandQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.PartPerThousand); - AssertEx.EqualTolerance(PartsPerThousandInOneDecimalFraction, (double)partperthousandQuantity.Value, PartsPerThousandTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerThousand, partperthousandQuantity.Unit); - - var partpertrillionQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.PartPerTrillion); - AssertEx.EqualTolerance(PartsPerTrillionInOneDecimalFraction, (double)partpertrillionQuantity.Value, PartsPerTrillionTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerTrillion, partpertrillionQuantity.Unit); - - var percentQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.Percent); - AssertEx.EqualTolerance(PercentInOneDecimalFraction, (double)percentQuantity.Value, PercentTolerance); - Assert.Equal(VolumeConcentrationUnit.Percent, percentQuantity.Unit); - - var picolitersperliterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.PicolitersPerLiter); - AssertEx.EqualTolerance(PicolitersPerLiterInOneDecimalFraction, (double)picolitersperliterQuantity.Value, PicolitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.PicolitersPerLiter, picolitersperliterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var picoliterspermililiterQuantity = decimalfraction.ToUnit(VolumeConcentrationUnit.PicolitersPerMililiter); - AssertEx.EqualTolerance(PicolitersPerMililiterInOneDecimalFraction, (double)picoliterspermililiterQuantity.Value, PicolitersPerMililiterTolerance); - Assert.Equal(VolumeConcentrationUnit.PicolitersPerMililiter, picoliterspermililiterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(VolumeConcentrationUnit unit) + { + var quantity = VolumeConcentration.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeConcentrationUnit unit) { - var quantityInBaseUnit = VolumeConcentration.FromDecimalFractions(1).ToBaseUnit(); - Assert.Equal(VolumeConcentration.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = VolumeConcentration.Units.FirstOrDefault(u => u != VolumeConcentration.BaseUnit && u != VolumeConcentrationUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == VolumeConcentrationUnit.Undefined) + fromUnit = VolumeConcentration.BaseUnit; + + var quantity = VolumeConcentration.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs index 766a0a6b53..6758c1bdb2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -45,6 +46,22 @@ public abstract partial class VolumeFlowPerAreaTestsBase : QuantityTestsBase protected virtual double CubicMetersPerSecondPerSquareMeterTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumeFlowPerAreaUnit unit) + { + return unit switch + { + VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot => (CubicFeetPerMinutePerSquareFootInOneCubicMeterPerSecondPerSquareMeter, CubicFeetPerMinutePerSquareFootTolerance), + VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter => (CubicMetersPerSecondPerSquareMeterInOneCubicMeterPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot }, + new object[] { VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -172,25 +189,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(VolumeFlowPerAreaUnit unit) { - var cubicmeterpersecondpersquaremeter = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); + var inBaseUnits = VolumeFlowPerArea.From(1.0, VolumeFlowPerArea.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var cubicfootperminutepersquarefootQuantity = cubicmeterpersecondpersquaremeter.ToUnit(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); - AssertEx.EqualTolerance(CubicFeetPerMinutePerSquareFootInOneCubicMeterPerSecondPerSquareMeter, (double)cubicfootperminutepersquarefootQuantity.Value, CubicFeetPerMinutePerSquareFootTolerance); - Assert.Equal(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, cubicfootperminutepersquarefootQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var cubicmeterpersecondpersquaremeterQuantity = cubicmeterpersecondpersquaremeter.ToUnit(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); - AssertEx.EqualTolerance(CubicMetersPerSecondPerSquareMeterInOneCubicMeterPerSecondPerSquareMeter, (double)cubicmeterpersecondpersquaremeterQuantity.Value, CubicMetersPerSecondPerSquareMeterTolerance); - Assert.Equal(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, cubicmeterpersecondpersquaremeterQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(VolumeFlowPerAreaUnit unit) + { + var quantity = VolumeFlowPerArea.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeFlowPerAreaUnit unit) { - var quantityInBaseUnit = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1).ToBaseUnit(); - Assert.Equal(VolumeFlowPerArea.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = VolumeFlowPerArea.Units.FirstOrDefault(u => u != VolumeFlowPerArea.BaseUnit && u != VolumeFlowPerAreaUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == VolumeFlowPerAreaUnit.Undefined) + fromUnit = VolumeFlowPerArea.BaseUnit; + + var quantity = VolumeFlowPerArea.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs index 25d807d135..bbbc2ee7a6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -165,6 +166,142 @@ public abstract partial class VolumeFlowTestsBase : QuantityTestsBase protected virtual double UsGallonsPerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumeFlowUnit unit) + { + return unit switch + { + VolumeFlowUnit.AcreFootPerDay => (AcreFeetPerDayInOneCubicMeterPerSecond, AcreFeetPerDayTolerance), + VolumeFlowUnit.AcreFootPerHour => (AcreFeetPerHourInOneCubicMeterPerSecond, AcreFeetPerHourTolerance), + VolumeFlowUnit.AcreFootPerMinute => (AcreFeetPerMinuteInOneCubicMeterPerSecond, AcreFeetPerMinuteTolerance), + VolumeFlowUnit.AcreFootPerSecond => (AcreFeetPerSecondInOneCubicMeterPerSecond, AcreFeetPerSecondTolerance), + VolumeFlowUnit.CentiliterPerDay => (CentilitersPerDayInOneCubicMeterPerSecond, CentilitersPerDayTolerance), + VolumeFlowUnit.CentiliterPerHour => (CentilitersPerHourInOneCubicMeterPerSecond, CentilitersPerHourTolerance), + VolumeFlowUnit.CentiliterPerMinute => (CentilitersPerMinuteInOneCubicMeterPerSecond, CentilitersPerMinuteTolerance), + VolumeFlowUnit.CentiliterPerSecond => (CentilitersPerSecondInOneCubicMeterPerSecond, CentilitersPerSecondTolerance), + VolumeFlowUnit.CubicCentimeterPerMinute => (CubicCentimetersPerMinuteInOneCubicMeterPerSecond, CubicCentimetersPerMinuteTolerance), + VolumeFlowUnit.CubicDecimeterPerMinute => (CubicDecimetersPerMinuteInOneCubicMeterPerSecond, CubicDecimetersPerMinuteTolerance), + VolumeFlowUnit.CubicFootPerHour => (CubicFeetPerHourInOneCubicMeterPerSecond, CubicFeetPerHourTolerance), + VolumeFlowUnit.CubicFootPerMinute => (CubicFeetPerMinuteInOneCubicMeterPerSecond, CubicFeetPerMinuteTolerance), + VolumeFlowUnit.CubicFootPerSecond => (CubicFeetPerSecondInOneCubicMeterPerSecond, CubicFeetPerSecondTolerance), + VolumeFlowUnit.CubicMeterPerDay => (CubicMetersPerDayInOneCubicMeterPerSecond, CubicMetersPerDayTolerance), + VolumeFlowUnit.CubicMeterPerHour => (CubicMetersPerHourInOneCubicMeterPerSecond, CubicMetersPerHourTolerance), + VolumeFlowUnit.CubicMeterPerMinute => (CubicMetersPerMinuteInOneCubicMeterPerSecond, CubicMetersPerMinuteTolerance), + VolumeFlowUnit.CubicMeterPerSecond => (CubicMetersPerSecondInOneCubicMeterPerSecond, CubicMetersPerSecondTolerance), + VolumeFlowUnit.CubicMillimeterPerSecond => (CubicMillimetersPerSecondInOneCubicMeterPerSecond, CubicMillimetersPerSecondTolerance), + VolumeFlowUnit.CubicYardPerDay => (CubicYardsPerDayInOneCubicMeterPerSecond, CubicYardsPerDayTolerance), + VolumeFlowUnit.CubicYardPerHour => (CubicYardsPerHourInOneCubicMeterPerSecond, CubicYardsPerHourTolerance), + VolumeFlowUnit.CubicYardPerMinute => (CubicYardsPerMinuteInOneCubicMeterPerSecond, CubicYardsPerMinuteTolerance), + VolumeFlowUnit.CubicYardPerSecond => (CubicYardsPerSecondInOneCubicMeterPerSecond, CubicYardsPerSecondTolerance), + VolumeFlowUnit.DeciliterPerDay => (DecilitersPerDayInOneCubicMeterPerSecond, DecilitersPerDayTolerance), + VolumeFlowUnit.DeciliterPerHour => (DecilitersPerHourInOneCubicMeterPerSecond, DecilitersPerHourTolerance), + VolumeFlowUnit.DeciliterPerMinute => (DecilitersPerMinuteInOneCubicMeterPerSecond, DecilitersPerMinuteTolerance), + VolumeFlowUnit.DeciliterPerSecond => (DecilitersPerSecondInOneCubicMeterPerSecond, DecilitersPerSecondTolerance), + VolumeFlowUnit.KiloliterPerDay => (KilolitersPerDayInOneCubicMeterPerSecond, KilolitersPerDayTolerance), + VolumeFlowUnit.KiloliterPerHour => (KilolitersPerHourInOneCubicMeterPerSecond, KilolitersPerHourTolerance), + VolumeFlowUnit.KiloliterPerMinute => (KilolitersPerMinuteInOneCubicMeterPerSecond, KilolitersPerMinuteTolerance), + VolumeFlowUnit.KiloliterPerSecond => (KilolitersPerSecondInOneCubicMeterPerSecond, KilolitersPerSecondTolerance), + VolumeFlowUnit.KilousGallonPerMinute => (KilousGallonsPerMinuteInOneCubicMeterPerSecond, KilousGallonsPerMinuteTolerance), + VolumeFlowUnit.LiterPerDay => (LitersPerDayInOneCubicMeterPerSecond, LitersPerDayTolerance), + VolumeFlowUnit.LiterPerHour => (LitersPerHourInOneCubicMeterPerSecond, LitersPerHourTolerance), + VolumeFlowUnit.LiterPerMinute => (LitersPerMinuteInOneCubicMeterPerSecond, LitersPerMinuteTolerance), + VolumeFlowUnit.LiterPerSecond => (LitersPerSecondInOneCubicMeterPerSecond, LitersPerSecondTolerance), + VolumeFlowUnit.MegaliterPerDay => (MegalitersPerDayInOneCubicMeterPerSecond, MegalitersPerDayTolerance), + VolumeFlowUnit.MegaukGallonPerSecond => (MegaukGallonsPerSecondInOneCubicMeterPerSecond, MegaukGallonsPerSecondTolerance), + VolumeFlowUnit.MicroliterPerDay => (MicrolitersPerDayInOneCubicMeterPerSecond, MicrolitersPerDayTolerance), + VolumeFlowUnit.MicroliterPerHour => (MicrolitersPerHourInOneCubicMeterPerSecond, MicrolitersPerHourTolerance), + VolumeFlowUnit.MicroliterPerMinute => (MicrolitersPerMinuteInOneCubicMeterPerSecond, MicrolitersPerMinuteTolerance), + VolumeFlowUnit.MicroliterPerSecond => (MicrolitersPerSecondInOneCubicMeterPerSecond, MicrolitersPerSecondTolerance), + VolumeFlowUnit.MilliliterPerDay => (MillilitersPerDayInOneCubicMeterPerSecond, MillilitersPerDayTolerance), + VolumeFlowUnit.MilliliterPerHour => (MillilitersPerHourInOneCubicMeterPerSecond, MillilitersPerHourTolerance), + VolumeFlowUnit.MilliliterPerMinute => (MillilitersPerMinuteInOneCubicMeterPerSecond, MillilitersPerMinuteTolerance), + VolumeFlowUnit.MilliliterPerSecond => (MillilitersPerSecondInOneCubicMeterPerSecond, MillilitersPerSecondTolerance), + VolumeFlowUnit.MillionUsGallonsPerDay => (MillionUsGallonsPerDayInOneCubicMeterPerSecond, MillionUsGallonsPerDayTolerance), + VolumeFlowUnit.NanoliterPerDay => (NanolitersPerDayInOneCubicMeterPerSecond, NanolitersPerDayTolerance), + VolumeFlowUnit.NanoliterPerHour => (NanolitersPerHourInOneCubicMeterPerSecond, NanolitersPerHourTolerance), + VolumeFlowUnit.NanoliterPerMinute => (NanolitersPerMinuteInOneCubicMeterPerSecond, NanolitersPerMinuteTolerance), + VolumeFlowUnit.NanoliterPerSecond => (NanolitersPerSecondInOneCubicMeterPerSecond, NanolitersPerSecondTolerance), + VolumeFlowUnit.OilBarrelPerDay => (OilBarrelsPerDayInOneCubicMeterPerSecond, OilBarrelsPerDayTolerance), + VolumeFlowUnit.OilBarrelPerHour => (OilBarrelsPerHourInOneCubicMeterPerSecond, OilBarrelsPerHourTolerance), + VolumeFlowUnit.OilBarrelPerMinute => (OilBarrelsPerMinuteInOneCubicMeterPerSecond, OilBarrelsPerMinuteTolerance), + VolumeFlowUnit.OilBarrelPerSecond => (OilBarrelsPerSecondInOneCubicMeterPerSecond, OilBarrelsPerSecondTolerance), + VolumeFlowUnit.UkGallonPerDay => (UkGallonsPerDayInOneCubicMeterPerSecond, UkGallonsPerDayTolerance), + VolumeFlowUnit.UkGallonPerHour => (UkGallonsPerHourInOneCubicMeterPerSecond, UkGallonsPerHourTolerance), + VolumeFlowUnit.UkGallonPerMinute => (UkGallonsPerMinuteInOneCubicMeterPerSecond, UkGallonsPerMinuteTolerance), + VolumeFlowUnit.UkGallonPerSecond => (UkGallonsPerSecondInOneCubicMeterPerSecond, UkGallonsPerSecondTolerance), + VolumeFlowUnit.UsGallonPerDay => (UsGallonsPerDayInOneCubicMeterPerSecond, UsGallonsPerDayTolerance), + VolumeFlowUnit.UsGallonPerHour => (UsGallonsPerHourInOneCubicMeterPerSecond, UsGallonsPerHourTolerance), + VolumeFlowUnit.UsGallonPerMinute => (UsGallonsPerMinuteInOneCubicMeterPerSecond, UsGallonsPerMinuteTolerance), + VolumeFlowUnit.UsGallonPerSecond => (UsGallonsPerSecondInOneCubicMeterPerSecond, UsGallonsPerSecondTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { VolumeFlowUnit.AcreFootPerDay }, + new object[] { VolumeFlowUnit.AcreFootPerHour }, + new object[] { VolumeFlowUnit.AcreFootPerMinute }, + new object[] { VolumeFlowUnit.AcreFootPerSecond }, + new object[] { VolumeFlowUnit.CentiliterPerDay }, + new object[] { VolumeFlowUnit.CentiliterPerHour }, + new object[] { VolumeFlowUnit.CentiliterPerMinute }, + new object[] { VolumeFlowUnit.CentiliterPerSecond }, + new object[] { VolumeFlowUnit.CubicCentimeterPerMinute }, + new object[] { VolumeFlowUnit.CubicDecimeterPerMinute }, + new object[] { VolumeFlowUnit.CubicFootPerHour }, + new object[] { VolumeFlowUnit.CubicFootPerMinute }, + new object[] { VolumeFlowUnit.CubicFootPerSecond }, + new object[] { VolumeFlowUnit.CubicMeterPerDay }, + new object[] { VolumeFlowUnit.CubicMeterPerHour }, + new object[] { VolumeFlowUnit.CubicMeterPerMinute }, + new object[] { VolumeFlowUnit.CubicMeterPerSecond }, + new object[] { VolumeFlowUnit.CubicMillimeterPerSecond }, + new object[] { VolumeFlowUnit.CubicYardPerDay }, + new object[] { VolumeFlowUnit.CubicYardPerHour }, + new object[] { VolumeFlowUnit.CubicYardPerMinute }, + new object[] { VolumeFlowUnit.CubicYardPerSecond }, + new object[] { VolumeFlowUnit.DeciliterPerDay }, + new object[] { VolumeFlowUnit.DeciliterPerHour }, + new object[] { VolumeFlowUnit.DeciliterPerMinute }, + new object[] { VolumeFlowUnit.DeciliterPerSecond }, + new object[] { VolumeFlowUnit.KiloliterPerDay }, + new object[] { VolumeFlowUnit.KiloliterPerHour }, + new object[] { VolumeFlowUnit.KiloliterPerMinute }, + new object[] { VolumeFlowUnit.KiloliterPerSecond }, + new object[] { VolumeFlowUnit.KilousGallonPerMinute }, + new object[] { VolumeFlowUnit.LiterPerDay }, + new object[] { VolumeFlowUnit.LiterPerHour }, + new object[] { VolumeFlowUnit.LiterPerMinute }, + new object[] { VolumeFlowUnit.LiterPerSecond }, + new object[] { VolumeFlowUnit.MegaliterPerDay }, + new object[] { VolumeFlowUnit.MegaukGallonPerSecond }, + new object[] { VolumeFlowUnit.MicroliterPerDay }, + new object[] { VolumeFlowUnit.MicroliterPerHour }, + new object[] { VolumeFlowUnit.MicroliterPerMinute }, + new object[] { VolumeFlowUnit.MicroliterPerSecond }, + new object[] { VolumeFlowUnit.MilliliterPerDay }, + new object[] { VolumeFlowUnit.MilliliterPerHour }, + new object[] { VolumeFlowUnit.MilliliterPerMinute }, + new object[] { VolumeFlowUnit.MilliliterPerSecond }, + new object[] { VolumeFlowUnit.MillionUsGallonsPerDay }, + new object[] { VolumeFlowUnit.NanoliterPerDay }, + new object[] { VolumeFlowUnit.NanoliterPerHour }, + new object[] { VolumeFlowUnit.NanoliterPerMinute }, + new object[] { VolumeFlowUnit.NanoliterPerSecond }, + new object[] { VolumeFlowUnit.OilBarrelPerDay }, + new object[] { VolumeFlowUnit.OilBarrelPerHour }, + new object[] { VolumeFlowUnit.OilBarrelPerMinute }, + new object[] { VolumeFlowUnit.OilBarrelPerSecond }, + new object[] { VolumeFlowUnit.UkGallonPerDay }, + new object[] { VolumeFlowUnit.UkGallonPerHour }, + new object[] { VolumeFlowUnit.UkGallonPerMinute }, + new object[] { VolumeFlowUnit.UkGallonPerSecond }, + new object[] { VolumeFlowUnit.UsGallonPerDay }, + new object[] { VolumeFlowUnit.UsGallonPerHour }, + new object[] { VolumeFlowUnit.UsGallonPerMinute }, + new object[] { VolumeFlowUnit.UsGallonPerSecond }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -652,265 +789,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(VolumeFlowUnit unit) { - var cubicmeterpersecond = VolumeFlow.FromCubicMetersPerSecond(1); - - var acrefootperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.AcreFootPerDay); - AssertEx.EqualTolerance(AcreFeetPerDayInOneCubicMeterPerSecond, (double)acrefootperdayQuantity.Value, AcreFeetPerDayTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerDay, acrefootperdayQuantity.Unit); - - var acrefootperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.AcreFootPerHour); - AssertEx.EqualTolerance(AcreFeetPerHourInOneCubicMeterPerSecond, (double)acrefootperhourQuantity.Value, AcreFeetPerHourTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerHour, acrefootperhourQuantity.Unit); - - var acrefootperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.AcreFootPerMinute); - AssertEx.EqualTolerance(AcreFeetPerMinuteInOneCubicMeterPerSecond, (double)acrefootperminuteQuantity.Value, AcreFeetPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerMinute, acrefootperminuteQuantity.Unit); - - var acrefootpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.AcreFootPerSecond); - AssertEx.EqualTolerance(AcreFeetPerSecondInOneCubicMeterPerSecond, (double)acrefootpersecondQuantity.Value, AcreFeetPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerSecond, acrefootpersecondQuantity.Unit); - - var centiliterperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CentiliterPerDay); - AssertEx.EqualTolerance(CentilitersPerDayInOneCubicMeterPerSecond, (double)centiliterperdayQuantity.Value, CentilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerDay, centiliterperdayQuantity.Unit); - - var centiliterperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CentiliterPerHour); - AssertEx.EqualTolerance(CentilitersPerHourInOneCubicMeterPerSecond, (double)centiliterperhourQuantity.Value, CentilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerHour, centiliterperhourQuantity.Unit); - - var centiliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CentiliterPerMinute); - AssertEx.EqualTolerance(CentilitersPerMinuteInOneCubicMeterPerSecond, (double)centiliterperminuteQuantity.Value, CentilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerMinute, centiliterperminuteQuantity.Unit); - - var centiliterpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CentiliterPerSecond); - AssertEx.EqualTolerance(CentilitersPerSecondInOneCubicMeterPerSecond, (double)centiliterpersecondQuantity.Value, CentilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerSecond, centiliterpersecondQuantity.Unit); - - var cubiccentimeterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicCentimeterPerMinute); - AssertEx.EqualTolerance(CubicCentimetersPerMinuteInOneCubicMeterPerSecond, (double)cubiccentimeterperminuteQuantity.Value, CubicCentimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicCentimeterPerMinute, cubiccentimeterperminuteQuantity.Unit); - - var cubicdecimeterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicDecimeterPerMinute); - AssertEx.EqualTolerance(CubicDecimetersPerMinuteInOneCubicMeterPerSecond, (double)cubicdecimeterperminuteQuantity.Value, CubicDecimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicDecimeterPerMinute, cubicdecimeterperminuteQuantity.Unit); - - var cubicfootperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicFootPerHour); - AssertEx.EqualTolerance(CubicFeetPerHourInOneCubicMeterPerSecond, (double)cubicfootperhourQuantity.Value, CubicFeetPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerHour, cubicfootperhourQuantity.Unit); - - var cubicfootperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicFootPerMinute); - AssertEx.EqualTolerance(CubicFeetPerMinuteInOneCubicMeterPerSecond, (double)cubicfootperminuteQuantity.Value, CubicFeetPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerMinute, cubicfootperminuteQuantity.Unit); - - var cubicfootpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicFootPerSecond); - AssertEx.EqualTolerance(CubicFeetPerSecondInOneCubicMeterPerSecond, (double)cubicfootpersecondQuantity.Value, CubicFeetPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerSecond, cubicfootpersecondQuantity.Unit); - - var cubicmeterperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicMeterPerDay); - AssertEx.EqualTolerance(CubicMetersPerDayInOneCubicMeterPerSecond, (double)cubicmeterperdayQuantity.Value, CubicMetersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerDay, cubicmeterperdayQuantity.Unit); - - var cubicmeterperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicMeterPerHour); - AssertEx.EqualTolerance(CubicMetersPerHourInOneCubicMeterPerSecond, (double)cubicmeterperhourQuantity.Value, CubicMetersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerHour, cubicmeterperhourQuantity.Unit); - - var cubicmeterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicMeterPerMinute); - AssertEx.EqualTolerance(CubicMetersPerMinuteInOneCubicMeterPerSecond, (double)cubicmeterperminuteQuantity.Value, CubicMetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerMinute, cubicmeterperminuteQuantity.Unit); - - var cubicmeterpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicMeterPerSecond); - AssertEx.EqualTolerance(CubicMetersPerSecondInOneCubicMeterPerSecond, (double)cubicmeterpersecondQuantity.Value, CubicMetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerSecond, cubicmeterpersecondQuantity.Unit); - - var cubicmillimeterpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicMillimeterPerSecond); - AssertEx.EqualTolerance(CubicMillimetersPerSecondInOneCubicMeterPerSecond, (double)cubicmillimeterpersecondQuantity.Value, CubicMillimetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMillimeterPerSecond, cubicmillimeterpersecondQuantity.Unit); - - var cubicyardperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicYardPerDay); - AssertEx.EqualTolerance(CubicYardsPerDayInOneCubicMeterPerSecond, (double)cubicyardperdayQuantity.Value, CubicYardsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerDay, cubicyardperdayQuantity.Unit); - - var cubicyardperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicYardPerHour); - AssertEx.EqualTolerance(CubicYardsPerHourInOneCubicMeterPerSecond, (double)cubicyardperhourQuantity.Value, CubicYardsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerHour, cubicyardperhourQuantity.Unit); - - var cubicyardperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicYardPerMinute); - AssertEx.EqualTolerance(CubicYardsPerMinuteInOneCubicMeterPerSecond, (double)cubicyardperminuteQuantity.Value, CubicYardsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerMinute, cubicyardperminuteQuantity.Unit); - - var cubicyardpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicYardPerSecond); - AssertEx.EqualTolerance(CubicYardsPerSecondInOneCubicMeterPerSecond, (double)cubicyardpersecondQuantity.Value, CubicYardsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerSecond, cubicyardpersecondQuantity.Unit); - - var deciliterperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.DeciliterPerDay); - AssertEx.EqualTolerance(DecilitersPerDayInOneCubicMeterPerSecond, (double)deciliterperdayQuantity.Value, DecilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerDay, deciliterperdayQuantity.Unit); - - var deciliterperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.DeciliterPerHour); - AssertEx.EqualTolerance(DecilitersPerHourInOneCubicMeterPerSecond, (double)deciliterperhourQuantity.Value, DecilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerHour, deciliterperhourQuantity.Unit); - - var deciliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.DeciliterPerMinute); - AssertEx.EqualTolerance(DecilitersPerMinuteInOneCubicMeterPerSecond, (double)deciliterperminuteQuantity.Value, DecilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerMinute, deciliterperminuteQuantity.Unit); - - var deciliterpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.DeciliterPerSecond); - AssertEx.EqualTolerance(DecilitersPerSecondInOneCubicMeterPerSecond, (double)deciliterpersecondQuantity.Value, DecilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerSecond, deciliterpersecondQuantity.Unit); - - var kiloliterperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.KiloliterPerDay); - AssertEx.EqualTolerance(KilolitersPerDayInOneCubicMeterPerSecond, (double)kiloliterperdayQuantity.Value, KilolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerDay, kiloliterperdayQuantity.Unit); - - var kiloliterperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.KiloliterPerHour); - AssertEx.EqualTolerance(KilolitersPerHourInOneCubicMeterPerSecond, (double)kiloliterperhourQuantity.Value, KilolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerHour, kiloliterperhourQuantity.Unit); - - var kiloliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.KiloliterPerMinute); - AssertEx.EqualTolerance(KilolitersPerMinuteInOneCubicMeterPerSecond, (double)kiloliterperminuteQuantity.Value, KilolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerMinute, kiloliterperminuteQuantity.Unit); + var inBaseUnits = VolumeFlow.From(1.0, VolumeFlow.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kiloliterpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.KiloliterPerSecond); - AssertEx.EqualTolerance(KilolitersPerSecondInOneCubicMeterPerSecond, (double)kiloliterpersecondQuantity.Value, KilolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerSecond, kiloliterpersecondQuantity.Unit); - - var kilousgallonperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.KilousGallonPerMinute); - AssertEx.EqualTolerance(KilousGallonsPerMinuteInOneCubicMeterPerSecond, (double)kilousgallonperminuteQuantity.Value, KilousGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KilousGallonPerMinute, kilousgallonperminuteQuantity.Unit); - - var literperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LiterPerDay); - AssertEx.EqualTolerance(LitersPerDayInOneCubicMeterPerSecond, (double)literperdayQuantity.Value, LitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerDay, literperdayQuantity.Unit); - - var literperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LiterPerHour); - AssertEx.EqualTolerance(LitersPerHourInOneCubicMeterPerSecond, (double)literperhourQuantity.Value, LitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerHour, literperhourQuantity.Unit); - - var literperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LiterPerMinute); - AssertEx.EqualTolerance(LitersPerMinuteInOneCubicMeterPerSecond, (double)literperminuteQuantity.Value, LitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerMinute, literperminuteQuantity.Unit); - - var literpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LiterPerSecond); - AssertEx.EqualTolerance(LitersPerSecondInOneCubicMeterPerSecond, (double)literpersecondQuantity.Value, LitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerSecond, literpersecondQuantity.Unit); - - var megaliterperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MegaliterPerDay); - AssertEx.EqualTolerance(MegalitersPerDayInOneCubicMeterPerSecond, (double)megaliterperdayQuantity.Value, MegalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerDay, megaliterperdayQuantity.Unit); - - var megaukgallonpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MegaukGallonPerSecond); - AssertEx.EqualTolerance(MegaukGallonsPerSecondInOneCubicMeterPerSecond, (double)megaukgallonpersecondQuantity.Value, MegaukGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MegaukGallonPerSecond, megaukgallonpersecondQuantity.Unit); - - var microliterperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MicroliterPerDay); - AssertEx.EqualTolerance(MicrolitersPerDayInOneCubicMeterPerSecond, (double)microliterperdayQuantity.Value, MicrolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerDay, microliterperdayQuantity.Unit); - - var microliterperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MicroliterPerHour); - AssertEx.EqualTolerance(MicrolitersPerHourInOneCubicMeterPerSecond, (double)microliterperhourQuantity.Value, MicrolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerHour, microliterperhourQuantity.Unit); - - var microliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MicroliterPerMinute); - AssertEx.EqualTolerance(MicrolitersPerMinuteInOneCubicMeterPerSecond, (double)microliterperminuteQuantity.Value, MicrolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, microliterperminuteQuantity.Unit); - - var microliterpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MicroliterPerSecond); - AssertEx.EqualTolerance(MicrolitersPerSecondInOneCubicMeterPerSecond, (double)microliterpersecondQuantity.Value, MicrolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerSecond, microliterpersecondQuantity.Unit); - - var milliliterperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MilliliterPerDay); - AssertEx.EqualTolerance(MillilitersPerDayInOneCubicMeterPerSecond, (double)milliliterperdayQuantity.Value, MillilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerDay, milliliterperdayQuantity.Unit); - - var milliliterperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MilliliterPerHour); - AssertEx.EqualTolerance(MillilitersPerHourInOneCubicMeterPerSecond, (double)milliliterperhourQuantity.Value, MillilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerHour, milliliterperhourQuantity.Unit); - - var milliliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MilliliterPerMinute); - AssertEx.EqualTolerance(MillilitersPerMinuteInOneCubicMeterPerSecond, (double)milliliterperminuteQuantity.Value, MillilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerMinute, milliliterperminuteQuantity.Unit); - - var milliliterpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MilliliterPerSecond); - AssertEx.EqualTolerance(MillilitersPerSecondInOneCubicMeterPerSecond, (double)milliliterpersecondQuantity.Value, MillilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerSecond, milliliterpersecondQuantity.Unit); - - var millionusgallonsperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MillionUsGallonsPerDay); - AssertEx.EqualTolerance(MillionUsGallonsPerDayInOneCubicMeterPerSecond, (double)millionusgallonsperdayQuantity.Value, MillionUsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MillionUsGallonsPerDay, millionusgallonsperdayQuantity.Unit); - - var nanoliterperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.NanoliterPerDay); - AssertEx.EqualTolerance(NanolitersPerDayInOneCubicMeterPerSecond, (double)nanoliterperdayQuantity.Value, NanolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerDay, nanoliterperdayQuantity.Unit); - - var nanoliterperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.NanoliterPerHour); - AssertEx.EqualTolerance(NanolitersPerHourInOneCubicMeterPerSecond, (double)nanoliterperhourQuantity.Value, NanolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerHour, nanoliterperhourQuantity.Unit); - - var nanoliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.NanoliterPerMinute); - AssertEx.EqualTolerance(NanolitersPerMinuteInOneCubicMeterPerSecond, (double)nanoliterperminuteQuantity.Value, NanolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerMinute, nanoliterperminuteQuantity.Unit); - - var nanoliterpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.NanoliterPerSecond); - AssertEx.EqualTolerance(NanolitersPerSecondInOneCubicMeterPerSecond, (double)nanoliterpersecondQuantity.Value, NanolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerSecond, nanoliterpersecondQuantity.Unit); - - var oilbarrelperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelPerDay); - AssertEx.EqualTolerance(OilBarrelsPerDayInOneCubicMeterPerSecond, (double)oilbarrelperdayQuantity.Value, OilBarrelsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerDay, oilbarrelperdayQuantity.Unit); - - var oilbarrelperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelPerHour); - AssertEx.EqualTolerance(OilBarrelsPerHourInOneCubicMeterPerSecond, (double)oilbarrelperhourQuantity.Value, OilBarrelsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerHour, oilbarrelperhourQuantity.Unit); - - var oilbarrelperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelPerMinute); - AssertEx.EqualTolerance(OilBarrelsPerMinuteInOneCubicMeterPerSecond, (double)oilbarrelperminuteQuantity.Value, OilBarrelsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerMinute, oilbarrelperminuteQuantity.Unit); - - var oilbarrelpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelPerSecond); - AssertEx.EqualTolerance(OilBarrelsPerSecondInOneCubicMeterPerSecond, (double)oilbarrelpersecondQuantity.Value, OilBarrelsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerSecond, oilbarrelpersecondQuantity.Unit); - - var ukgallonperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UkGallonPerDay); - AssertEx.EqualTolerance(UkGallonsPerDayInOneCubicMeterPerSecond, (double)ukgallonperdayQuantity.Value, UkGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerDay, ukgallonperdayQuantity.Unit); - - var ukgallonperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UkGallonPerHour); - AssertEx.EqualTolerance(UkGallonsPerHourInOneCubicMeterPerSecond, (double)ukgallonperhourQuantity.Value, UkGallonsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerHour, ukgallonperhourQuantity.Unit); - - var ukgallonperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UkGallonPerMinute); - AssertEx.EqualTolerance(UkGallonsPerMinuteInOneCubicMeterPerSecond, (double)ukgallonperminuteQuantity.Value, UkGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerMinute, ukgallonperminuteQuantity.Unit); - - var ukgallonpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UkGallonPerSecond); - AssertEx.EqualTolerance(UkGallonsPerSecondInOneCubicMeterPerSecond, (double)ukgallonpersecondQuantity.Value, UkGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerSecond, ukgallonpersecondQuantity.Unit); - - var usgallonperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonPerDay); - AssertEx.EqualTolerance(UsGallonsPerDayInOneCubicMeterPerSecond, (double)usgallonperdayQuantity.Value, UsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerDay, usgallonperdayQuantity.Unit); - - var usgallonperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonPerHour); - AssertEx.EqualTolerance(UsGallonsPerHourInOneCubicMeterPerSecond, (double)usgallonperhourQuantity.Value, UsGallonsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerHour, usgallonperhourQuantity.Unit); - - var usgallonperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonPerMinute); - AssertEx.EqualTolerance(UsGallonsPerMinuteInOneCubicMeterPerSecond, (double)usgallonperminuteQuantity.Value, UsGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerMinute, usgallonperminuteQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var usgallonpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonPerSecond); - AssertEx.EqualTolerance(UsGallonsPerSecondInOneCubicMeterPerSecond, (double)usgallonpersecondQuantity.Value, UsGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerSecond, usgallonpersecondQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(VolumeFlowUnit unit) + { + var quantity = VolumeFlow.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeFlowUnit unit) { - var quantityInBaseUnit = VolumeFlow.FromCubicMetersPerSecond(1).ToBaseUnit(); - Assert.Equal(VolumeFlow.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = VolumeFlow.Units.FirstOrDefault(u => u != VolumeFlow.BaseUnit && u != VolumeFlowUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == VolumeFlowUnit.Undefined) + fromUnit = VolumeFlow.BaseUnit; + + var quantity = VolumeFlow.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs index ce74461e4f..99b3b19301 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -55,6 +56,32 @@ public abstract partial class VolumePerLengthTestsBase : QuantityTestsBase protected virtual double OilBarrelsPerFootTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumePerLengthUnit unit) + { + return unit switch + { + VolumePerLengthUnit.CubicMeterPerMeter => (CubicMetersPerMeterInOneCubicMeterPerMeter, CubicMetersPerMeterTolerance), + VolumePerLengthUnit.CubicYardPerFoot => (CubicYardsPerFootInOneCubicMeterPerMeter, CubicYardsPerFootTolerance), + VolumePerLengthUnit.CubicYardPerUsSurveyFoot => (CubicYardsPerUsSurveyFootInOneCubicMeterPerMeter, CubicYardsPerUsSurveyFootTolerance), + VolumePerLengthUnit.LiterPerKilometer => (LitersPerKilometerInOneCubicMeterPerMeter, LitersPerKilometerTolerance), + VolumePerLengthUnit.LiterPerMeter => (LitersPerMeterInOneCubicMeterPerMeter, LitersPerMeterTolerance), + VolumePerLengthUnit.LiterPerMillimeter => (LitersPerMillimeterInOneCubicMeterPerMeter, LitersPerMillimeterTolerance), + VolumePerLengthUnit.OilBarrelPerFoot => (OilBarrelsPerFootInOneCubicMeterPerMeter, OilBarrelsPerFootTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { VolumePerLengthUnit.CubicMeterPerMeter }, + new object[] { VolumePerLengthUnit.CubicYardPerFoot }, + new object[] { VolumePerLengthUnit.CubicYardPerUsSurveyFoot }, + new object[] { VolumePerLengthUnit.LiterPerKilometer }, + new object[] { VolumePerLengthUnit.LiterPerMeter }, + new object[] { VolumePerLengthUnit.LiterPerMillimeter }, + new object[] { VolumePerLengthUnit.OilBarrelPerFoot }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -212,45 +239,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(VolumePerLengthUnit unit) { - var cubicmeterpermeter = VolumePerLength.FromCubicMetersPerMeter(1); - - var cubicmeterpermeterQuantity = cubicmeterpermeter.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter); - AssertEx.EqualTolerance(CubicMetersPerMeterInOneCubicMeterPerMeter, (double)cubicmeterpermeterQuantity.Value, CubicMetersPerMeterTolerance); - Assert.Equal(VolumePerLengthUnit.CubicMeterPerMeter, cubicmeterpermeterQuantity.Unit); - - var cubicyardperfootQuantity = cubicmeterpermeter.ToUnit(VolumePerLengthUnit.CubicYardPerFoot); - AssertEx.EqualTolerance(CubicYardsPerFootInOneCubicMeterPerMeter, (double)cubicyardperfootQuantity.Value, CubicYardsPerFootTolerance); - Assert.Equal(VolumePerLengthUnit.CubicYardPerFoot, cubicyardperfootQuantity.Unit); + var inBaseUnits = VolumePerLength.From(1.0, VolumePerLength.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var cubicyardperussurveyfootQuantity = cubicmeterpermeter.ToUnit(VolumePerLengthUnit.CubicYardPerUsSurveyFoot); - AssertEx.EqualTolerance(CubicYardsPerUsSurveyFootInOneCubicMeterPerMeter, (double)cubicyardperussurveyfootQuantity.Value, CubicYardsPerUsSurveyFootTolerance); - Assert.Equal(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, cubicyardperussurveyfootQuantity.Unit); - - var literperkilometerQuantity = cubicmeterpermeter.ToUnit(VolumePerLengthUnit.LiterPerKilometer); - AssertEx.EqualTolerance(LitersPerKilometerInOneCubicMeterPerMeter, (double)literperkilometerQuantity.Value, LitersPerKilometerTolerance); - Assert.Equal(VolumePerLengthUnit.LiterPerKilometer, literperkilometerQuantity.Unit); - - var literpermeterQuantity = cubicmeterpermeter.ToUnit(VolumePerLengthUnit.LiterPerMeter); - AssertEx.EqualTolerance(LitersPerMeterInOneCubicMeterPerMeter, (double)literpermeterQuantity.Value, LitersPerMeterTolerance); - Assert.Equal(VolumePerLengthUnit.LiterPerMeter, literpermeterQuantity.Unit); - - var literpermillimeterQuantity = cubicmeterpermeter.ToUnit(VolumePerLengthUnit.LiterPerMillimeter); - AssertEx.EqualTolerance(LitersPerMillimeterInOneCubicMeterPerMeter, (double)literpermillimeterQuantity.Value, LitersPerMillimeterTolerance); - Assert.Equal(VolumePerLengthUnit.LiterPerMillimeter, literpermillimeterQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var oilbarrelperfootQuantity = cubicmeterpermeter.ToUnit(VolumePerLengthUnit.OilBarrelPerFoot); - AssertEx.EqualTolerance(OilBarrelsPerFootInOneCubicMeterPerMeter, (double)oilbarrelperfootQuantity.Value, OilBarrelsPerFootTolerance); - Assert.Equal(VolumePerLengthUnit.OilBarrelPerFoot, oilbarrelperfootQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(VolumePerLengthUnit unit) + { + var quantity = VolumePerLength.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumePerLengthUnit unit) { - var quantityInBaseUnit = VolumePerLength.FromCubicMetersPerMeter(1).ToBaseUnit(); - Assert.Equal(VolumePerLength.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = VolumePerLength.Units.FirstOrDefault(u => u != VolumePerLength.BaseUnit && u != VolumePerLengthUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == VolumePerLengthUnit.Undefined) + fromUnit = VolumePerLength.BaseUnit; + + var quantity = VolumePerLength.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs index 7012708187..53acb7dd64 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -143,6 +144,120 @@ public abstract partial class VolumeTestsBase : QuantityTestsBase protected virtual double UsTeaspoonsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumeUnit unit) + { + return unit switch + { + VolumeUnit.AcreFoot => (AcreFeetInOneCubicMeter, AcreFeetTolerance), + VolumeUnit.AuTablespoon => (AuTablespoonsInOneCubicMeter, AuTablespoonsTolerance), + VolumeUnit.BoardFoot => (BoardFeetInOneCubicMeter, BoardFeetTolerance), + VolumeUnit.Centiliter => (CentilitersInOneCubicMeter, CentilitersTolerance), + VolumeUnit.CubicCentimeter => (CubicCentimetersInOneCubicMeter, CubicCentimetersTolerance), + VolumeUnit.CubicDecimeter => (CubicDecimetersInOneCubicMeter, CubicDecimetersTolerance), + VolumeUnit.CubicFoot => (CubicFeetInOneCubicMeter, CubicFeetTolerance), + VolumeUnit.CubicHectometer => (CubicHectometersInOneCubicMeter, CubicHectometersTolerance), + VolumeUnit.CubicInch => (CubicInchesInOneCubicMeter, CubicInchesTolerance), + VolumeUnit.CubicKilometer => (CubicKilometersInOneCubicMeter, CubicKilometersTolerance), + VolumeUnit.CubicMeter => (CubicMetersInOneCubicMeter, CubicMetersTolerance), + VolumeUnit.CubicMicrometer => (CubicMicrometersInOneCubicMeter, CubicMicrometersTolerance), + VolumeUnit.CubicMile => (CubicMilesInOneCubicMeter, CubicMilesTolerance), + VolumeUnit.CubicMillimeter => (CubicMillimetersInOneCubicMeter, CubicMillimetersTolerance), + VolumeUnit.CubicYard => (CubicYardsInOneCubicMeter, CubicYardsTolerance), + VolumeUnit.DecausGallon => (DecausGallonsInOneCubicMeter, DecausGallonsTolerance), + VolumeUnit.Deciliter => (DecilitersInOneCubicMeter, DecilitersTolerance), + VolumeUnit.DeciusGallon => (DeciusGallonsInOneCubicMeter, DeciusGallonsTolerance), + VolumeUnit.HectocubicFoot => (HectocubicFeetInOneCubicMeter, HectocubicFeetTolerance), + VolumeUnit.HectocubicMeter => (HectocubicMetersInOneCubicMeter, HectocubicMetersTolerance), + VolumeUnit.Hectoliter => (HectolitersInOneCubicMeter, HectolitersTolerance), + VolumeUnit.HectousGallon => (HectousGallonsInOneCubicMeter, HectousGallonsTolerance), + VolumeUnit.ImperialBeerBarrel => (ImperialBeerBarrelsInOneCubicMeter, ImperialBeerBarrelsTolerance), + VolumeUnit.ImperialGallon => (ImperialGallonsInOneCubicMeter, ImperialGallonsTolerance), + VolumeUnit.ImperialOunce => (ImperialOuncesInOneCubicMeter, ImperialOuncesTolerance), + VolumeUnit.ImperialPint => (ImperialPintsInOneCubicMeter, ImperialPintsTolerance), + VolumeUnit.KilocubicFoot => (KilocubicFeetInOneCubicMeter, KilocubicFeetTolerance), + VolumeUnit.KilocubicMeter => (KilocubicMetersInOneCubicMeter, KilocubicMetersTolerance), + VolumeUnit.KiloimperialGallon => (KiloimperialGallonsInOneCubicMeter, KiloimperialGallonsTolerance), + VolumeUnit.Kiloliter => (KilolitersInOneCubicMeter, KilolitersTolerance), + VolumeUnit.KilousGallon => (KilousGallonsInOneCubicMeter, KilousGallonsTolerance), + VolumeUnit.Liter => (LitersInOneCubicMeter, LitersTolerance), + VolumeUnit.MegacubicFoot => (MegacubicFeetInOneCubicMeter, MegacubicFeetTolerance), + VolumeUnit.MegaimperialGallon => (MegaimperialGallonsInOneCubicMeter, MegaimperialGallonsTolerance), + VolumeUnit.Megaliter => (MegalitersInOneCubicMeter, MegalitersTolerance), + VolumeUnit.MegausGallon => (MegausGallonsInOneCubicMeter, MegausGallonsTolerance), + VolumeUnit.MetricCup => (MetricCupsInOneCubicMeter, MetricCupsTolerance), + VolumeUnit.MetricTeaspoon => (MetricTeaspoonsInOneCubicMeter, MetricTeaspoonsTolerance), + VolumeUnit.Microliter => (MicrolitersInOneCubicMeter, MicrolitersTolerance), + VolumeUnit.Milliliter => (MillilitersInOneCubicMeter, MillilitersTolerance), + VolumeUnit.OilBarrel => (OilBarrelsInOneCubicMeter, OilBarrelsTolerance), + VolumeUnit.UkTablespoon => (UkTablespoonsInOneCubicMeter, UkTablespoonsTolerance), + VolumeUnit.UsBeerBarrel => (UsBeerBarrelsInOneCubicMeter, UsBeerBarrelsTolerance), + VolumeUnit.UsCustomaryCup => (UsCustomaryCupsInOneCubicMeter, UsCustomaryCupsTolerance), + VolumeUnit.UsGallon => (UsGallonsInOneCubicMeter, UsGallonsTolerance), + VolumeUnit.UsLegalCup => (UsLegalCupsInOneCubicMeter, UsLegalCupsTolerance), + VolumeUnit.UsOunce => (UsOuncesInOneCubicMeter, UsOuncesTolerance), + VolumeUnit.UsPint => (UsPintsInOneCubicMeter, UsPintsTolerance), + VolumeUnit.UsQuart => (UsQuartsInOneCubicMeter, UsQuartsTolerance), + VolumeUnit.UsTablespoon => (UsTablespoonsInOneCubicMeter, UsTablespoonsTolerance), + VolumeUnit.UsTeaspoon => (UsTeaspoonsInOneCubicMeter, UsTeaspoonsTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { VolumeUnit.AcreFoot }, + new object[] { VolumeUnit.AuTablespoon }, + new object[] { VolumeUnit.BoardFoot }, + new object[] { VolumeUnit.Centiliter }, + new object[] { VolumeUnit.CubicCentimeter }, + new object[] { VolumeUnit.CubicDecimeter }, + new object[] { VolumeUnit.CubicFoot }, + new object[] { VolumeUnit.CubicHectometer }, + new object[] { VolumeUnit.CubicInch }, + new object[] { VolumeUnit.CubicKilometer }, + new object[] { VolumeUnit.CubicMeter }, + new object[] { VolumeUnit.CubicMicrometer }, + new object[] { VolumeUnit.CubicMile }, + new object[] { VolumeUnit.CubicMillimeter }, + new object[] { VolumeUnit.CubicYard }, + new object[] { VolumeUnit.DecausGallon }, + new object[] { VolumeUnit.Deciliter }, + new object[] { VolumeUnit.DeciusGallon }, + new object[] { VolumeUnit.HectocubicFoot }, + new object[] { VolumeUnit.HectocubicMeter }, + new object[] { VolumeUnit.Hectoliter }, + new object[] { VolumeUnit.HectousGallon }, + new object[] { VolumeUnit.ImperialBeerBarrel }, + new object[] { VolumeUnit.ImperialGallon }, + new object[] { VolumeUnit.ImperialOunce }, + new object[] { VolumeUnit.ImperialPint }, + new object[] { VolumeUnit.KilocubicFoot }, + new object[] { VolumeUnit.KilocubicMeter }, + new object[] { VolumeUnit.KiloimperialGallon }, + new object[] { VolumeUnit.Kiloliter }, + new object[] { VolumeUnit.KilousGallon }, + new object[] { VolumeUnit.Liter }, + new object[] { VolumeUnit.MegacubicFoot }, + new object[] { VolumeUnit.MegaimperialGallon }, + new object[] { VolumeUnit.Megaliter }, + new object[] { VolumeUnit.MegausGallon }, + new object[] { VolumeUnit.MetricCup }, + new object[] { VolumeUnit.MetricTeaspoon }, + new object[] { VolumeUnit.Microliter }, + new object[] { VolumeUnit.Milliliter }, + new object[] { VolumeUnit.OilBarrel }, + new object[] { VolumeUnit.UkTablespoon }, + new object[] { VolumeUnit.UsBeerBarrel }, + new object[] { VolumeUnit.UsCustomaryCup }, + new object[] { VolumeUnit.UsGallon }, + new object[] { VolumeUnit.UsLegalCup }, + new object[] { VolumeUnit.UsOunce }, + new object[] { VolumeUnit.UsPint }, + new object[] { VolumeUnit.UsQuart }, + new object[] { VolumeUnit.UsTablespoon }, + new object[] { VolumeUnit.UsTeaspoon }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -564,221 +679,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(VolumeUnit unit) { - var cubicmeter = Volume.FromCubicMeters(1); - - var acrefootQuantity = cubicmeter.ToUnit(VolumeUnit.AcreFoot); - AssertEx.EqualTolerance(AcreFeetInOneCubicMeter, (double)acrefootQuantity.Value, AcreFeetTolerance); - Assert.Equal(VolumeUnit.AcreFoot, acrefootQuantity.Unit); - - var autablespoonQuantity = cubicmeter.ToUnit(VolumeUnit.AuTablespoon); - AssertEx.EqualTolerance(AuTablespoonsInOneCubicMeter, (double)autablespoonQuantity.Value, AuTablespoonsTolerance); - Assert.Equal(VolumeUnit.AuTablespoon, autablespoonQuantity.Unit); - - var boardfootQuantity = cubicmeter.ToUnit(VolumeUnit.BoardFoot); - AssertEx.EqualTolerance(BoardFeetInOneCubicMeter, (double)boardfootQuantity.Value, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, boardfootQuantity.Unit); - - var centiliterQuantity = cubicmeter.ToUnit(VolumeUnit.Centiliter); - AssertEx.EqualTolerance(CentilitersInOneCubicMeter, (double)centiliterQuantity.Value, CentilitersTolerance); - Assert.Equal(VolumeUnit.Centiliter, centiliterQuantity.Unit); - - var cubiccentimeterQuantity = cubicmeter.ToUnit(VolumeUnit.CubicCentimeter); - AssertEx.EqualTolerance(CubicCentimetersInOneCubicMeter, (double)cubiccentimeterQuantity.Value, CubicCentimetersTolerance); - Assert.Equal(VolumeUnit.CubicCentimeter, cubiccentimeterQuantity.Unit); - - var cubicdecimeterQuantity = cubicmeter.ToUnit(VolumeUnit.CubicDecimeter); - AssertEx.EqualTolerance(CubicDecimetersInOneCubicMeter, (double)cubicdecimeterQuantity.Value, CubicDecimetersTolerance); - Assert.Equal(VolumeUnit.CubicDecimeter, cubicdecimeterQuantity.Unit); - - var cubicfootQuantity = cubicmeter.ToUnit(VolumeUnit.CubicFoot); - AssertEx.EqualTolerance(CubicFeetInOneCubicMeter, (double)cubicfootQuantity.Value, CubicFeetTolerance); - Assert.Equal(VolumeUnit.CubicFoot, cubicfootQuantity.Unit); - - var cubichectometerQuantity = cubicmeter.ToUnit(VolumeUnit.CubicHectometer); - AssertEx.EqualTolerance(CubicHectometersInOneCubicMeter, (double)cubichectometerQuantity.Value, CubicHectometersTolerance); - Assert.Equal(VolumeUnit.CubicHectometer, cubichectometerQuantity.Unit); - - var cubicinchQuantity = cubicmeter.ToUnit(VolumeUnit.CubicInch); - AssertEx.EqualTolerance(CubicInchesInOneCubicMeter, (double)cubicinchQuantity.Value, CubicInchesTolerance); - Assert.Equal(VolumeUnit.CubicInch, cubicinchQuantity.Unit); - - var cubickilometerQuantity = cubicmeter.ToUnit(VolumeUnit.CubicKilometer); - AssertEx.EqualTolerance(CubicKilometersInOneCubicMeter, (double)cubickilometerQuantity.Value, CubicKilometersTolerance); - Assert.Equal(VolumeUnit.CubicKilometer, cubickilometerQuantity.Unit); - - var cubicmeterQuantity = cubicmeter.ToUnit(VolumeUnit.CubicMeter); - AssertEx.EqualTolerance(CubicMetersInOneCubicMeter, (double)cubicmeterQuantity.Value, CubicMetersTolerance); - Assert.Equal(VolumeUnit.CubicMeter, cubicmeterQuantity.Unit); - - var cubicmicrometerQuantity = cubicmeter.ToUnit(VolumeUnit.CubicMicrometer); - AssertEx.EqualTolerance(CubicMicrometersInOneCubicMeter, (double)cubicmicrometerQuantity.Value, CubicMicrometersTolerance); - Assert.Equal(VolumeUnit.CubicMicrometer, cubicmicrometerQuantity.Unit); - - var cubicmileQuantity = cubicmeter.ToUnit(VolumeUnit.CubicMile); - AssertEx.EqualTolerance(CubicMilesInOneCubicMeter, (double)cubicmileQuantity.Value, CubicMilesTolerance); - Assert.Equal(VolumeUnit.CubicMile, cubicmileQuantity.Unit); - - var cubicmillimeterQuantity = cubicmeter.ToUnit(VolumeUnit.CubicMillimeter); - AssertEx.EqualTolerance(CubicMillimetersInOneCubicMeter, (double)cubicmillimeterQuantity.Value, CubicMillimetersTolerance); - Assert.Equal(VolumeUnit.CubicMillimeter, cubicmillimeterQuantity.Unit); - - var cubicyardQuantity = cubicmeter.ToUnit(VolumeUnit.CubicYard); - AssertEx.EqualTolerance(CubicYardsInOneCubicMeter, (double)cubicyardQuantity.Value, CubicYardsTolerance); - Assert.Equal(VolumeUnit.CubicYard, cubicyardQuantity.Unit); - - var decausgallonQuantity = cubicmeter.ToUnit(VolumeUnit.DecausGallon); - AssertEx.EqualTolerance(DecausGallonsInOneCubicMeter, (double)decausgallonQuantity.Value, DecausGallonsTolerance); - Assert.Equal(VolumeUnit.DecausGallon, decausgallonQuantity.Unit); - - var deciliterQuantity = cubicmeter.ToUnit(VolumeUnit.Deciliter); - AssertEx.EqualTolerance(DecilitersInOneCubicMeter, (double)deciliterQuantity.Value, DecilitersTolerance); - Assert.Equal(VolumeUnit.Deciliter, deciliterQuantity.Unit); - - var deciusgallonQuantity = cubicmeter.ToUnit(VolumeUnit.DeciusGallon); - AssertEx.EqualTolerance(DeciusGallonsInOneCubicMeter, (double)deciusgallonQuantity.Value, DeciusGallonsTolerance); - Assert.Equal(VolumeUnit.DeciusGallon, deciusgallonQuantity.Unit); - - var hectocubicfootQuantity = cubicmeter.ToUnit(VolumeUnit.HectocubicFoot); - AssertEx.EqualTolerance(HectocubicFeetInOneCubicMeter, (double)hectocubicfootQuantity.Value, HectocubicFeetTolerance); - Assert.Equal(VolumeUnit.HectocubicFoot, hectocubicfootQuantity.Unit); - - var hectocubicmeterQuantity = cubicmeter.ToUnit(VolumeUnit.HectocubicMeter); - AssertEx.EqualTolerance(HectocubicMetersInOneCubicMeter, (double)hectocubicmeterQuantity.Value, HectocubicMetersTolerance); - Assert.Equal(VolumeUnit.HectocubicMeter, hectocubicmeterQuantity.Unit); - - var hectoliterQuantity = cubicmeter.ToUnit(VolumeUnit.Hectoliter); - AssertEx.EqualTolerance(HectolitersInOneCubicMeter, (double)hectoliterQuantity.Value, HectolitersTolerance); - Assert.Equal(VolumeUnit.Hectoliter, hectoliterQuantity.Unit); - - var hectousgallonQuantity = cubicmeter.ToUnit(VolumeUnit.HectousGallon); - AssertEx.EqualTolerance(HectousGallonsInOneCubicMeter, (double)hectousgallonQuantity.Value, HectousGallonsTolerance); - Assert.Equal(VolumeUnit.HectousGallon, hectousgallonQuantity.Unit); - - var imperialbeerbarrelQuantity = cubicmeter.ToUnit(VolumeUnit.ImperialBeerBarrel); - AssertEx.EqualTolerance(ImperialBeerBarrelsInOneCubicMeter, (double)imperialbeerbarrelQuantity.Value, ImperialBeerBarrelsTolerance); - Assert.Equal(VolumeUnit.ImperialBeerBarrel, imperialbeerbarrelQuantity.Unit); - - var imperialgallonQuantity = cubicmeter.ToUnit(VolumeUnit.ImperialGallon); - AssertEx.EqualTolerance(ImperialGallonsInOneCubicMeter, (double)imperialgallonQuantity.Value, ImperialGallonsTolerance); - Assert.Equal(VolumeUnit.ImperialGallon, imperialgallonQuantity.Unit); + var inBaseUnits = Volume.From(1.0, Volume.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var imperialounceQuantity = cubicmeter.ToUnit(VolumeUnit.ImperialOunce); - AssertEx.EqualTolerance(ImperialOuncesInOneCubicMeter, (double)imperialounceQuantity.Value, ImperialOuncesTolerance); - Assert.Equal(VolumeUnit.ImperialOunce, imperialounceQuantity.Unit); - - var imperialpintQuantity = cubicmeter.ToUnit(VolumeUnit.ImperialPint); - AssertEx.EqualTolerance(ImperialPintsInOneCubicMeter, (double)imperialpintQuantity.Value, ImperialPintsTolerance); - Assert.Equal(VolumeUnit.ImperialPint, imperialpintQuantity.Unit); - - var kilocubicfootQuantity = cubicmeter.ToUnit(VolumeUnit.KilocubicFoot); - AssertEx.EqualTolerance(KilocubicFeetInOneCubicMeter, (double)kilocubicfootQuantity.Value, KilocubicFeetTolerance); - Assert.Equal(VolumeUnit.KilocubicFoot, kilocubicfootQuantity.Unit); - - var kilocubicmeterQuantity = cubicmeter.ToUnit(VolumeUnit.KilocubicMeter); - AssertEx.EqualTolerance(KilocubicMetersInOneCubicMeter, (double)kilocubicmeterQuantity.Value, KilocubicMetersTolerance); - Assert.Equal(VolumeUnit.KilocubicMeter, kilocubicmeterQuantity.Unit); - - var kiloimperialgallonQuantity = cubicmeter.ToUnit(VolumeUnit.KiloimperialGallon); - AssertEx.EqualTolerance(KiloimperialGallonsInOneCubicMeter, (double)kiloimperialgallonQuantity.Value, KiloimperialGallonsTolerance); - Assert.Equal(VolumeUnit.KiloimperialGallon, kiloimperialgallonQuantity.Unit); - - var kiloliterQuantity = cubicmeter.ToUnit(VolumeUnit.Kiloliter); - AssertEx.EqualTolerance(KilolitersInOneCubicMeter, (double)kiloliterQuantity.Value, KilolitersTolerance); - Assert.Equal(VolumeUnit.Kiloliter, kiloliterQuantity.Unit); - - var kilousgallonQuantity = cubicmeter.ToUnit(VolumeUnit.KilousGallon); - AssertEx.EqualTolerance(KilousGallonsInOneCubicMeter, (double)kilousgallonQuantity.Value, KilousGallonsTolerance); - Assert.Equal(VolumeUnit.KilousGallon, kilousgallonQuantity.Unit); - - var literQuantity = cubicmeter.ToUnit(VolumeUnit.Liter); - AssertEx.EqualTolerance(LitersInOneCubicMeter, (double)literQuantity.Value, LitersTolerance); - Assert.Equal(VolumeUnit.Liter, literQuantity.Unit); - - var megacubicfootQuantity = cubicmeter.ToUnit(VolumeUnit.MegacubicFoot); - AssertEx.EqualTolerance(MegacubicFeetInOneCubicMeter, (double)megacubicfootQuantity.Value, MegacubicFeetTolerance); - Assert.Equal(VolumeUnit.MegacubicFoot, megacubicfootQuantity.Unit); - - var megaimperialgallonQuantity = cubicmeter.ToUnit(VolumeUnit.MegaimperialGallon); - AssertEx.EqualTolerance(MegaimperialGallonsInOneCubicMeter, (double)megaimperialgallonQuantity.Value, MegaimperialGallonsTolerance); - Assert.Equal(VolumeUnit.MegaimperialGallon, megaimperialgallonQuantity.Unit); - - var megaliterQuantity = cubicmeter.ToUnit(VolumeUnit.Megaliter); - AssertEx.EqualTolerance(MegalitersInOneCubicMeter, (double)megaliterQuantity.Value, MegalitersTolerance); - Assert.Equal(VolumeUnit.Megaliter, megaliterQuantity.Unit); - - var megausgallonQuantity = cubicmeter.ToUnit(VolumeUnit.MegausGallon); - AssertEx.EqualTolerance(MegausGallonsInOneCubicMeter, (double)megausgallonQuantity.Value, MegausGallonsTolerance); - Assert.Equal(VolumeUnit.MegausGallon, megausgallonQuantity.Unit); - - var metriccupQuantity = cubicmeter.ToUnit(VolumeUnit.MetricCup); - AssertEx.EqualTolerance(MetricCupsInOneCubicMeter, (double)metriccupQuantity.Value, MetricCupsTolerance); - Assert.Equal(VolumeUnit.MetricCup, metriccupQuantity.Unit); - - var metricteaspoonQuantity = cubicmeter.ToUnit(VolumeUnit.MetricTeaspoon); - AssertEx.EqualTolerance(MetricTeaspoonsInOneCubicMeter, (double)metricteaspoonQuantity.Value, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, metricteaspoonQuantity.Unit); - - var microliterQuantity = cubicmeter.ToUnit(VolumeUnit.Microliter); - AssertEx.EqualTolerance(MicrolitersInOneCubicMeter, (double)microliterQuantity.Value, MicrolitersTolerance); - Assert.Equal(VolumeUnit.Microliter, microliterQuantity.Unit); - - var milliliterQuantity = cubicmeter.ToUnit(VolumeUnit.Milliliter); - AssertEx.EqualTolerance(MillilitersInOneCubicMeter, (double)milliliterQuantity.Value, MillilitersTolerance); - Assert.Equal(VolumeUnit.Milliliter, milliliterQuantity.Unit); - - var oilbarrelQuantity = cubicmeter.ToUnit(VolumeUnit.OilBarrel); - AssertEx.EqualTolerance(OilBarrelsInOneCubicMeter, (double)oilbarrelQuantity.Value, OilBarrelsTolerance); - Assert.Equal(VolumeUnit.OilBarrel, oilbarrelQuantity.Unit); - - var uktablespoonQuantity = cubicmeter.ToUnit(VolumeUnit.UkTablespoon); - AssertEx.EqualTolerance(UkTablespoonsInOneCubicMeter, (double)uktablespoonQuantity.Value, UkTablespoonsTolerance); - Assert.Equal(VolumeUnit.UkTablespoon, uktablespoonQuantity.Unit); - - var usbeerbarrelQuantity = cubicmeter.ToUnit(VolumeUnit.UsBeerBarrel); - AssertEx.EqualTolerance(UsBeerBarrelsInOneCubicMeter, (double)usbeerbarrelQuantity.Value, UsBeerBarrelsTolerance); - Assert.Equal(VolumeUnit.UsBeerBarrel, usbeerbarrelQuantity.Unit); - - var uscustomarycupQuantity = cubicmeter.ToUnit(VolumeUnit.UsCustomaryCup); - AssertEx.EqualTolerance(UsCustomaryCupsInOneCubicMeter, (double)uscustomarycupQuantity.Value, UsCustomaryCupsTolerance); - Assert.Equal(VolumeUnit.UsCustomaryCup, uscustomarycupQuantity.Unit); - - var usgallonQuantity = cubicmeter.ToUnit(VolumeUnit.UsGallon); - AssertEx.EqualTolerance(UsGallonsInOneCubicMeter, (double)usgallonQuantity.Value, UsGallonsTolerance); - Assert.Equal(VolumeUnit.UsGallon, usgallonQuantity.Unit); - - var uslegalcupQuantity = cubicmeter.ToUnit(VolumeUnit.UsLegalCup); - AssertEx.EqualTolerance(UsLegalCupsInOneCubicMeter, (double)uslegalcupQuantity.Value, UsLegalCupsTolerance); - Assert.Equal(VolumeUnit.UsLegalCup, uslegalcupQuantity.Unit); - - var usounceQuantity = cubicmeter.ToUnit(VolumeUnit.UsOunce); - AssertEx.EqualTolerance(UsOuncesInOneCubicMeter, (double)usounceQuantity.Value, UsOuncesTolerance); - Assert.Equal(VolumeUnit.UsOunce, usounceQuantity.Unit); - - var uspintQuantity = cubicmeter.ToUnit(VolumeUnit.UsPint); - AssertEx.EqualTolerance(UsPintsInOneCubicMeter, (double)uspintQuantity.Value, UsPintsTolerance); - Assert.Equal(VolumeUnit.UsPint, uspintQuantity.Unit); - - var usquartQuantity = cubicmeter.ToUnit(VolumeUnit.UsQuart); - AssertEx.EqualTolerance(UsQuartsInOneCubicMeter, (double)usquartQuantity.Value, UsQuartsTolerance); - Assert.Equal(VolumeUnit.UsQuart, usquartQuantity.Unit); - - var ustablespoonQuantity = cubicmeter.ToUnit(VolumeUnit.UsTablespoon); - AssertEx.EqualTolerance(UsTablespoonsInOneCubicMeter, (double)ustablespoonQuantity.Value, UsTablespoonsTolerance); - Assert.Equal(VolumeUnit.UsTablespoon, ustablespoonQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var usteaspoonQuantity = cubicmeter.ToUnit(VolumeUnit.UsTeaspoon); - AssertEx.EqualTolerance(UsTeaspoonsInOneCubicMeter, (double)usteaspoonQuantity.Value, UsTeaspoonsTolerance); - Assert.Equal(VolumeUnit.UsTeaspoon, usteaspoonQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(VolumeUnit unit) + { + var quantity = Volume.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeUnit unit) { - var quantityInBaseUnit = Volume.FromCubicMeters(1).ToBaseUnit(); - Assert.Equal(Volume.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = Volume.Units.FirstOrDefault(u => u != Volume.BaseUnit && u != VolumeUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == VolumeUnit.Undefined) + fromUnit = Volume.BaseUnit; + + var quantity = Volume.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs index 8abd390f15..68f191f66c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -59,6 +60,36 @@ public abstract partial class VolumetricHeatCapacityTestsBase : QuantityTestsBas protected virtual double MegajoulesPerCubicMeterKelvinTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumetricHeatCapacityUnit unit) + { + return unit switch + { + VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit => (BtusPerCubicFootDegreeFahrenheitInOneJoulePerCubicMeterKelvin, BtusPerCubicFootDegreeFahrenheitTolerance), + VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius => (CaloriesPerCubicCentimeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, CaloriesPerCubicCentimeterDegreeCelsiusTolerance), + VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius => (JoulesPerCubicMeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, JoulesPerCubicMeterDegreeCelsiusTolerance), + VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin => (JoulesPerCubicMeterKelvinInOneJoulePerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance), + VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius => (KilocaloriesPerCubicCentimeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, KilocaloriesPerCubicCentimeterDegreeCelsiusTolerance), + VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius => (KilojoulesPerCubicMeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, KilojoulesPerCubicMeterDegreeCelsiusTolerance), + VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin => (KilojoulesPerCubicMeterKelvinInOneJoulePerCubicMeterKelvin, KilojoulesPerCubicMeterKelvinTolerance), + VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius => (MegajoulesPerCubicMeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, MegajoulesPerCubicMeterDegreeCelsiusTolerance), + VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin => (MegajoulesPerCubicMeterKelvinInOneJoulePerCubicMeterKelvin, MegajoulesPerCubicMeterKelvinTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit }, + new object[] { VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius }, + new object[] { VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius }, + new object[] { VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin }, + new object[] { VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius }, + new object[] { VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius }, + new object[] { VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin }, + new object[] { VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius }, + new object[] { VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -228,53 +259,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(VolumetricHeatCapacityUnit unit) { - var joulepercubicmeterkelvin = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - - var btupercubicfootdegreefahrenheitQuantity = joulepercubicmeterkelvin.ToUnit(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); - AssertEx.EqualTolerance(BtusPerCubicFootDegreeFahrenheitInOneJoulePerCubicMeterKelvin, (double)btupercubicfootdegreefahrenheitQuantity.Value, BtusPerCubicFootDegreeFahrenheitTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, btupercubicfootdegreefahrenheitQuantity.Unit); - - var caloriepercubiccentimeterdegreecelsiusQuantity = joulepercubicmeterkelvin.ToUnit(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); - AssertEx.EqualTolerance(CaloriesPerCubicCentimeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, (double)caloriepercubiccentimeterdegreecelsiusQuantity.Value, CaloriesPerCubicCentimeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, caloriepercubiccentimeterdegreecelsiusQuantity.Unit); - - var joulepercubicmeterdegreecelsiusQuantity = joulepercubicmeterkelvin.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); - AssertEx.EqualTolerance(JoulesPerCubicMeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, (double)joulepercubicmeterdegreecelsiusQuantity.Value, JoulesPerCubicMeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, joulepercubicmeterdegreecelsiusQuantity.Unit); - - var joulepercubicmeterkelvinQuantity = joulepercubicmeterkelvin.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); - AssertEx.EqualTolerance(JoulesPerCubicMeterKelvinInOneJoulePerCubicMeterKelvin, (double)joulepercubicmeterkelvinQuantity.Value, JoulesPerCubicMeterKelvinTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, joulepercubicmeterkelvinQuantity.Unit); + var inBaseUnits = VolumetricHeatCapacity.From(1.0, VolumetricHeatCapacity.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var kilocaloriepercubiccentimeterdegreecelsiusQuantity = joulepercubicmeterkelvin.ToUnit(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); - AssertEx.EqualTolerance(KilocaloriesPerCubicCentimeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, (double)kilocaloriepercubiccentimeterdegreecelsiusQuantity.Value, KilocaloriesPerCubicCentimeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, kilocaloriepercubiccentimeterdegreecelsiusQuantity.Unit); - - var kilojoulepercubicmeterdegreecelsiusQuantity = joulepercubicmeterkelvin.ToUnit(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); - AssertEx.EqualTolerance(KilojoulesPerCubicMeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, (double)kilojoulepercubicmeterdegreecelsiusQuantity.Value, KilojoulesPerCubicMeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, kilojoulepercubicmeterdegreecelsiusQuantity.Unit); - - var kilojoulepercubicmeterkelvinQuantity = joulepercubicmeterkelvin.ToUnit(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); - AssertEx.EqualTolerance(KilojoulesPerCubicMeterKelvinInOneJoulePerCubicMeterKelvin, (double)kilojoulepercubicmeterkelvinQuantity.Value, KilojoulesPerCubicMeterKelvinTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, kilojoulepercubicmeterkelvinQuantity.Unit); - - var megajoulepercubicmeterdegreecelsiusQuantity = joulepercubicmeterkelvin.ToUnit(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); - AssertEx.EqualTolerance(MegajoulesPerCubicMeterDegreeCelsiusInOneJoulePerCubicMeterKelvin, (double)megajoulepercubicmeterdegreecelsiusQuantity.Value, MegajoulesPerCubicMeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, megajoulepercubicmeterdegreecelsiusQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var megajoulepercubicmeterkelvinQuantity = joulepercubicmeterkelvin.ToUnit(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); - AssertEx.EqualTolerance(MegajoulesPerCubicMeterKelvinInOneJoulePerCubicMeterKelvin, (double)megajoulepercubicmeterkelvinQuantity.Value, MegajoulesPerCubicMeterKelvinTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, megajoulepercubicmeterkelvinQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(VolumetricHeatCapacityUnit unit) + { + var quantity = VolumetricHeatCapacity.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumetricHeatCapacityUnit unit) { - var quantityInBaseUnit = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1).ToBaseUnit(); - Assert.Equal(VolumetricHeatCapacity.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = VolumetricHeatCapacity.Units.FirstOrDefault(u => u != VolumetricHeatCapacity.BaseUnit && u != VolumetricHeatCapacityUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == VolumetricHeatCapacityUnit.Undefined) + fromUnit = VolumetricHeatCapacity.BaseUnit; + + var quantity = VolumetricHeatCapacity.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs index 6890a5115c..6f1677cfb9 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs @@ -18,6 +18,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; @@ -53,6 +54,30 @@ public abstract partial class WarpingMomentOfInertiaTestsBase : QuantityTestsBas protected virtual double MillimetersToTheSixthTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(WarpingMomentOfInertiaUnit unit) + { + return unit switch + { + WarpingMomentOfInertiaUnit.CentimeterToTheSixth => (CentimetersToTheSixthInOneMeterToTheSixth, CentimetersToTheSixthTolerance), + WarpingMomentOfInertiaUnit.DecimeterToTheSixth => (DecimetersToTheSixthInOneMeterToTheSixth, DecimetersToTheSixthTolerance), + WarpingMomentOfInertiaUnit.FootToTheSixth => (FeetToTheSixthInOneMeterToTheSixth, FeetToTheSixthTolerance), + WarpingMomentOfInertiaUnit.InchToTheSixth => (InchesToTheSixthInOneMeterToTheSixth, InchesToTheSixthTolerance), + WarpingMomentOfInertiaUnit.MeterToTheSixth => (MetersToTheSixthInOneMeterToTheSixth, MetersToTheSixthTolerance), + WarpingMomentOfInertiaUnit.MillimeterToTheSixth => (MillimetersToTheSixthInOneMeterToTheSixth, MillimetersToTheSixthTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { WarpingMomentOfInertiaUnit.CentimeterToTheSixth }, + new object[] { WarpingMomentOfInertiaUnit.DecimeterToTheSixth }, + new object[] { WarpingMomentOfInertiaUnit.FootToTheSixth }, + new object[] { WarpingMomentOfInertiaUnit.InchToTheSixth }, + new object[] { WarpingMomentOfInertiaUnit.MeterToTheSixth }, + new object[] { WarpingMomentOfInertiaUnit.MillimeterToTheSixth }, + }; + [Fact] public void Ctor_WithUndefinedUnit_ThrowsArgumentException() { @@ -204,41 +229,41 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() } } - [Fact] - public void ToUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(WarpingMomentOfInertiaUnit unit) { - var metertothesixth = WarpingMomentOfInertia.FromMetersToTheSixth(1); - - var centimetertothesixthQuantity = metertothesixth.ToUnit(WarpingMomentOfInertiaUnit.CentimeterToTheSixth); - AssertEx.EqualTolerance(CentimetersToTheSixthInOneMeterToTheSixth, (double)centimetertothesixthQuantity.Value, CentimetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, centimetertothesixthQuantity.Unit); + var inBaseUnits = WarpingMomentOfInertia.From(1.0, WarpingMomentOfInertia.BaseUnit); + var converted = inBaseUnits.ToUnit(unit); - var decimetertothesixthQuantity = metertothesixth.ToUnit(WarpingMomentOfInertiaUnit.DecimeterToTheSixth); - AssertEx.EqualTolerance(DecimetersToTheSixthInOneMeterToTheSixth, (double)decimetertothesixthQuantity.Value, DecimetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, decimetertothesixthQuantity.Unit); - - var foottothesixthQuantity = metertothesixth.ToUnit(WarpingMomentOfInertiaUnit.FootToTheSixth); - AssertEx.EqualTolerance(FeetToTheSixthInOneMeterToTheSixth, (double)foottothesixthQuantity.Value, FeetToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.FootToTheSixth, foottothesixthQuantity.Unit); - - var inchtothesixthQuantity = metertothesixth.ToUnit(WarpingMomentOfInertiaUnit.InchToTheSixth); - AssertEx.EqualTolerance(InchesToTheSixthInOneMeterToTheSixth, (double)inchtothesixthQuantity.Value, InchesToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.InchToTheSixth, inchtothesixthQuantity.Unit); - - var metertothesixthQuantity = metertothesixth.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth); - AssertEx.EqualTolerance(MetersToTheSixthInOneMeterToTheSixth, (double)metertothesixthQuantity.Value, MetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.MeterToTheSixth, metertothesixthQuantity.Unit); + var conversionFactor = GetConversionFactor(unit); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + Assert.Equal(unit, converted.Unit); + } - var millimetertothesixthQuantity = metertothesixth.ToUnit(WarpingMomentOfInertiaUnit.MillimeterToTheSixth); - AssertEx.EqualTolerance(MillimetersToTheSixthInOneMeterToTheSixth, (double)millimetertothesixthQuantity.Value, MillimetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, millimetertothesixthQuantity.Unit); + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_WithSameUnits_AreEqual(WarpingMomentOfInertiaUnit unit) + { + var quantity = WarpingMomentOfInertia.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); } - [Fact] - public void ToBaseUnit_ReturnsQuantityWithBaseUnit() + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(WarpingMomentOfInertiaUnit unit) { - var quantityInBaseUnit = WarpingMomentOfInertia.FromMetersToTheSixth(1).ToBaseUnit(); - Assert.Equal(WarpingMomentOfInertia.BaseUnit, quantityInBaseUnit.Unit); + // See if there is a unit available that is not the base unit. + var fromUnit = WarpingMomentOfInertia.Units.FirstOrDefault(u => u != WarpingMomentOfInertia.BaseUnit && u != WarpingMomentOfInertiaUnit.Undefined); + + // If there is only one unit for the quantity, we must use the base unit. + if(fromUnit == WarpingMomentOfInertiaUnit.Undefined) + fromUnit = WarpingMomentOfInertia.BaseUnit; + + var quantity = WarpingMomentOfInertia.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); } [Fact] diff --git a/UnitsNet.Tests/UnitConverterTest.cs b/UnitsNet.Tests/UnitConverterTest.cs index 9de3a67e94..421d7fef23 100644 --- a/UnitsNet.Tests/UnitConverterTest.cs +++ b/UnitsNet.Tests/UnitConverterTest.cs @@ -9,6 +9,19 @@ namespace UnitsNet.Tests { public class UnitConverterTest { + [Fact] + public void CopyConstructorCopiesCoversionFunctions() + { + Length ConversionFunction(Length from) => Length.FromInches(18); + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, ConversionFunction); + + var copiedUnitConverter = new UnitConverter(unitConverter); + var foundConversionFunction = copiedUnitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); + Assert.NotNull(foundConversionFunction); + } + [Fact] public void CustomConversionWithSameQuantityType() { diff --git a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs index 13cfef0974..6463a39af7 100644 --- a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs @@ -78,6 +78,8 @@ static Acceleration() new UnitInfo(AccelerationUnit.StandardGravity, "StandardGravity", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), }, BaseUnit, Zero, BaseDimensions, QuantityType.Acceleration); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -116,6 +118,11 @@ public Acceleration(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -273,37 +280,37 @@ public Acceleration(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> AccelerationUnit - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.CentimeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.CentimeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.DecimeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.DecimeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.FootPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.FootPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.InchPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.InchPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KilometerPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.KilometerPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerHour, quantity => quantity.ToUnit(AccelerationUnit.KnotPerHour)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerMinute, quantity => quantity.ToUnit(AccelerationUnit.KnotPerMinute)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerSecond, quantity => quantity.ToUnit(AccelerationUnit.KnotPerSecond)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MicrometerPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MicrometerPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillimeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MillimeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillistandardGravity, quantity => quantity.ToUnit(AccelerationUnit.MillistandardGravity)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.NanometerPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.NanometerPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.StandardGravity, quantity => quantity.ToUnit(AccelerationUnit.StandardGravity)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.CentimeterPerSecondSquared, quantity => new Acceleration((quantity.Value) / 1e-2d, AccelerationUnit.CentimeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.DecimeterPerSecondSquared, quantity => new Acceleration((quantity.Value) / 1e-1d, AccelerationUnit.DecimeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.FootPerSecondSquared, quantity => new Acceleration(quantity.Value/0.304800, AccelerationUnit.FootPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.InchPerSecondSquared, quantity => new Acceleration(quantity.Value/0.0254, AccelerationUnit.InchPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KilometerPerSecondSquared, quantity => new Acceleration((quantity.Value) / 1e3d, AccelerationUnit.KilometerPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerHour, quantity => new Acceleration(quantity.Value/0.5144444444444*3600, AccelerationUnit.KnotPerHour)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerMinute, quantity => new Acceleration(quantity.Value/0.5144444444444*60, AccelerationUnit.KnotPerMinute)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerSecond, quantity => new Acceleration(quantity.Value/0.5144444444444, AccelerationUnit.KnotPerSecond)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MicrometerPerSecondSquared, quantity => new Acceleration((quantity.Value) / 1e-6d, AccelerationUnit.MicrometerPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillimeterPerSecondSquared, quantity => new Acceleration((quantity.Value) / 1e-3d, AccelerationUnit.MillimeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillistandardGravity, quantity => new Acceleration((quantity.Value/9.80665) / 1e-3d, AccelerationUnit.MillistandardGravity)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.NanometerPerSecondSquared, quantity => new Acceleration((quantity.Value) / 1e-9d, AccelerationUnit.NanometerPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.StandardGravity, quantity => new Acceleration(quantity.Value/9.80665, AccelerationUnit.StandardGravity)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity); // Register in unit converter: AccelerationUnit -> BaseUnit - unitConverter.SetConversionFunction(AccelerationUnit.CentimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.DecimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.FootPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.InchPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.KilometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.KnotPerHour, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.KnotPerMinute, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.KnotPerSecond, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.MicrometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.MillimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.MillistandardGravity, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.NanometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AccelerationUnit.StandardGravity, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(AccelerationUnit.CentimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration((quantity.Value) * 1e-2d, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.DecimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration((quantity.Value) * 1e-1d, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.FootPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration(quantity.Value*0.304800, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.InchPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration(quantity.Value*0.0254, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.KilometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration((quantity.Value) * 1e3d, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.KnotPerHour, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration(quantity.Value*0.5144444444444/3600, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.KnotPerMinute, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration(quantity.Value*0.5144444444444/60, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.KnotPerSecond, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration(quantity.Value*0.5144444444444, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MicrometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration((quantity.Value) * 1e-6d, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MillimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration((quantity.Value) * 1e-3d, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.MillistandardGravity, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration((quantity.Value*9.80665) * 1e-3d, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.NanometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration((quantity.Value) * 1e-9d, AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction(AccelerationUnit.StandardGravity, AccelerationUnit.MeterPerSecondSquared, quantity => new Acceleration(quantity.Value*9.80665, AccelerationUnit.MeterPerSecondSquared)); } /// @@ -837,11 +844,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Acceleration to another Acceleration with the unit representation . /// + /// The unit to convert to. /// A Acceleration with the specified unit. public Acceleration ToUnit(AccelerationUnit unit) { - var convertedValue = GetValueAs(unit); - return new Acceleration(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Acceleration to another Acceleration using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Acceleration with the specified unit. + public Acceleration ToUnit(AccelerationUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Acceleration), Unit, typeof(Acceleration), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Acceleration)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -850,7 +888,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is AccelerationUnit unitAsAccelerationUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AccelerationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAccelerationUnit); + return ToUnit(unitAsAccelerationUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is AccelerationUnit unitAsAccelerationUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AccelerationUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsAccelerationUnit, unitConverter); } /// @@ -875,73 +922,15 @@ public Acceleration ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(AccelerationUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case AccelerationUnit.CentimeterPerSecondSquared: return (_value) * 1e-2d; - case AccelerationUnit.DecimeterPerSecondSquared: return (_value) * 1e-1d; - case AccelerationUnit.FootPerSecondSquared: return _value*0.304800; - case AccelerationUnit.InchPerSecondSquared: return _value*0.0254; - case AccelerationUnit.KilometerPerSecondSquared: return (_value) * 1e3d; - case AccelerationUnit.KnotPerHour: return _value*0.5144444444444/3600; - case AccelerationUnit.KnotPerMinute: return _value*0.5144444444444/60; - case AccelerationUnit.KnotPerSecond: return _value*0.5144444444444; - case AccelerationUnit.MeterPerSecondSquared: return _value; - case AccelerationUnit.MicrometerPerSecondSquared: return (_value) * 1e-6d; - case AccelerationUnit.MillimeterPerSecondSquared: return (_value) * 1e-3d; - case AccelerationUnit.MillistandardGravity: return (_value*9.80665) * 1e-3d; - case AccelerationUnit.NanometerPerSecondSquared: return (_value) * 1e-9d; - case AccelerationUnit.StandardGravity: return _value*9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(AccelerationUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Acceleration ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Acceleration(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(AccelerationUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case AccelerationUnit.CentimeterPerSecondSquared: return (baseUnitValue) / 1e-2d; - case AccelerationUnit.DecimeterPerSecondSquared: return (baseUnitValue) / 1e-1d; - case AccelerationUnit.FootPerSecondSquared: return baseUnitValue/0.304800; - case AccelerationUnit.InchPerSecondSquared: return baseUnitValue/0.0254; - case AccelerationUnit.KilometerPerSecondSquared: return (baseUnitValue) / 1e3d; - case AccelerationUnit.KnotPerHour: return baseUnitValue/0.5144444444444*3600; - case AccelerationUnit.KnotPerMinute: return baseUnitValue/0.5144444444444*60; - case AccelerationUnit.KnotPerSecond: return baseUnitValue/0.5144444444444; - case AccelerationUnit.MeterPerSecondSquared: return baseUnitValue; - case AccelerationUnit.MicrometerPerSecondSquared: return (baseUnitValue) / 1e-6d; - case AccelerationUnit.MillimeterPerSecondSquared: return (baseUnitValue) / 1e-3d; - case AccelerationUnit.MillistandardGravity: return (baseUnitValue/9.80665) / 1e-3d; - case AccelerationUnit.NanometerPerSecondSquared: return (baseUnitValue) / 1e-9d; - case AccelerationUnit.StandardGravity: return baseUnitValue/9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs index d127717a65..f0a95c8bff 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs @@ -79,6 +79,8 @@ static AmountOfSubstance() new UnitInfo(AmountOfSubstanceUnit.PoundMole, "PoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.PoundMole)), }, BaseUnit, Zero, BaseDimensions, QuantityType.AmountOfSubstance); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -117,6 +119,11 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -279,39 +286,39 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> AmountOfSubstanceUnit - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Centimole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Centimole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.CentipoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.CentipoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Decimole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Decimole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.DecipoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.DecipoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Kilomole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Kilomole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.KilopoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.KilopoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Megamole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Megamole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Micromole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Micromole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MicropoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.MicropoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Millimole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Millimole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MillipoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.MillipoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Nanomole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Nanomole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.NanopoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.NanopoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.PoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.PoundMole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Centimole, quantity => new AmountOfSubstance((quantity.Value) / 1e-2d, AmountOfSubstanceUnit.Centimole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.CentipoundMole, quantity => new AmountOfSubstance((quantity.Value/453.59237) / 1e-2d, AmountOfSubstanceUnit.CentipoundMole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Decimole, quantity => new AmountOfSubstance((quantity.Value) / 1e-1d, AmountOfSubstanceUnit.Decimole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.DecipoundMole, quantity => new AmountOfSubstance((quantity.Value/453.59237) / 1e-1d, AmountOfSubstanceUnit.DecipoundMole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Kilomole, quantity => new AmountOfSubstance((quantity.Value) / 1e3d, AmountOfSubstanceUnit.Kilomole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.KilopoundMole, quantity => new AmountOfSubstance((quantity.Value/453.59237) / 1e3d, AmountOfSubstanceUnit.KilopoundMole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Megamole, quantity => new AmountOfSubstance((quantity.Value) / 1e6d, AmountOfSubstanceUnit.Megamole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Micromole, quantity => new AmountOfSubstance((quantity.Value) / 1e-6d, AmountOfSubstanceUnit.Micromole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MicropoundMole, quantity => new AmountOfSubstance((quantity.Value/453.59237) / 1e-6d, AmountOfSubstanceUnit.MicropoundMole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Millimole, quantity => new AmountOfSubstance((quantity.Value) / 1e-3d, AmountOfSubstanceUnit.Millimole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MillipoundMole, quantity => new AmountOfSubstance((quantity.Value/453.59237) / 1e-3d, AmountOfSubstanceUnit.MillipoundMole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Nanomole, quantity => new AmountOfSubstance((quantity.Value) / 1e-9d, AmountOfSubstanceUnit.Nanomole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.NanopoundMole, quantity => new AmountOfSubstance((quantity.Value/453.59237) / 1e-9d, AmountOfSubstanceUnit.NanopoundMole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.PoundMole, quantity => new AmountOfSubstance(quantity.Value/453.59237, AmountOfSubstanceUnit.PoundMole)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Mole, quantity => quantity); // Register in unit converter: AmountOfSubstanceUnit -> BaseUnit - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Centimole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.CentipoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Decimole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.DecipoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Kilomole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.KilopoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Megamole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Micromole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.MicropoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Millimole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.MillipoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Nanomole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.NanopoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.PoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Centimole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value) * 1e-2d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.CentipoundMole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value*453.59237) * 1e-2d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Decimole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value) * 1e-1d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.DecipoundMole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value*453.59237) * 1e-1d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Kilomole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value) * 1e3d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.KilopoundMole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value*453.59237) * 1e3d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Megamole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value) * 1e6d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Micromole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value) * 1e-6d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.MicropoundMole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value*453.59237) * 1e-6d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Millimole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value) * 1e-3d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.MillipoundMole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value*453.59237) * 1e-3d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Nanomole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value) * 1e-9d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.NanopoundMole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance((quantity.Value*453.59237) * 1e-9d, AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction(AmountOfSubstanceUnit.PoundMole, AmountOfSubstanceUnit.Mole, quantity => new AmountOfSubstance(quantity.Value*453.59237, AmountOfSubstanceUnit.Mole)); } /// @@ -854,11 +861,42 @@ double IQuantity.As(Enum unit) /// /// Converts this AmountOfSubstance to another AmountOfSubstance with the unit representation . /// + /// The unit to convert to. /// A AmountOfSubstance with the specified unit. public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) { - var convertedValue = GetValueAs(unit); - return new AmountOfSubstance(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this AmountOfSubstance to another AmountOfSubstance using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A AmountOfSubstance with the specified unit. + public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(AmountOfSubstance), Unit, typeof(AmountOfSubstance), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (AmountOfSubstance)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -867,7 +905,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is AmountOfSubstanceUnit unitAsAmountOfSubstanceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmountOfSubstanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAmountOfSubstanceUnit); + return ToUnit(unitAsAmountOfSubstanceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is AmountOfSubstanceUnit unitAsAmountOfSubstanceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmountOfSubstanceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsAmountOfSubstanceUnit, unitConverter); } /// @@ -892,75 +939,15 @@ public AmountOfSubstance ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(AmountOfSubstanceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case AmountOfSubstanceUnit.Centimole: return (_value) * 1e-2d; - case AmountOfSubstanceUnit.CentipoundMole: return (_value*453.59237) * 1e-2d; - case AmountOfSubstanceUnit.Decimole: return (_value) * 1e-1d; - case AmountOfSubstanceUnit.DecipoundMole: return (_value*453.59237) * 1e-1d; - case AmountOfSubstanceUnit.Kilomole: return (_value) * 1e3d; - case AmountOfSubstanceUnit.KilopoundMole: return (_value*453.59237) * 1e3d; - case AmountOfSubstanceUnit.Megamole: return (_value) * 1e6d; - case AmountOfSubstanceUnit.Micromole: return (_value) * 1e-6d; - case AmountOfSubstanceUnit.MicropoundMole: return (_value*453.59237) * 1e-6d; - case AmountOfSubstanceUnit.Millimole: return (_value) * 1e-3d; - case AmountOfSubstanceUnit.MillipoundMole: return (_value*453.59237) * 1e-3d; - case AmountOfSubstanceUnit.Mole: return _value; - case AmountOfSubstanceUnit.Nanomole: return (_value) * 1e-9d; - case AmountOfSubstanceUnit.NanopoundMole: return (_value*453.59237) * 1e-9d; - case AmountOfSubstanceUnit.PoundMole: return _value*453.59237; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(AmountOfSubstanceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal AmountOfSubstance ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new AmountOfSubstance(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(AmountOfSubstanceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case AmountOfSubstanceUnit.Centimole: return (baseUnitValue) / 1e-2d; - case AmountOfSubstanceUnit.CentipoundMole: return (baseUnitValue/453.59237) / 1e-2d; - case AmountOfSubstanceUnit.Decimole: return (baseUnitValue) / 1e-1d; - case AmountOfSubstanceUnit.DecipoundMole: return (baseUnitValue/453.59237) / 1e-1d; - case AmountOfSubstanceUnit.Kilomole: return (baseUnitValue) / 1e3d; - case AmountOfSubstanceUnit.KilopoundMole: return (baseUnitValue/453.59237) / 1e3d; - case AmountOfSubstanceUnit.Megamole: return (baseUnitValue) / 1e6d; - case AmountOfSubstanceUnit.Micromole: return (baseUnitValue) / 1e-6d; - case AmountOfSubstanceUnit.MicropoundMole: return (baseUnitValue/453.59237) / 1e-6d; - case AmountOfSubstanceUnit.Millimole: return (baseUnitValue) / 1e-3d; - case AmountOfSubstanceUnit.MillipoundMole: return (baseUnitValue/453.59237) / 1e-3d; - case AmountOfSubstanceUnit.Mole: return baseUnitValue; - case AmountOfSubstanceUnit.Nanomole: return (baseUnitValue) / 1e-9d; - case AmountOfSubstanceUnit.NanopoundMole: return (baseUnitValue/453.59237) / 1e-9d; - case AmountOfSubstanceUnit.PoundMole: return baseUnitValue/453.59237; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs index 4d3e2c24f0..5cb7f6c4ec 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs @@ -68,6 +68,8 @@ static AmplitudeRatio() new UnitInfo(AmplitudeRatioUnit.DecibelVolt, "DecibelVolts", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.AmplitudeRatio); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public AmplitudeRatio(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -213,17 +220,17 @@ public AmplitudeRatio(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> AmplitudeRatioUnit - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMicrovolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelMicrovolt)); - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMillivolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelMillivolt)); - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelUnloaded, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelUnloaded)); + unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMicrovolt, quantity => new AmplitudeRatio(quantity.Value + 120, AmplitudeRatioUnit.DecibelMicrovolt)); + unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMillivolt, quantity => new AmplitudeRatio(quantity.Value + 60, AmplitudeRatioUnit.DecibelMillivolt)); + unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelUnloaded, quantity => new AmplitudeRatio(quantity.Value + 2.218487499, AmplitudeRatioUnit.DecibelUnloaded)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelVolt, quantity => quantity); // Register in unit converter: AmplitudeRatioUnit -> BaseUnit - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelMicrovolt, AmplitudeRatioUnit.DecibelVolt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelMillivolt, AmplitudeRatioUnit.DecibelVolt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelUnloaded, AmplitudeRatioUnit.DecibelVolt, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelMicrovolt, AmplitudeRatioUnit.DecibelVolt, quantity => new AmplitudeRatio(quantity.Value - 120, AmplitudeRatioUnit.DecibelVolt)); + unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelMillivolt, AmplitudeRatioUnit.DecibelVolt, quantity => new AmplitudeRatio(quantity.Value - 60, AmplitudeRatioUnit.DecibelVolt)); + unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelUnloaded, AmplitudeRatioUnit.DecibelVolt, quantity => new AmplitudeRatio(quantity.Value - 2.218487499, AmplitudeRatioUnit.DecibelVolt)); } /// @@ -675,11 +682,42 @@ double IQuantity.As(Enum unit) /// /// Converts this AmplitudeRatio to another AmplitudeRatio with the unit representation . /// + /// The unit to convert to. /// A AmplitudeRatio with the specified unit. public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) { - var convertedValue = GetValueAs(unit); - return new AmplitudeRatio(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this AmplitudeRatio to another AmplitudeRatio using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A AmplitudeRatio with the specified unit. + public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(AmplitudeRatio), Unit, typeof(AmplitudeRatio), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (AmplitudeRatio)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -688,7 +726,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is AmplitudeRatioUnit unitAsAmplitudeRatioUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmplitudeRatioUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAmplitudeRatioUnit); + return ToUnit(unitAsAmplitudeRatioUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is AmplitudeRatioUnit unitAsAmplitudeRatioUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmplitudeRatioUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsAmplitudeRatioUnit, unitConverter); } /// @@ -713,53 +760,15 @@ public AmplitudeRatio ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(AmplitudeRatioUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: return _value - 120; - case AmplitudeRatioUnit.DecibelMillivolt: return _value - 60; - case AmplitudeRatioUnit.DecibelUnloaded: return _value - 2.218487499; - case AmplitudeRatioUnit.DecibelVolt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(AmplitudeRatioUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal AmplitudeRatio ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new AmplitudeRatio(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(AmplitudeRatioUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: return baseUnitValue + 120; - case AmplitudeRatioUnit.DecibelMillivolt: return baseUnitValue + 60; - case AmplitudeRatioUnit.DecibelUnloaded: return baseUnitValue + 2.218487499; - case AmplitudeRatioUnit.DecibelVolt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs index 5985109995..0bb72a8223 100644 --- a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs @@ -80,6 +80,8 @@ static Angle() new UnitInfo(AngleUnit.Tilt, "Tilt", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Angle); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -118,6 +120,11 @@ public Angle(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -285,41 +292,41 @@ public Angle(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> AngleUnit - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Arcminute, quantity => quantity.ToUnit(AngleUnit.Arcminute)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Arcsecond, quantity => quantity.ToUnit(AngleUnit.Arcsecond)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Centiradian, quantity => quantity.ToUnit(AngleUnit.Centiradian)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Deciradian, quantity => quantity.ToUnit(AngleUnit.Deciradian)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Gradian, quantity => quantity.ToUnit(AngleUnit.Gradian)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Microdegree, quantity => quantity.ToUnit(AngleUnit.Microdegree)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Microradian, quantity => quantity.ToUnit(AngleUnit.Microradian)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Millidegree, quantity => quantity.ToUnit(AngleUnit.Millidegree)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Milliradian, quantity => quantity.ToUnit(AngleUnit.Milliradian)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Nanodegree, quantity => quantity.ToUnit(AngleUnit.Nanodegree)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Nanoradian, quantity => quantity.ToUnit(AngleUnit.Nanoradian)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.NatoMil, quantity => quantity.ToUnit(AngleUnit.NatoMil)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Revolution, quantity => quantity.ToUnit(AngleUnit.Revolution)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Tilt, quantity => quantity.ToUnit(AngleUnit.Tilt)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Arcminute, quantity => new Angle(quantity.Value*60, AngleUnit.Arcminute)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Arcsecond, quantity => new Angle(quantity.Value*3600, AngleUnit.Arcsecond)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Centiradian, quantity => new Angle((quantity.Value/180*Math.PI) / 1e-2d, AngleUnit.Centiradian)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Deciradian, quantity => new Angle((quantity.Value/180*Math.PI) / 1e-1d, AngleUnit.Deciradian)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Gradian, quantity => new Angle(quantity.Value/0.9, AngleUnit.Gradian)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Microdegree, quantity => new Angle((quantity.Value) / 1e-6d, AngleUnit.Microdegree)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Microradian, quantity => new Angle((quantity.Value/180*Math.PI) / 1e-6d, AngleUnit.Microradian)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Millidegree, quantity => new Angle((quantity.Value) / 1e-3d, AngleUnit.Millidegree)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Milliradian, quantity => new Angle((quantity.Value/180*Math.PI) / 1e-3d, AngleUnit.Milliradian)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Nanodegree, quantity => new Angle((quantity.Value) / 1e-9d, AngleUnit.Nanodegree)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Nanoradian, quantity => new Angle((quantity.Value/180*Math.PI) / 1e-9d, AngleUnit.Nanoradian)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.NatoMil, quantity => new Angle(quantity.Value*160/9, AngleUnit.NatoMil)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Radian, quantity => new Angle(quantity.Value/180*Math.PI, AngleUnit.Radian)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Revolution, quantity => new Angle(quantity.Value/360, AngleUnit.Revolution)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Tilt, quantity => new Angle(Math.Sin(quantity.Value/180*Math.PI), AngleUnit.Tilt)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Degree, quantity => quantity); // Register in unit converter: AngleUnit -> BaseUnit - unitConverter.SetConversionFunction(AngleUnit.Arcminute, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Arcsecond, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Centiradian, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Deciradian, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Gradian, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Microdegree, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Microradian, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Millidegree, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Milliradian, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Nanodegree, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Nanoradian, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.NatoMil, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Revolution, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AngleUnit.Tilt, AngleUnit.Degree, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(AngleUnit.Arcminute, AngleUnit.Degree, quantity => new Angle(quantity.Value/60, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Arcsecond, AngleUnit.Degree, quantity => new Angle(quantity.Value/3600, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Centiradian, AngleUnit.Degree, quantity => new Angle((quantity.Value*180/Math.PI) * 1e-2d, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Deciradian, AngleUnit.Degree, quantity => new Angle((quantity.Value*180/Math.PI) * 1e-1d, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Gradian, AngleUnit.Degree, quantity => new Angle(quantity.Value*0.9, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Microdegree, AngleUnit.Degree, quantity => new Angle((quantity.Value) * 1e-6d, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Microradian, AngleUnit.Degree, quantity => new Angle((quantity.Value*180/Math.PI) * 1e-6d, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Millidegree, AngleUnit.Degree, quantity => new Angle((quantity.Value) * 1e-3d, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Milliradian, AngleUnit.Degree, quantity => new Angle((quantity.Value*180/Math.PI) * 1e-3d, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Nanodegree, AngleUnit.Degree, quantity => new Angle((quantity.Value) * 1e-9d, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Nanoradian, AngleUnit.Degree, quantity => new Angle((quantity.Value*180/Math.PI) * 1e-9d, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.NatoMil, AngleUnit.Degree, quantity => new Angle(quantity.Value*9/160, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Degree, quantity => new Angle(quantity.Value*180/Math.PI, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Revolution, AngleUnit.Degree, quantity => new Angle(quantity.Value*360, AngleUnit.Degree)); + unitConverter.SetConversionFunction(AngleUnit.Tilt, AngleUnit.Degree, quantity => new Angle(Math.Asin(quantity.Value)*180/Math.PI, AngleUnit.Degree)); } /// @@ -871,11 +878,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Angle to another Angle with the unit representation . /// + /// The unit to convert to. /// A Angle with the specified unit. public Angle ToUnit(AngleUnit unit) { - var convertedValue = GetValueAs(unit); - return new Angle(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Angle to another Angle using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Angle with the specified unit. + public Angle ToUnit(AngleUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Angle), Unit, typeof(Angle), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Angle)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -884,7 +922,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is AngleUnit unitAsAngleUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AngleUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAngleUnit); + return ToUnit(unitAsAngleUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is AngleUnit unitAsAngleUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AngleUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsAngleUnit, unitConverter); } /// @@ -909,77 +956,15 @@ public Angle ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(AngleUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case AngleUnit.Arcminute: return _value/60; - case AngleUnit.Arcsecond: return _value/3600; - case AngleUnit.Centiradian: return (_value*180/Math.PI) * 1e-2d; - case AngleUnit.Deciradian: return (_value*180/Math.PI) * 1e-1d; - case AngleUnit.Degree: return _value; - case AngleUnit.Gradian: return _value*0.9; - case AngleUnit.Microdegree: return (_value) * 1e-6d; - case AngleUnit.Microradian: return (_value*180/Math.PI) * 1e-6d; - case AngleUnit.Millidegree: return (_value) * 1e-3d; - case AngleUnit.Milliradian: return (_value*180/Math.PI) * 1e-3d; - case AngleUnit.Nanodegree: return (_value) * 1e-9d; - case AngleUnit.Nanoradian: return (_value*180/Math.PI) * 1e-9d; - case AngleUnit.NatoMil: return _value*9/160; - case AngleUnit.Radian: return _value*180/Math.PI; - case AngleUnit.Revolution: return _value*360; - case AngleUnit.Tilt: return Math.Asin(_value)*180/Math.PI; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(AngleUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Angle ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Angle(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(AngleUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case AngleUnit.Arcminute: return baseUnitValue*60; - case AngleUnit.Arcsecond: return baseUnitValue*3600; - case AngleUnit.Centiradian: return (baseUnitValue/180*Math.PI) / 1e-2d; - case AngleUnit.Deciradian: return (baseUnitValue/180*Math.PI) / 1e-1d; - case AngleUnit.Degree: return baseUnitValue; - case AngleUnit.Gradian: return baseUnitValue/0.9; - case AngleUnit.Microdegree: return (baseUnitValue) / 1e-6d; - case AngleUnit.Microradian: return (baseUnitValue/180*Math.PI) / 1e-6d; - case AngleUnit.Millidegree: return (baseUnitValue) / 1e-3d; - case AngleUnit.Milliradian: return (baseUnitValue/180*Math.PI) / 1e-3d; - case AngleUnit.Nanodegree: return (baseUnitValue) / 1e-9d; - case AngleUnit.Nanoradian: return (baseUnitValue/180*Math.PI) / 1e-9d; - case AngleUnit.NatoMil: return baseUnitValue*160/9; - case AngleUnit.Radian: return baseUnitValue/180*Math.PI; - case AngleUnit.Revolution: return baseUnitValue/360; - case AngleUnit.Tilt: return Math.Sin(baseUnitValue/180*Math.PI); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs index 78f50a4aa4..4c8700c719 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs @@ -67,6 +67,8 @@ static ApparentEnergy() new UnitInfo(ApparentEnergyUnit.VoltampereHour, "VoltampereHours", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ApparentEnergy); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -105,6 +107,11 @@ public ApparentEnergy(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -207,15 +214,15 @@ public ApparentEnergy(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ApparentEnergyUnit - unitConverter.SetConversionFunction(ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.KilovoltampereHour, quantity => quantity.ToUnit(ApparentEnergyUnit.KilovoltampereHour)); - unitConverter.SetConversionFunction(ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.MegavoltampereHour, quantity => quantity.ToUnit(ApparentEnergyUnit.MegavoltampereHour)); + unitConverter.SetConversionFunction(ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.KilovoltampereHour, quantity => new ApparentEnergy((quantity.Value) / 1e3d, ApparentEnergyUnit.KilovoltampereHour)); + unitConverter.SetConversionFunction(ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.MegavoltampereHour, quantity => new ApparentEnergy((quantity.Value) / 1e6d, ApparentEnergyUnit.MegavoltampereHour)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.VoltampereHour, quantity => quantity); // Register in unit converter: ApparentEnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(ApparentEnergyUnit.KilovoltampereHour, ApparentEnergyUnit.VoltampereHour, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ApparentEnergyUnit.MegavoltampereHour, ApparentEnergyUnit.VoltampereHour, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ApparentEnergyUnit.KilovoltampereHour, ApparentEnergyUnit.VoltampereHour, quantity => new ApparentEnergy((quantity.Value) * 1e3d, ApparentEnergyUnit.VoltampereHour)); + unitConverter.SetConversionFunction(ApparentEnergyUnit.MegavoltampereHour, ApparentEnergyUnit.VoltampereHour, quantity => new ApparentEnergy((quantity.Value) * 1e6d, ApparentEnergyUnit.VoltampereHour)); } /// @@ -650,11 +657,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ApparentEnergy to another ApparentEnergy with the unit representation . /// + /// The unit to convert to. /// A ApparentEnergy with the specified unit. public ApparentEnergy ToUnit(ApparentEnergyUnit unit) { - var convertedValue = GetValueAs(unit); - return new ApparentEnergy(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ApparentEnergy to another ApparentEnergy using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ApparentEnergy with the specified unit. + public ApparentEnergy ToUnit(ApparentEnergyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ApparentEnergy), Unit, typeof(ApparentEnergy), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ApparentEnergy)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -663,7 +701,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ApparentEnergyUnit unitAsApparentEnergyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentEnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsApparentEnergyUnit); + return ToUnit(unitAsApparentEnergyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ApparentEnergyUnit unitAsApparentEnergyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentEnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsApparentEnergyUnit, unitConverter); } /// @@ -688,51 +735,15 @@ public ApparentEnergy ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ApparentEnergyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ApparentEnergyUnit.KilovoltampereHour: return (_value) * 1e3d; - case ApparentEnergyUnit.MegavoltampereHour: return (_value) * 1e6d; - case ApparentEnergyUnit.VoltampereHour: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ApparentEnergyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ApparentEnergy ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ApparentEnergy(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ApparentEnergyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ApparentEnergyUnit.KilovoltampereHour: return (baseUnitValue) / 1e3d; - case ApparentEnergyUnit.MegavoltampereHour: return (baseUnitValue) / 1e6d; - case ApparentEnergyUnit.VoltampereHour: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs index be2bb33c7d..eff9b336d8 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs @@ -68,6 +68,8 @@ static ApparentPower() new UnitInfo(ApparentPowerUnit.Voltampere, "Voltamperes", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ApparentPower); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public ApparentPower(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -213,17 +220,17 @@ public ApparentPower(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ApparentPowerUnit - unitConverter.SetConversionFunction(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Gigavoltampere, quantity => quantity.ToUnit(ApparentPowerUnit.Gigavoltampere)); - unitConverter.SetConversionFunction(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Kilovoltampere, quantity => quantity.ToUnit(ApparentPowerUnit.Kilovoltampere)); - unitConverter.SetConversionFunction(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Megavoltampere, quantity => quantity.ToUnit(ApparentPowerUnit.Megavoltampere)); + unitConverter.SetConversionFunction(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Gigavoltampere, quantity => new ApparentPower((quantity.Value) / 1e9d, ApparentPowerUnit.Gigavoltampere)); + unitConverter.SetConversionFunction(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Kilovoltampere, quantity => new ApparentPower((quantity.Value) / 1e3d, ApparentPowerUnit.Kilovoltampere)); + unitConverter.SetConversionFunction(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Megavoltampere, quantity => new ApparentPower((quantity.Value) / 1e6d, ApparentPowerUnit.Megavoltampere)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Voltampere, quantity => quantity); // Register in unit converter: ApparentPowerUnit -> BaseUnit - unitConverter.SetConversionFunction(ApparentPowerUnit.Gigavoltampere, ApparentPowerUnit.Voltampere, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ApparentPowerUnit.Kilovoltampere, ApparentPowerUnit.Voltampere, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ApparentPowerUnit.Megavoltampere, ApparentPowerUnit.Voltampere, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ApparentPowerUnit.Gigavoltampere, ApparentPowerUnit.Voltampere, quantity => new ApparentPower((quantity.Value) * 1e9d, ApparentPowerUnit.Voltampere)); + unitConverter.SetConversionFunction(ApparentPowerUnit.Kilovoltampere, ApparentPowerUnit.Voltampere, quantity => new ApparentPower((quantity.Value) * 1e3d, ApparentPowerUnit.Voltampere)); + unitConverter.SetConversionFunction(ApparentPowerUnit.Megavoltampere, ApparentPowerUnit.Voltampere, quantity => new ApparentPower((quantity.Value) * 1e6d, ApparentPowerUnit.Voltampere)); } /// @@ -667,11 +674,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ApparentPower to another ApparentPower with the unit representation . /// + /// The unit to convert to. /// A ApparentPower with the specified unit. public ApparentPower ToUnit(ApparentPowerUnit unit) { - var convertedValue = GetValueAs(unit); - return new ApparentPower(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ApparentPower to another ApparentPower using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ApparentPower with the specified unit. + public ApparentPower ToUnit(ApparentPowerUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ApparentPower), Unit, typeof(ApparentPower), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ApparentPower)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -680,7 +718,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ApparentPowerUnit unitAsApparentPowerUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentPowerUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsApparentPowerUnit); + return ToUnit(unitAsApparentPowerUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ApparentPowerUnit unitAsApparentPowerUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentPowerUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsApparentPowerUnit, unitConverter); } /// @@ -705,53 +752,15 @@ public ApparentPower ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ApparentPowerUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ApparentPowerUnit.Gigavoltampere: return (_value) * 1e9d; - case ApparentPowerUnit.Kilovoltampere: return (_value) * 1e3d; - case ApparentPowerUnit.Megavoltampere: return (_value) * 1e6d; - case ApparentPowerUnit.Voltampere: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ApparentPowerUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ApparentPower ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ApparentPower(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ApparentPowerUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ApparentPowerUnit.Gigavoltampere: return (baseUnitValue) / 1e9d; - case ApparentPowerUnit.Kilovoltampere: return (baseUnitValue) / 1e3d; - case ApparentPowerUnit.Megavoltampere: return (baseUnitValue) / 1e6d; - case ApparentPowerUnit.Voltampere: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Area.g.cs b/UnitsNet/GeneratedCode/Quantities/Area.g.cs index 2abf2392ea..fc1ada0d35 100644 --- a/UnitsNet/GeneratedCode/Quantities/Area.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Area.g.cs @@ -78,6 +78,8 @@ static Area() new UnitInfo(AreaUnit.UsSurveySquareFoot, "UsSurveySquareFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot)), }, BaseUnit, Zero, BaseDimensions, QuantityType.Area); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -116,6 +118,11 @@ public Area(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -273,37 +280,37 @@ public Area(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> AreaUnit - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.Acre, quantity => quantity.ToUnit(AreaUnit.Acre)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.Hectare, quantity => quantity.ToUnit(AreaUnit.Hectare)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareCentimeter, quantity => quantity.ToUnit(AreaUnit.SquareCentimeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareDecimeter, quantity => quantity.ToUnit(AreaUnit.SquareDecimeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareFoot, quantity => quantity.ToUnit(AreaUnit.SquareFoot)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareInch, quantity => quantity.ToUnit(AreaUnit.SquareInch)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareKilometer, quantity => quantity.ToUnit(AreaUnit.SquareKilometer)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMicrometer, quantity => quantity.ToUnit(AreaUnit.SquareMicrometer)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMile, quantity => quantity.ToUnit(AreaUnit.SquareMile)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMillimeter, quantity => quantity.ToUnit(AreaUnit.SquareMillimeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareNauticalMile, quantity => quantity.ToUnit(AreaUnit.SquareNauticalMile)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareYard, quantity => quantity.ToUnit(AreaUnit.SquareYard)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.UsSurveySquareFoot, quantity => quantity.ToUnit(AreaUnit.UsSurveySquareFoot)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.Acre, quantity => new Area(quantity.Value/4046.85642, AreaUnit.Acre)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.Hectare, quantity => new Area(quantity.Value/1e4, AreaUnit.Hectare)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareCentimeter, quantity => new Area(quantity.Value/1e-4, AreaUnit.SquareCentimeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareDecimeter, quantity => new Area(quantity.Value/1e-2, AreaUnit.SquareDecimeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareFoot, quantity => new Area(quantity.Value/0.092903, AreaUnit.SquareFoot)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareInch, quantity => new Area(quantity.Value/0.00064516, AreaUnit.SquareInch)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareKilometer, quantity => new Area(quantity.Value/1e6, AreaUnit.SquareKilometer)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMicrometer, quantity => new Area(quantity.Value/1e-12, AreaUnit.SquareMicrometer)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMile, quantity => new Area(quantity.Value/2.59e6, AreaUnit.SquareMile)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMillimeter, quantity => new Area(quantity.Value/1e-6, AreaUnit.SquareMillimeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareNauticalMile, quantity => new Area(quantity.Value/3429904, AreaUnit.SquareNauticalMile)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareYard, quantity => new Area(quantity.Value/0.836127, AreaUnit.SquareYard)); + unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.UsSurveySquareFoot, quantity => new Area(quantity.Value/0.09290341161, AreaUnit.UsSurveySquareFoot)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMeter, quantity => quantity); // Register in unit converter: AreaUnit -> BaseUnit - unitConverter.SetConversionFunction(AreaUnit.Acre, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.Hectare, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareCentimeter, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareDecimeter, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareFoot, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareInch, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareKilometer, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareMicrometer, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareMile, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareMillimeter, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareNauticalMile, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.SquareYard, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaUnit.UsSurveySquareFoot, AreaUnit.SquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(AreaUnit.Acre, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*4046.85642, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.Hectare, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*1e4, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareCentimeter, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*1e-4, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareDecimeter, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*1e-2, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareFoot, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*0.092903, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareInch, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*0.00064516, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareKilometer, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*1e6, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareMicrometer, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*1e-12, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareMile, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*2.59e6, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareMillimeter, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*1e-6, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareNauticalMile, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*3429904, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.SquareYard, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*0.836127, AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction(AreaUnit.UsSurveySquareFoot, AreaUnit.SquareMeter, quantity => new Area(quantity.Value*0.09290341161, AreaUnit.SquareMeter)); } /// @@ -837,11 +844,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Area to another Area with the unit representation . /// + /// The unit to convert to. /// A Area with the specified unit. public Area ToUnit(AreaUnit unit) { - var convertedValue = GetValueAs(unit); - return new Area(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Area to another Area using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Area with the specified unit. + public Area ToUnit(AreaUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Area), Unit, typeof(Area), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Area)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -850,7 +888,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is AreaUnit unitAsAreaUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAreaUnit); + return ToUnit(unitAsAreaUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is AreaUnit unitAsAreaUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsAreaUnit, unitConverter); } /// @@ -875,73 +922,15 @@ public Area ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(AreaUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case AreaUnit.Acre: return _value*4046.85642; - case AreaUnit.Hectare: return _value*1e4; - case AreaUnit.SquareCentimeter: return _value*1e-4; - case AreaUnit.SquareDecimeter: return _value*1e-2; - case AreaUnit.SquareFoot: return _value*0.092903; - case AreaUnit.SquareInch: return _value*0.00064516; - case AreaUnit.SquareKilometer: return _value*1e6; - case AreaUnit.SquareMeter: return _value; - case AreaUnit.SquareMicrometer: return _value*1e-12; - case AreaUnit.SquareMile: return _value*2.59e6; - case AreaUnit.SquareMillimeter: return _value*1e-6; - case AreaUnit.SquareNauticalMile: return _value*3429904; - case AreaUnit.SquareYard: return _value*0.836127; - case AreaUnit.UsSurveySquareFoot: return _value*0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(AreaUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Area ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Area(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(AreaUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case AreaUnit.Acre: return baseUnitValue/4046.85642; - case AreaUnit.Hectare: return baseUnitValue/1e4; - case AreaUnit.SquareCentimeter: return baseUnitValue/1e-4; - case AreaUnit.SquareDecimeter: return baseUnitValue/1e-2; - case AreaUnit.SquareFoot: return baseUnitValue/0.092903; - case AreaUnit.SquareInch: return baseUnitValue/0.00064516; - case AreaUnit.SquareKilometer: return baseUnitValue/1e6; - case AreaUnit.SquareMeter: return baseUnitValue; - case AreaUnit.SquareMicrometer: return baseUnitValue/1e-12; - case AreaUnit.SquareMile: return baseUnitValue/2.59e6; - case AreaUnit.SquareMillimeter: return baseUnitValue/1e-6; - case AreaUnit.SquareNauticalMile: return baseUnitValue/3429904; - case AreaUnit.SquareYard: return baseUnitValue/0.836127; - case AreaUnit.UsSurveySquareFoot: return baseUnitValue/0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs index 8db47f39ac..3915eb7e03 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs @@ -65,6 +65,8 @@ static AreaDensity() new UnitInfo(AreaDensityUnit.KilogramPerSquareMeter, "KilogramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram)), }, BaseUnit, Zero, BaseDimensions, QuantityType.AreaDensity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -103,6 +105,11 @@ public AreaDensity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -616,11 +623,42 @@ double IQuantity.As(Enum unit) /// /// Converts this AreaDensity to another AreaDensity with the unit representation . /// + /// The unit to convert to. /// A AreaDensity with the specified unit. public AreaDensity ToUnit(AreaDensityUnit unit) { - var convertedValue = GetValueAs(unit); - return new AreaDensity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this AreaDensity to another AreaDensity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A AreaDensity with the specified unit. + public AreaDensity ToUnit(AreaDensityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(AreaDensity), Unit, typeof(AreaDensity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (AreaDensity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -629,7 +667,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is AreaDensityUnit unitAsAreaDensityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAreaDensityUnit); + return ToUnit(unitAsAreaDensityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is AreaDensityUnit unitAsAreaDensityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsAreaDensityUnit, unitConverter); } /// @@ -654,47 +701,15 @@ public AreaDensity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(AreaDensityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case AreaDensityUnit.KilogramPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(AreaDensityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal AreaDensity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new AreaDensity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(AreaDensityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case AreaDensityUnit.KilogramPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs index 9aa93d1ee8..5644e5dda7 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs @@ -70,6 +70,8 @@ static AreaMomentOfInertia() new UnitInfo(AreaMomentOfInertiaUnit.MillimeterToTheFourth, "MillimetersToTheFourth", new BaseUnits(length: LengthUnit.Millimeter)), }, BaseUnit, Zero, BaseDimensions, QuantityType.AreaMomentOfInertia); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -108,6 +110,11 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -225,21 +232,21 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> AreaMomentOfInertiaUnit - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.CentimeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.CentimeterToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.DecimeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.DecimeterToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.FootToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.FootToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.InchToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.InchToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.MillimeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MillimeterToTheFourth)); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.CentimeterToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value*1e8, AreaMomentOfInertiaUnit.CentimeterToTheFourth)); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.DecimeterToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value*1e4, AreaMomentOfInertiaUnit.DecimeterToTheFourth)); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.FootToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value/Math.Pow(0.3048, 4), AreaMomentOfInertiaUnit.FootToTheFourth)); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.InchToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value/Math.Pow(2.54e-2, 4), AreaMomentOfInertiaUnit.InchToTheFourth)); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.MillimeterToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value*1e12, AreaMomentOfInertiaUnit.MillimeterToTheFourth)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity); // Register in unit converter: AreaMomentOfInertiaUnit -> BaseUnit - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.CentimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.DecimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.FootToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.InchToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MillimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.CentimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value/1e8, AreaMomentOfInertiaUnit.MeterToTheFourth)); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.DecimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value/1e4, AreaMomentOfInertiaUnit.MeterToTheFourth)); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.FootToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value*Math.Pow(0.3048, 4), AreaMomentOfInertiaUnit.MeterToTheFourth)); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.InchToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value*Math.Pow(2.54e-2, 4), AreaMomentOfInertiaUnit.MeterToTheFourth)); + unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MillimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => new AreaMomentOfInertia(quantity.Value/1e12, AreaMomentOfInertiaUnit.MeterToTheFourth)); } /// @@ -701,11 +708,42 @@ double IQuantity.As(Enum unit) /// /// Converts this AreaMomentOfInertia to another AreaMomentOfInertia with the unit representation . /// + /// The unit to convert to. /// A AreaMomentOfInertia with the specified unit. public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) { - var convertedValue = GetValueAs(unit); - return new AreaMomentOfInertia(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this AreaMomentOfInertia to another AreaMomentOfInertia using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A AreaMomentOfInertia with the specified unit. + public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(AreaMomentOfInertia), Unit, typeof(AreaMomentOfInertia), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (AreaMomentOfInertia)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -714,7 +752,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is AreaMomentOfInertiaUnit unitAsAreaMomentOfInertiaUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaMomentOfInertiaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAreaMomentOfInertiaUnit); + return ToUnit(unitAsAreaMomentOfInertiaUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is AreaMomentOfInertiaUnit unitAsAreaMomentOfInertiaUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaMomentOfInertiaUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsAreaMomentOfInertiaUnit, unitConverter); } /// @@ -739,57 +786,15 @@ public AreaMomentOfInertia ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(AreaMomentOfInertiaUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return _value/1e8; - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return _value/1e4; - case AreaMomentOfInertiaUnit.FootToTheFourth: return _value*Math.Pow(0.3048, 4); - case AreaMomentOfInertiaUnit.InchToTheFourth: return _value*Math.Pow(2.54e-2, 4); - case AreaMomentOfInertiaUnit.MeterToTheFourth: return _value; - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return _value/1e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(AreaMomentOfInertiaUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal AreaMomentOfInertia ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new AreaMomentOfInertia(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(AreaMomentOfInertiaUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return baseUnitValue*1e8; - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return baseUnitValue*1e4; - case AreaMomentOfInertiaUnit.FootToTheFourth: return baseUnitValue/Math.Pow(0.3048, 4); - case AreaMomentOfInertiaUnit.InchToTheFourth: return baseUnitValue/Math.Pow(2.54e-2, 4); - case AreaMomentOfInertiaUnit.MeterToTheFourth: return baseUnitValue; - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return baseUnitValue*1e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs index 1c171e6cef..3de47d828b 100644 --- a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs @@ -93,6 +93,8 @@ static BitRate() new UnitInfo(BitRateUnit.TerabytePerSecond, "TerabytesPerSecond", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.BitRate); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -131,6 +133,11 @@ public BitRate(decimal value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -353,61 +360,61 @@ public BitRate(decimal value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> BitRateUnit - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.BytePerSecond, quantity => quantity.ToUnit(BitRateUnit.BytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.ExabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.ExabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExbibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.ExbibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExbibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.ExbibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GibibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.GibibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GibibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.GibibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GigabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.GigabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GigabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.GigabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KibibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.KibibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KibibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.KibibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KilobitPerSecond, quantity => quantity.ToUnit(BitRateUnit.KilobitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KilobytePerSecond, quantity => quantity.ToUnit(BitRateUnit.KilobytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.MebibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.MebibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MegabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.MegabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MegabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.MegabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.PebibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.PebibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PetabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.PetabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PetabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.PetabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.TebibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.TebibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TerabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.TerabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TerabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.TerabytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.BytePerSecond, quantity => new BitRate(quantity.Value/8m, BitRateUnit.BytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExabitPerSecond, quantity => new BitRate((quantity.Value) / 1e18m, BitRateUnit.ExabitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExabytePerSecond, quantity => new BitRate((quantity.Value/8m) / 1e18m, BitRateUnit.ExabytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExbibitPerSecond, quantity => new BitRate((quantity.Value) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.ExbibitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExbibytePerSecond, quantity => new BitRate((quantity.Value/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.ExbibytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GibibitPerSecond, quantity => new BitRate((quantity.Value) / (1024m * 1024 * 1024), BitRateUnit.GibibitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GibibytePerSecond, quantity => new BitRate((quantity.Value/8m) / (1024m * 1024 * 1024), BitRateUnit.GibibytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GigabitPerSecond, quantity => new BitRate((quantity.Value) / 1e9m, BitRateUnit.GigabitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GigabytePerSecond, quantity => new BitRate((quantity.Value/8m) / 1e9m, BitRateUnit.GigabytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KibibitPerSecond, quantity => new BitRate((quantity.Value) / 1024m, BitRateUnit.KibibitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KibibytePerSecond, quantity => new BitRate((quantity.Value/8m) / 1024m, BitRateUnit.KibibytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KilobitPerSecond, quantity => new BitRate((quantity.Value) / 1e3m, BitRateUnit.KilobitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KilobytePerSecond, quantity => new BitRate((quantity.Value/8m) / 1e3m, BitRateUnit.KilobytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MebibitPerSecond, quantity => new BitRate((quantity.Value) / (1024m * 1024), BitRateUnit.MebibitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MebibytePerSecond, quantity => new BitRate((quantity.Value/8m) / (1024m * 1024), BitRateUnit.MebibytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MegabitPerSecond, quantity => new BitRate((quantity.Value) / 1e6m, BitRateUnit.MegabitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MegabytePerSecond, quantity => new BitRate((quantity.Value/8m) / 1e6m, BitRateUnit.MegabytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PebibitPerSecond, quantity => new BitRate((quantity.Value) / (1024m * 1024 * 1024 * 1024 * 1024), BitRateUnit.PebibitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PebibytePerSecond, quantity => new BitRate((quantity.Value/8m) / (1024m * 1024 * 1024 * 1024 * 1024), BitRateUnit.PebibytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PetabitPerSecond, quantity => new BitRate((quantity.Value) / 1e15m, BitRateUnit.PetabitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PetabytePerSecond, quantity => new BitRate((quantity.Value/8m) / 1e15m, BitRateUnit.PetabytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TebibitPerSecond, quantity => new BitRate((quantity.Value) / (1024m * 1024 * 1024 * 1024), BitRateUnit.TebibitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TebibytePerSecond, quantity => new BitRate((quantity.Value/8m) / (1024m * 1024 * 1024 * 1024), BitRateUnit.TebibytePerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TerabitPerSecond, quantity => new BitRate((quantity.Value) / 1e12m, BitRateUnit.TerabitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TerabytePerSecond, quantity => new BitRate((quantity.Value/8m) / 1e12m, BitRateUnit.TerabytePerSecond)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity); // Register in unit converter: BitRateUnit -> BaseUnit - unitConverter.SetConversionFunction(BitRateUnit.BytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.ExabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.ExabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.ExbibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.ExbibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.GibibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.GibibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.GigabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.GigabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.KibibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.KibibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.KilobitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.KilobytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.MebibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.MebibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.MegabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.MegabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.PebibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.PebibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.PetabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.PetabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.TebibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.TebibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.TerabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BitRateUnit.TerabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(BitRateUnit.BytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate(quantity.Value*8m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.ExabitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * 1e18m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.ExabytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * 1e18m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.ExbibitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.ExbibytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.GibibitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * (1024m * 1024 * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.GibibytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * (1024m * 1024 * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.GigabitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * 1e9m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.GigabytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * 1e9m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.KibibitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * 1024m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.KibibytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * 1024m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.KilobitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * 1e3m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.KilobytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * 1e3m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.MebibitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * (1024m * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.MebibytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * (1024m * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.MegabitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * 1e6m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.MegabytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * 1e6m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.PebibitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * (1024m * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.PebibytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * (1024m * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.PetabitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * 1e15m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.PetabytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * 1e15m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.TebibitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * (1024m * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.TebibytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * (1024m * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.TerabitPerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value) * 1e12m, BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction(BitRateUnit.TerabytePerSecond, BitRateUnit.BitPerSecond, quantity => new BitRate((quantity.Value*8m) * 1e12m, BitRateUnit.BitPerSecond)); } /// @@ -1049,11 +1056,42 @@ double IQuantity.As(Enum unit) /// /// Converts this BitRate to another BitRate with the unit representation . /// + /// The unit to convert to. /// A BitRate with the specified unit. public BitRate ToUnit(BitRateUnit unit) { - var convertedValue = GetValueAs(unit); - return new BitRate(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this BitRate to another BitRate using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A BitRate with the specified unit. + public BitRate ToUnit(BitRateUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(BitRate), Unit, typeof(BitRate), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (BitRate)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1062,7 +1100,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is BitRateUnit unitAsBitRateUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BitRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsBitRateUnit); + return ToUnit(unitAsBitRateUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is BitRateUnit unitAsBitRateUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BitRateUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsBitRateUnit, unitConverter); } /// @@ -1087,97 +1134,15 @@ public BitRate ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(BitRateUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private decimal GetValueInBaseUnit() - { - switch(Unit) - { - case BitRateUnit.BitPerSecond: return _value; - case BitRateUnit.BytePerSecond: return _value*8m; - case BitRateUnit.ExabitPerSecond: return (_value) * 1e18m; - case BitRateUnit.ExabytePerSecond: return (_value*8m) * 1e18m; - case BitRateUnit.ExbibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.ExbibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.GibibitPerSecond: return (_value) * (1024m * 1024 * 1024); - case BitRateUnit.GibibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024); - case BitRateUnit.GigabitPerSecond: return (_value) * 1e9m; - case BitRateUnit.GigabytePerSecond: return (_value*8m) * 1e9m; - case BitRateUnit.KibibitPerSecond: return (_value) * 1024m; - case BitRateUnit.KibibytePerSecond: return (_value*8m) * 1024m; - case BitRateUnit.KilobitPerSecond: return (_value) * 1e3m; - case BitRateUnit.KilobytePerSecond: return (_value*8m) * 1e3m; - case BitRateUnit.MebibitPerSecond: return (_value) * (1024m * 1024); - case BitRateUnit.MebibytePerSecond: return (_value*8m) * (1024m * 1024); - case BitRateUnit.MegabitPerSecond: return (_value) * 1e6m; - case BitRateUnit.MegabytePerSecond: return (_value*8m) * 1e6m; - case BitRateUnit.PebibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PebibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PetabitPerSecond: return (_value) * 1e15m; - case BitRateUnit.PetabytePerSecond: return (_value*8m) * 1e15m; - case BitRateUnit.TebibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TebibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TerabitPerSecond: return (_value) * 1e12m; - case BitRateUnit.TerabytePerSecond: return (_value*8m) * 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(BitRateUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal BitRate ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new BitRate(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private decimal GetValueAs(BitRateUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case BitRateUnit.BitPerSecond: return baseUnitValue; - case BitRateUnit.BytePerSecond: return baseUnitValue/8m; - case BitRateUnit.ExabitPerSecond: return (baseUnitValue) / 1e18m; - case BitRateUnit.ExabytePerSecond: return (baseUnitValue/8m) / 1e18m; - case BitRateUnit.ExbibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.ExbibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.GibibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024); - case BitRateUnit.GibibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024); - case BitRateUnit.GigabitPerSecond: return (baseUnitValue) / 1e9m; - case BitRateUnit.GigabytePerSecond: return (baseUnitValue/8m) / 1e9m; - case BitRateUnit.KibibitPerSecond: return (baseUnitValue) / 1024m; - case BitRateUnit.KibibytePerSecond: return (baseUnitValue/8m) / 1024m; - case BitRateUnit.KilobitPerSecond: return (baseUnitValue) / 1e3m; - case BitRateUnit.KilobytePerSecond: return (baseUnitValue/8m) / 1e3m; - case BitRateUnit.MebibitPerSecond: return (baseUnitValue) / (1024m * 1024); - case BitRateUnit.MebibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024); - case BitRateUnit.MegabitPerSecond: return (baseUnitValue) / 1e6m; - case BitRateUnit.MegabytePerSecond: return (baseUnitValue/8m) / 1e6m; - case BitRateUnit.PebibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PebibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PetabitPerSecond: return (baseUnitValue) / 1e15m; - case BitRateUnit.PetabytePerSecond: return (baseUnitValue/8m) / 1e15m; - case BitRateUnit.TebibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TebibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TerabitPerSecond: return (baseUnitValue) / 1e12m; - case BitRateUnit.TerabytePerSecond: return (baseUnitValue/8m) / 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (decimal)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs index c7f2574619..c89db18280 100644 --- a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs @@ -67,6 +67,8 @@ static BrakeSpecificFuelConsumption() new UnitInfo(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, "PoundsPerMechanicalHorsepowerHour", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.BrakeSpecificFuelConsumption); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -105,6 +107,11 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -207,15 +214,15 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> BrakeSpecificFuelConsumptionUnit - unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour)); - unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour)); + unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, quantity => new BrakeSpecificFuelConsumption(quantity.Value*3.6e9, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour)); + unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, quantity => new BrakeSpecificFuelConsumption(quantity.Value/1.689659410672e-7, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => quantity); // Register in unit converter: BrakeSpecificFuelConsumptionUnit -> BaseUnit - unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => new BrakeSpecificFuelConsumption(quantity.Value/3.6e9, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule)); + unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => new BrakeSpecificFuelConsumption(quantity.Value*1.689659410672e-7, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule)); } /// @@ -650,11 +657,42 @@ double IQuantity.As(Enum unit) /// /// Converts this BrakeSpecificFuelConsumption to another BrakeSpecificFuelConsumption with the unit representation . /// + /// The unit to convert to. /// A BrakeSpecificFuelConsumption with the specified unit. public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) { - var convertedValue = GetValueAs(unit); - return new BrakeSpecificFuelConsumption(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this BrakeSpecificFuelConsumption to another BrakeSpecificFuelConsumption using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A BrakeSpecificFuelConsumption with the specified unit. + public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(BrakeSpecificFuelConsumption), Unit, typeof(BrakeSpecificFuelConsumption), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (BrakeSpecificFuelConsumption)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -663,7 +701,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is BrakeSpecificFuelConsumptionUnit unitAsBrakeSpecificFuelConsumptionUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BrakeSpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsBrakeSpecificFuelConsumptionUnit); + return ToUnit(unitAsBrakeSpecificFuelConsumptionUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is BrakeSpecificFuelConsumptionUnit unitAsBrakeSpecificFuelConsumptionUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BrakeSpecificFuelConsumptionUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsBrakeSpecificFuelConsumptionUnit, unitConverter); } /// @@ -688,51 +735,15 @@ public BrakeSpecificFuelConsumption ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(BrakeSpecificFuelConsumptionUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return _value/3.6e9; - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return _value; - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return _value*1.689659410672e-7; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(BrakeSpecificFuelConsumptionUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal BrakeSpecificFuelConsumption ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new BrakeSpecificFuelConsumption(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(BrakeSpecificFuelConsumptionUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return baseUnitValue*3.6e9; - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return baseUnitValue; - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return baseUnitValue/1.689659410672e-7; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs index 02dd405b37..137371654b 100644 --- a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs @@ -74,6 +74,8 @@ static Capacitance() new UnitInfo(CapacitanceUnit.Picofarad, "Picofarads", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Capacitance); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -112,6 +114,11 @@ public Capacitance(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -234,23 +241,23 @@ public Capacitance(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> CapacitanceUnit - unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Kilofarad, quantity => quantity.ToUnit(CapacitanceUnit.Kilofarad)); - unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Megafarad, quantity => quantity.ToUnit(CapacitanceUnit.Megafarad)); - unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Microfarad, quantity => quantity.ToUnit(CapacitanceUnit.Microfarad)); - unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Millifarad, quantity => quantity.ToUnit(CapacitanceUnit.Millifarad)); - unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Nanofarad, quantity => quantity.ToUnit(CapacitanceUnit.Nanofarad)); - unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Picofarad, quantity => quantity.ToUnit(CapacitanceUnit.Picofarad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Kilofarad, quantity => new Capacitance((quantity.Value) / 1e3d, CapacitanceUnit.Kilofarad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Megafarad, quantity => new Capacitance((quantity.Value) / 1e6d, CapacitanceUnit.Megafarad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Microfarad, quantity => new Capacitance((quantity.Value) / 1e-6d, CapacitanceUnit.Microfarad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Millifarad, quantity => new Capacitance((quantity.Value) / 1e-3d, CapacitanceUnit.Millifarad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Nanofarad, quantity => new Capacitance((quantity.Value) / 1e-9d, CapacitanceUnit.Nanofarad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Picofarad, quantity => new Capacitance((quantity.Value) / 1e-12d, CapacitanceUnit.Picofarad)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(CapacitanceUnit.Farad, CapacitanceUnit.Farad, quantity => quantity); // Register in unit converter: CapacitanceUnit -> BaseUnit - unitConverter.SetConversionFunction(CapacitanceUnit.Kilofarad, CapacitanceUnit.Farad, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(CapacitanceUnit.Megafarad, CapacitanceUnit.Farad, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(CapacitanceUnit.Microfarad, CapacitanceUnit.Farad, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(CapacitanceUnit.Millifarad, CapacitanceUnit.Farad, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(CapacitanceUnit.Nanofarad, CapacitanceUnit.Farad, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(CapacitanceUnit.Picofarad, CapacitanceUnit.Farad, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(CapacitanceUnit.Kilofarad, CapacitanceUnit.Farad, quantity => new Capacitance((quantity.Value) * 1e3d, CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Megafarad, CapacitanceUnit.Farad, quantity => new Capacitance((quantity.Value) * 1e6d, CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Microfarad, CapacitanceUnit.Farad, quantity => new Capacitance((quantity.Value) * 1e-6d, CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Millifarad, CapacitanceUnit.Farad, quantity => new Capacitance((quantity.Value) * 1e-3d, CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Nanofarad, CapacitanceUnit.Farad, quantity => new Capacitance((quantity.Value) * 1e-9d, CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction(CapacitanceUnit.Picofarad, CapacitanceUnit.Farad, quantity => new Capacitance((quantity.Value) * 1e-12d, CapacitanceUnit.Farad)); } /// @@ -721,11 +728,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Capacitance to another Capacitance with the unit representation . /// + /// The unit to convert to. /// A Capacitance with the specified unit. public Capacitance ToUnit(CapacitanceUnit unit) { - var convertedValue = GetValueAs(unit); - return new Capacitance(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Capacitance to another Capacitance using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Capacitance with the specified unit. + public Capacitance ToUnit(CapacitanceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Capacitance), Unit, typeof(Capacitance), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Capacitance)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -734,7 +772,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is CapacitanceUnit unitAsCapacitanceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CapacitanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsCapacitanceUnit); + return ToUnit(unitAsCapacitanceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is CapacitanceUnit unitAsCapacitanceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CapacitanceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsCapacitanceUnit, unitConverter); } /// @@ -759,59 +806,15 @@ public Capacitance ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(CapacitanceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case CapacitanceUnit.Farad: return _value; - case CapacitanceUnit.Kilofarad: return (_value) * 1e3d; - case CapacitanceUnit.Megafarad: return (_value) * 1e6d; - case CapacitanceUnit.Microfarad: return (_value) * 1e-6d; - case CapacitanceUnit.Millifarad: return (_value) * 1e-3d; - case CapacitanceUnit.Nanofarad: return (_value) * 1e-9d; - case CapacitanceUnit.Picofarad: return (_value) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(CapacitanceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Capacitance ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Capacitance(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(CapacitanceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case CapacitanceUnit.Farad: return baseUnitValue; - case CapacitanceUnit.Kilofarad: return (baseUnitValue) / 1e3d; - case CapacitanceUnit.Megafarad: return (baseUnitValue) / 1e6d; - case CapacitanceUnit.Microfarad: return (baseUnitValue) / 1e-6d; - case CapacitanceUnit.Millifarad: return (baseUnitValue) / 1e-3d; - case CapacitanceUnit.Nanofarad: return (baseUnitValue) / 1e-9d; - case CapacitanceUnit.Picofarad: return (baseUnitValue) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs index ef1dc90444..ea35b86766 100644 --- a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs @@ -67,6 +67,8 @@ static CoefficientOfThermalExpansion() new UnitInfo(CoefficientOfThermalExpansionUnit.InverseKelvin, "InverseKelvin", new BaseUnits(temperature: TemperatureUnit.Kelvin)), }, BaseUnit, Zero, BaseDimensions, QuantityType.CoefficientOfThermalExpansion); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -105,6 +107,11 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -207,15 +214,15 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> CoefficientOfThermalExpansionUnit - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius)); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit)); + unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, quantity => new CoefficientOfThermalExpansion(quantity.Value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius)); + unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, quantity => new CoefficientOfThermalExpansion(quantity.Value*5/9, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => quantity); // Register in unit converter: CoefficientOfThermalExpansionUnit -> BaseUnit - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => new CoefficientOfThermalExpansion(quantity.Value, CoefficientOfThermalExpansionUnit.InverseKelvin)); + unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => new CoefficientOfThermalExpansion(quantity.Value*9/5, CoefficientOfThermalExpansionUnit.InverseKelvin)); } /// @@ -650,11 +657,42 @@ double IQuantity.As(Enum unit) /// /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation . /// + /// The unit to convert to. /// A CoefficientOfThermalExpansion with the specified unit. public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) { - var convertedValue = GetValueAs(unit); - return new CoefficientOfThermalExpansion(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A CoefficientOfThermalExpansion with the specified unit. + public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(CoefficientOfThermalExpansion), Unit, typeof(CoefficientOfThermalExpansion), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (CoefficientOfThermalExpansion)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -663,7 +701,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is CoefficientOfThermalExpansionUnit unitAsCoefficientOfThermalExpansionUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsCoefficientOfThermalExpansionUnit); + return ToUnit(unitAsCoefficientOfThermalExpansionUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is CoefficientOfThermalExpansionUnit unitAsCoefficientOfThermalExpansionUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsCoefficientOfThermalExpansionUnit, unitConverter); } /// @@ -688,51 +735,15 @@ public CoefficientOfThermalExpansion ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(CoefficientOfThermalExpansionUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return _value; - case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return _value*9/5; - case CoefficientOfThermalExpansionUnit.InverseKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(CoefficientOfThermalExpansionUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal CoefficientOfThermalExpansion ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new CoefficientOfThermalExpansion(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(CoefficientOfThermalExpansionUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return baseUnitValue; - case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return baseUnitValue*5/9; - case CoefficientOfThermalExpansionUnit.InverseKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Density.g.cs b/UnitsNet/GeneratedCode/Quantities/Density.g.cs index 7eb1494c4d..300d1689f8 100644 --- a/UnitsNet/GeneratedCode/Quantities/Density.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Density.g.cs @@ -118,6 +118,8 @@ static Density() new UnitInfo(DensityUnit.TonnePerCubicMillimeter, "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne)), }, BaseUnit, Zero, BaseDimensions, QuantityType.Density); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -156,6 +158,11 @@ public Density(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -498,111 +505,111 @@ public Density(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> DensityUnit - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.CentigramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerLiter, quantity => quantity.ToUnit(DensityUnit.CentigramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.CentigramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.DecigramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerLiter, quantity => quantity.ToUnit(DensityUnit.DecigramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.DecigramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.GramPerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.GramPerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicInch, quantity => quantity.ToUnit(DensityUnit.GramPerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.GramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.GramPerCubicMillimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.GramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerLiter, quantity => quantity.ToUnit(DensityUnit.GramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.GramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMillimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerLiter, quantity => quantity.ToUnit(DensityUnit.KilogramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.KilopoundPerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicInch, quantity => quantity.ToUnit(DensityUnit.KilopoundPerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerLiter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.MilligramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.MilligramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerLiter, quantity => quantity.ToUnit(DensityUnit.MilligramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.MilligramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.NanogramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerLiter, quantity => quantity.ToUnit(DensityUnit.NanogramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.NanogramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.PicogramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerLiter, quantity => quantity.ToUnit(DensityUnit.PicogramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.PicogramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicInch, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicMillimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerImperialGallon, quantity => quantity.ToUnit(DensityUnit.PoundPerImperialGallon)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerUSGallon, quantity => quantity.ToUnit(DensityUnit.PoundPerUSGallon)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicInch, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicMillimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicFoot, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicInch, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMeter, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicMillimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerDeciliter, quantity => new Density((quantity.Value*1e-1) / 1e-2d, DensityUnit.CentigramPerDeciliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerLiter, quantity => new Density((quantity.Value*1) / 1e-2d, DensityUnit.CentigramPerLiter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerMilliliter, quantity => new Density((quantity.Value*1e-3) / 1e-2d, DensityUnit.CentigramPerMilliliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerDeciliter, quantity => new Density((quantity.Value*1e-1) / 1e-1d, DensityUnit.DecigramPerDeciliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerLiter, quantity => new Density((quantity.Value*1) / 1e-1d, DensityUnit.DecigramPerLiter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerMilliliter, quantity => new Density((quantity.Value*1e-3) / 1e-1d, DensityUnit.DecigramPerMilliliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicCentimeter, quantity => new Density(quantity.Value*1e-3, DensityUnit.GramPerCubicCentimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicFoot, quantity => new Density(quantity.Value/0.0353146667214886, DensityUnit.GramPerCubicFoot)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicInch, quantity => new Density(quantity.Value/61.0237440947323, DensityUnit.GramPerCubicInch)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMeter, quantity => new Density(quantity.Value*1e3, DensityUnit.GramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMillimeter, quantity => new Density(quantity.Value*1e-6, DensityUnit.GramPerCubicMillimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerDeciliter, quantity => new Density(quantity.Value*1e-1, DensityUnit.GramPerDeciliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerLiter, quantity => new Density(quantity.Value*1, DensityUnit.GramPerLiter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerMilliliter, quantity => new Density(quantity.Value*1e-3, DensityUnit.GramPerMilliliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicCentimeter, quantity => new Density((quantity.Value*1e-3) / 1e3d, DensityUnit.KilogramPerCubicCentimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMillimeter, quantity => new Density((quantity.Value*1e-6) / 1e3d, DensityUnit.KilogramPerCubicMillimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerLiter, quantity => new Density(quantity.Value/1e3, DensityUnit.KilogramPerLiter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicFoot, quantity => new Density((quantity.Value*0.062427961) / 1e3d, DensityUnit.KilopoundPerCubicFoot)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicInch, quantity => new Density((quantity.Value*3.6127298147753e-5) / 1e3d, DensityUnit.KilopoundPerCubicInch)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerCubicMeter, quantity => new Density((quantity.Value*1e3) / 1e-6d, DensityUnit.MicrogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerDeciliter, quantity => new Density((quantity.Value*1e-1) / 1e-6d, DensityUnit.MicrogramPerDeciliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerLiter, quantity => new Density((quantity.Value*1) / 1e-6d, DensityUnit.MicrogramPerLiter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerMilliliter, quantity => new Density((quantity.Value*1e-3) / 1e-6d, DensityUnit.MicrogramPerMilliliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerCubicMeter, quantity => new Density((quantity.Value*1e3) / 1e-3d, DensityUnit.MilligramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerDeciliter, quantity => new Density((quantity.Value*1e-1) / 1e-3d, DensityUnit.MilligramPerDeciliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerLiter, quantity => new Density((quantity.Value*1) / 1e-3d, DensityUnit.MilligramPerLiter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerMilliliter, quantity => new Density((quantity.Value*1e-3) / 1e-3d, DensityUnit.MilligramPerMilliliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerDeciliter, quantity => new Density((quantity.Value*1e-1) / 1e-9d, DensityUnit.NanogramPerDeciliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerLiter, quantity => new Density((quantity.Value*1) / 1e-9d, DensityUnit.NanogramPerLiter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerMilliliter, quantity => new Density((quantity.Value*1e-3) / 1e-9d, DensityUnit.NanogramPerMilliliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerDeciliter, quantity => new Density((quantity.Value*1e-1) / 1e-12d, DensityUnit.PicogramPerDeciliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerLiter, quantity => new Density((quantity.Value*1) / 1e-12d, DensityUnit.PicogramPerLiter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerMilliliter, quantity => new Density((quantity.Value*1e-3) / 1e-12d, DensityUnit.PicogramPerMilliliter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicCentimeter, quantity => new Density(quantity.Value*2.204622621848775e-6, DensityUnit.PoundPerCubicCentimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicFoot, quantity => new Density(quantity.Value*0.062427961, DensityUnit.PoundPerCubicFoot)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicInch, quantity => new Density(quantity.Value*3.6127298147753e-5, DensityUnit.PoundPerCubicInch)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMeter, quantity => new Density(quantity.Value*2.204622621848775, DensityUnit.PoundPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMillimeter, quantity => new Density(quantity.Value*2.204622621848775e-9, DensityUnit.PoundPerCubicMillimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerImperialGallon, quantity => new Density(quantity.Value/9.9776398e1, DensityUnit.PoundPerImperialGallon)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerUSGallon, quantity => new Density(quantity.Value/1.19826427e2, DensityUnit.PoundPerUSGallon)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicCentimeter, quantity => new Density(quantity.Value/14593903, DensityUnit.SlugPerCubicCentimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicFoot, quantity => new Density(quantity.Value*0.00194032033, DensityUnit.SlugPerCubicFoot)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicInch, quantity => new Density(quantity.Value/890574.60201535, DensityUnit.SlugPerCubicInch)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMeter, quantity => new Density(quantity.Value/14.5939, DensityUnit.SlugPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMillimeter, quantity => new Density(quantity.Value/14593903000, DensityUnit.SlugPerCubicMillimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicCentimeter, quantity => new Density(quantity.Value*1e-9, DensityUnit.TonnePerCubicCentimeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicFoot, quantity => new Density(quantity.Value/3.53146667214886e4, DensityUnit.TonnePerCubicFoot)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicInch, quantity => new Density(quantity.Value/6.10237440947323e7, DensityUnit.TonnePerCubicInch)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMeter, quantity => new Density(quantity.Value*0.001, DensityUnit.TonnePerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMillimeter, quantity => new Density(quantity.Value*1e-12, DensityUnit.TonnePerCubicMillimeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity); // Register in unit converter: DensityUnit -> BaseUnit - unitConverter.SetConversionFunction(DensityUnit.CentigramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.CentigramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.CentigramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.DecigramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.DecigramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.DecigramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.GramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.GramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.GramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.KilopoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.KilopoundPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.MicrogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.MicrogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.MicrogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.MicrogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.MilligramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.MilligramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.MilligramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.MilligramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.NanogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.NanogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.NanogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PicogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PicogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PicogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PoundPerImperialGallon, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(DensityUnit.CentigramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-1) * 1e-2d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.CentigramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1) * 1e-2d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.CentigramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-3) * 1e-2d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.DecigramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-1) * 1e-1d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.DecigramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1) * 1e-1d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.DecigramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-3) * 1e-1d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.GramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/1e-3, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.GramPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*0.0353146667214886, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.GramPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*61.0237440947323, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.GramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/1e3, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.GramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/1e-6, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.GramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/1e-1, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.GramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/1, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.GramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/1e-3, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-3) * 1e3d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-6) * 1e3d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*1e3, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilopoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/0.062427961) * 1e3d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.KilopoundPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/3.6127298147753e-5) * 1e3d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.MicrogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e3) * 1e-6d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.MicrogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-1) * 1e-6d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.MicrogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1) * 1e-6d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.MicrogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-3) * 1e-6d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.MilligramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e3) * 1e-3d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.MilligramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-1) * 1e-3d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.MilligramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1) * 1e-3d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.MilligramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-3) * 1e-3d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.NanogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-1) * 1e-9d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.NanogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1) * 1e-9d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.NanogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-3) * 1e-9d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PicogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-1) * 1e-12d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PicogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1) * 1e-12d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PicogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => new Density((quantity.Value/1e-3) * 1e-12d, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/2.204622621848775e-6, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/0.062427961, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/3.6127298147753e-5, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/2.204622621848775, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/2.204622621848775e-9, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PoundPerImperialGallon, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*9.9776398e1, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*1.19826427e2, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*14593903, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*515.378818, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*890574.60201535, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*14.5939, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*14593903000, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/1e-9, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*3.53146667214886e4, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value*6.10237440947323e7, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/0.001, DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => new Density(quantity.Value/1e-12, DensityUnit.KilogramPerCubicMeter)); } /// @@ -1469,11 +1476,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Density to another Density with the unit representation . /// + /// The unit to convert to. /// A Density with the specified unit. public Density ToUnit(DensityUnit unit) { - var convertedValue = GetValueAs(unit); - return new Density(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Density to another Density using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Density with the specified unit. + public Density ToUnit(DensityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Density), Unit, typeof(Density), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Density)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1482,7 +1520,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is DensityUnit unitAsDensityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsDensityUnit); + return ToUnit(unitAsDensityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is DensityUnit unitAsDensityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DensityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsDensityUnit, unitConverter); } /// @@ -1507,147 +1554,15 @@ public Density ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(DensityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case DensityUnit.CentigramPerDeciliter: return (_value/1e-1) * 1e-2d; - case DensityUnit.CentigramPerLiter: return (_value/1) * 1e-2d; - case DensityUnit.CentigramPerMilliliter: return (_value/1e-3) * 1e-2d; - case DensityUnit.DecigramPerDeciliter: return (_value/1e-1) * 1e-1d; - case DensityUnit.DecigramPerLiter: return (_value/1) * 1e-1d; - case DensityUnit.DecigramPerMilliliter: return (_value/1e-3) * 1e-1d; - case DensityUnit.GramPerCubicCentimeter: return _value/1e-3; - case DensityUnit.GramPerCubicFoot: return _value*0.0353146667214886; - case DensityUnit.GramPerCubicInch: return _value*61.0237440947323; - case DensityUnit.GramPerCubicMeter: return _value/1e3; - case DensityUnit.GramPerCubicMillimeter: return _value/1e-6; - case DensityUnit.GramPerDeciliter: return _value/1e-1; - case DensityUnit.GramPerLiter: return _value/1; - case DensityUnit.GramPerMilliliter: return _value/1e-3; - case DensityUnit.KilogramPerCubicCentimeter: return (_value/1e-3) * 1e3d; - case DensityUnit.KilogramPerCubicMeter: return (_value/1e3) * 1e3d; - case DensityUnit.KilogramPerCubicMillimeter: return (_value/1e-6) * 1e3d; - case DensityUnit.KilogramPerLiter: return _value*1e3; - case DensityUnit.KilopoundPerCubicFoot: return (_value/0.062427961) * 1e3d; - case DensityUnit.KilopoundPerCubicInch: return (_value/3.6127298147753e-5) * 1e3d; - case DensityUnit.MicrogramPerCubicMeter: return (_value/1e3) * 1e-6d; - case DensityUnit.MicrogramPerDeciliter: return (_value/1e-1) * 1e-6d; - case DensityUnit.MicrogramPerLiter: return (_value/1) * 1e-6d; - case DensityUnit.MicrogramPerMilliliter: return (_value/1e-3) * 1e-6d; - case DensityUnit.MilligramPerCubicMeter: return (_value/1e3) * 1e-3d; - case DensityUnit.MilligramPerDeciliter: return (_value/1e-1) * 1e-3d; - case DensityUnit.MilligramPerLiter: return (_value/1) * 1e-3d; - case DensityUnit.MilligramPerMilliliter: return (_value/1e-3) * 1e-3d; - case DensityUnit.NanogramPerDeciliter: return (_value/1e-1) * 1e-9d; - case DensityUnit.NanogramPerLiter: return (_value/1) * 1e-9d; - case DensityUnit.NanogramPerMilliliter: return (_value/1e-3) * 1e-9d; - case DensityUnit.PicogramPerDeciliter: return (_value/1e-1) * 1e-12d; - case DensityUnit.PicogramPerLiter: return (_value/1) * 1e-12d; - case DensityUnit.PicogramPerMilliliter: return (_value/1e-3) * 1e-12d; - case DensityUnit.PoundPerCubicCentimeter: return _value/2.204622621848775e-6; - case DensityUnit.PoundPerCubicFoot: return _value/0.062427961; - case DensityUnit.PoundPerCubicInch: return _value/3.6127298147753e-5; - case DensityUnit.PoundPerCubicMeter: return _value/2.204622621848775; - case DensityUnit.PoundPerCubicMillimeter: return _value/2.204622621848775e-9; - case DensityUnit.PoundPerImperialGallon: return _value*9.9776398e1; - case DensityUnit.PoundPerUSGallon: return _value*1.19826427e2; - case DensityUnit.SlugPerCubicCentimeter: return _value*14593903; - case DensityUnit.SlugPerCubicFoot: return _value*515.378818; - case DensityUnit.SlugPerCubicInch: return _value*890574.60201535; - case DensityUnit.SlugPerCubicMeter: return _value*14.5939; - case DensityUnit.SlugPerCubicMillimeter: return _value*14593903000; - case DensityUnit.TonnePerCubicCentimeter: return _value/1e-9; - case DensityUnit.TonnePerCubicFoot: return _value*3.53146667214886e4; - case DensityUnit.TonnePerCubicInch: return _value*6.10237440947323e7; - case DensityUnit.TonnePerCubicMeter: return _value/0.001; - case DensityUnit.TonnePerCubicMillimeter: return _value/1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(DensityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Density ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Density(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(DensityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case DensityUnit.CentigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-2d; - case DensityUnit.CentigramPerLiter: return (baseUnitValue*1) / 1e-2d; - case DensityUnit.CentigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-2d; - case DensityUnit.DecigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-1d; - case DensityUnit.DecigramPerLiter: return (baseUnitValue*1) / 1e-1d; - case DensityUnit.DecigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-1d; - case DensityUnit.GramPerCubicCentimeter: return baseUnitValue*1e-3; - case DensityUnit.GramPerCubicFoot: return baseUnitValue/0.0353146667214886; - case DensityUnit.GramPerCubicInch: return baseUnitValue/61.0237440947323; - case DensityUnit.GramPerCubicMeter: return baseUnitValue*1e3; - case DensityUnit.GramPerCubicMillimeter: return baseUnitValue*1e-6; - case DensityUnit.GramPerDeciliter: return baseUnitValue*1e-1; - case DensityUnit.GramPerLiter: return baseUnitValue*1; - case DensityUnit.GramPerMilliliter: return baseUnitValue*1e-3; - case DensityUnit.KilogramPerCubicCentimeter: return (baseUnitValue*1e-3) / 1e3d; - case DensityUnit.KilogramPerCubicMeter: return (baseUnitValue*1e3) / 1e3d; - case DensityUnit.KilogramPerCubicMillimeter: return (baseUnitValue*1e-6) / 1e3d; - case DensityUnit.KilogramPerLiter: return baseUnitValue/1e3; - case DensityUnit.KilopoundPerCubicFoot: return (baseUnitValue*0.062427961) / 1e3d; - case DensityUnit.KilopoundPerCubicInch: return (baseUnitValue*3.6127298147753e-5) / 1e3d; - case DensityUnit.MicrogramPerCubicMeter: return (baseUnitValue*1e3) / 1e-6d; - case DensityUnit.MicrogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-6d; - case DensityUnit.MicrogramPerLiter: return (baseUnitValue*1) / 1e-6d; - case DensityUnit.MicrogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-6d; - case DensityUnit.MilligramPerCubicMeter: return (baseUnitValue*1e3) / 1e-3d; - case DensityUnit.MilligramPerDeciliter: return (baseUnitValue*1e-1) / 1e-3d; - case DensityUnit.MilligramPerLiter: return (baseUnitValue*1) / 1e-3d; - case DensityUnit.MilligramPerMilliliter: return (baseUnitValue*1e-3) / 1e-3d; - case DensityUnit.NanogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-9d; - case DensityUnit.NanogramPerLiter: return (baseUnitValue*1) / 1e-9d; - case DensityUnit.NanogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-9d; - case DensityUnit.PicogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-12d; - case DensityUnit.PicogramPerLiter: return (baseUnitValue*1) / 1e-12d; - case DensityUnit.PicogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-12d; - case DensityUnit.PoundPerCubicCentimeter: return baseUnitValue*2.204622621848775e-6; - case DensityUnit.PoundPerCubicFoot: return baseUnitValue*0.062427961; - case DensityUnit.PoundPerCubicInch: return baseUnitValue*3.6127298147753e-5; - case DensityUnit.PoundPerCubicMeter: return baseUnitValue*2.204622621848775; - case DensityUnit.PoundPerCubicMillimeter: return baseUnitValue*2.204622621848775e-9; - case DensityUnit.PoundPerImperialGallon: return baseUnitValue/9.9776398e1; - case DensityUnit.PoundPerUSGallon: return baseUnitValue/1.19826427e2; - case DensityUnit.SlugPerCubicCentimeter: return baseUnitValue/14593903; - case DensityUnit.SlugPerCubicFoot: return baseUnitValue*0.00194032033; - case DensityUnit.SlugPerCubicInch: return baseUnitValue/890574.60201535; - case DensityUnit.SlugPerCubicMeter: return baseUnitValue/14.5939; - case DensityUnit.SlugPerCubicMillimeter: return baseUnitValue/14593903000; - case DensityUnit.TonnePerCubicCentimeter: return baseUnitValue*1e-9; - case DensityUnit.TonnePerCubicFoot: return baseUnitValue/3.53146667214886e4; - case DensityUnit.TonnePerCubicInch: return baseUnitValue/6.10237440947323e7; - case DensityUnit.TonnePerCubicMeter: return baseUnitValue*0.001; - case DensityUnit.TonnePerCubicMillimeter: return baseUnitValue*1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs index 155a6b91ed..6dfce1e501 100644 --- a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs @@ -75,6 +75,8 @@ static Duration() new UnitInfo(DurationUnit.Year365, "Years365", new BaseUnits(time: DurationUnit.Year365)), }, BaseUnit, Zero, BaseDimensions, QuantityType.Duration); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -113,6 +115,11 @@ public Duration(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -255,31 +262,31 @@ public Duration(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> DurationUnit - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Day, quantity => quantity.ToUnit(DurationUnit.Day)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Hour, quantity => quantity.ToUnit(DurationUnit.Hour)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.JulianYear, quantity => quantity.ToUnit(DurationUnit.JulianYear)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Microsecond, quantity => quantity.ToUnit(DurationUnit.Microsecond)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Millisecond, quantity => quantity.ToUnit(DurationUnit.Millisecond)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Minute, quantity => quantity.ToUnit(DurationUnit.Minute)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Month30, quantity => quantity.ToUnit(DurationUnit.Month30)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Nanosecond, quantity => quantity.ToUnit(DurationUnit.Nanosecond)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Week, quantity => quantity.ToUnit(DurationUnit.Week)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Year365, quantity => quantity.ToUnit(DurationUnit.Year365)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Day, quantity => new Duration(quantity.Value/(24*3600), DurationUnit.Day)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Hour, quantity => new Duration(quantity.Value/3600, DurationUnit.Hour)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.JulianYear, quantity => new Duration(quantity.Value/(365.25*24*3600), DurationUnit.JulianYear)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Microsecond, quantity => new Duration((quantity.Value) / 1e-6d, DurationUnit.Microsecond)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Millisecond, quantity => new Duration((quantity.Value) / 1e-3d, DurationUnit.Millisecond)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Minute, quantity => new Duration(quantity.Value/60, DurationUnit.Minute)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Month30, quantity => new Duration(quantity.Value/(30*24*3600), DurationUnit.Month30)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Nanosecond, quantity => new Duration((quantity.Value) / 1e-9d, DurationUnit.Nanosecond)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Week, quantity => new Duration(quantity.Value/(7*24*3600), DurationUnit.Week)); + unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Year365, quantity => new Duration(quantity.Value/(365*24*3600), DurationUnit.Year365)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Second, quantity => quantity); // Register in unit converter: DurationUnit -> BaseUnit - unitConverter.SetConversionFunction(DurationUnit.Day, DurationUnit.Second, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DurationUnit.Hour, DurationUnit.Second, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DurationUnit.JulianYear, DurationUnit.Second, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DurationUnit.Microsecond, DurationUnit.Second, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DurationUnit.Millisecond, DurationUnit.Second, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DurationUnit.Minute, DurationUnit.Second, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DurationUnit.Month30, DurationUnit.Second, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DurationUnit.Nanosecond, DurationUnit.Second, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DurationUnit.Week, DurationUnit.Second, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DurationUnit.Year365, DurationUnit.Second, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(DurationUnit.Day, DurationUnit.Second, quantity => new Duration(quantity.Value*24*3600, DurationUnit.Second)); + unitConverter.SetConversionFunction(DurationUnit.Hour, DurationUnit.Second, quantity => new Duration(quantity.Value*3600, DurationUnit.Second)); + unitConverter.SetConversionFunction(DurationUnit.JulianYear, DurationUnit.Second, quantity => new Duration(quantity.Value*365.25*24*3600, DurationUnit.Second)); + unitConverter.SetConversionFunction(DurationUnit.Microsecond, DurationUnit.Second, quantity => new Duration((quantity.Value) * 1e-6d, DurationUnit.Second)); + unitConverter.SetConversionFunction(DurationUnit.Millisecond, DurationUnit.Second, quantity => new Duration((quantity.Value) * 1e-3d, DurationUnit.Second)); + unitConverter.SetConversionFunction(DurationUnit.Minute, DurationUnit.Second, quantity => new Duration(quantity.Value*60, DurationUnit.Second)); + unitConverter.SetConversionFunction(DurationUnit.Month30, DurationUnit.Second, quantity => new Duration(quantity.Value*30*24*3600, DurationUnit.Second)); + unitConverter.SetConversionFunction(DurationUnit.Nanosecond, DurationUnit.Second, quantity => new Duration((quantity.Value) * 1e-9d, DurationUnit.Second)); + unitConverter.SetConversionFunction(DurationUnit.Week, DurationUnit.Second, quantity => new Duration(quantity.Value*7*24*3600, DurationUnit.Second)); + unitConverter.SetConversionFunction(DurationUnit.Year365, DurationUnit.Second, quantity => new Duration(quantity.Value*365*24*3600, DurationUnit.Second)); } /// @@ -786,11 +793,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Duration to another Duration with the unit representation . /// + /// The unit to convert to. /// A Duration with the specified unit. public Duration ToUnit(DurationUnit unit) { - var convertedValue = GetValueAs(unit); - return new Duration(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Duration to another Duration using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Duration with the specified unit. + public Duration ToUnit(DurationUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Duration), Unit, typeof(Duration), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Duration)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -799,7 +837,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is DurationUnit unitAsDurationUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DurationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsDurationUnit); + return ToUnit(unitAsDurationUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is DurationUnit unitAsDurationUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DurationUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsDurationUnit, unitConverter); } /// @@ -824,67 +871,15 @@ public Duration ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(DurationUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case DurationUnit.Day: return _value*24*3600; - case DurationUnit.Hour: return _value*3600; - case DurationUnit.JulianYear: return _value*365.25*24*3600; - case DurationUnit.Microsecond: return (_value) * 1e-6d; - case DurationUnit.Millisecond: return (_value) * 1e-3d; - case DurationUnit.Minute: return _value*60; - case DurationUnit.Month30: return _value*30*24*3600; - case DurationUnit.Nanosecond: return (_value) * 1e-9d; - case DurationUnit.Second: return _value; - case DurationUnit.Week: return _value*7*24*3600; - case DurationUnit.Year365: return _value*365*24*3600; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(DurationUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Duration ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Duration(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(DurationUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case DurationUnit.Day: return baseUnitValue/(24*3600); - case DurationUnit.Hour: return baseUnitValue/3600; - case DurationUnit.JulianYear: return baseUnitValue/(365.25*24*3600); - case DurationUnit.Microsecond: return (baseUnitValue) / 1e-6d; - case DurationUnit.Millisecond: return (baseUnitValue) / 1e-3d; - case DurationUnit.Minute: return baseUnitValue/60; - case DurationUnit.Month30: return baseUnitValue/(30*24*3600); - case DurationUnit.Nanosecond: return (baseUnitValue) / 1e-9d; - case DurationUnit.Second: return baseUnitValue; - case DurationUnit.Week: return baseUnitValue/(7*24*3600); - case DurationUnit.Year365: return baseUnitValue/(365*24*3600); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs index 1c7bad757c..27281267bc 100644 --- a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs @@ -77,6 +77,8 @@ static DynamicViscosity() new UnitInfo(DynamicViscosityUnit.Reyn, "Reyns", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.DynamicViscosity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -115,6 +117,11 @@ public DynamicViscosity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -252,29 +259,29 @@ public DynamicViscosity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> DynamicViscosityUnit - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Centipoise, quantity => quantity.ToUnit(DynamicViscosityUnit.Centipoise)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MicropascalSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.MicropascalSecond)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MillipascalSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.MillipascalSecond)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PascalSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.PascalSecond)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Poise, quantity => quantity.ToUnit(DynamicViscosityUnit.Poise)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareFoot, quantity => quantity.ToUnit(DynamicViscosityUnit.PoundForceSecondPerSquareFoot)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareInch, quantity => quantity.ToUnit(DynamicViscosityUnit.PoundForceSecondPerSquareInch)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundPerFootSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.PoundPerFootSecond)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Reyn, quantity => quantity.ToUnit(DynamicViscosityUnit.Reyn)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Centipoise, quantity => new DynamicViscosity((quantity.Value*10) / 1e-2d, DynamicViscosityUnit.Centipoise)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MicropascalSecond, quantity => new DynamicViscosity((quantity.Value) / 1e-6d, DynamicViscosityUnit.MicropascalSecond)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MillipascalSecond, quantity => new DynamicViscosity((quantity.Value) / 1e-3d, DynamicViscosityUnit.MillipascalSecond)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PascalSecond, quantity => new DynamicViscosity(quantity.Value, DynamicViscosityUnit.PascalSecond)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Poise, quantity => new DynamicViscosity(quantity.Value*10, DynamicViscosityUnit.Poise)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareFoot, quantity => new DynamicViscosity(quantity.Value / 4.7880258980335843e1, DynamicViscosityUnit.PoundForceSecondPerSquareFoot)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareInch, quantity => new DynamicViscosity(quantity.Value / 6.8947572931683613e3, DynamicViscosityUnit.PoundForceSecondPerSquareInch)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundPerFootSecond, quantity => new DynamicViscosity(quantity.Value / 1.4881639, DynamicViscosityUnit.PoundPerFootSecond)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Reyn, quantity => new DynamicViscosity(quantity.Value / 6.8947572931683613e3, DynamicViscosityUnit.Reyn)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity); // Register in unit converter: DynamicViscosityUnit -> BaseUnit - unitConverter.SetConversionFunction(DynamicViscosityUnit.Centipoise, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DynamicViscosityUnit.MicropascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DynamicViscosityUnit.MillipascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DynamicViscosityUnit.PascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DynamicViscosityUnit.Poise, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DynamicViscosityUnit.PoundForceSecondPerSquareInch, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DynamicViscosityUnit.PoundPerFootSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(DynamicViscosityUnit.Reyn, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(DynamicViscosityUnit.Centipoise, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => new DynamicViscosity((quantity.Value/10) * 1e-2d, DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.MicropascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => new DynamicViscosity((quantity.Value) * 1e-6d, DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.MillipascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => new DynamicViscosity((quantity.Value) * 1e-3d, DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.PascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => new DynamicViscosity(quantity.Value, DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.Poise, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => new DynamicViscosity(quantity.Value/10, DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => new DynamicViscosity(quantity.Value * 4.7880258980335843e1, DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.PoundForceSecondPerSquareInch, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => new DynamicViscosity(quantity.Value * 6.8947572931683613e3, DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.PoundPerFootSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => new DynamicViscosity(quantity.Value * 1.4881639, DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction(DynamicViscosityUnit.Reyn, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => new DynamicViscosity(quantity.Value * 6.8947572931683613e3, DynamicViscosityUnit.NewtonSecondPerMeterSquared)); } /// @@ -772,11 +779,42 @@ double IQuantity.As(Enum unit) /// /// Converts this DynamicViscosity to another DynamicViscosity with the unit representation . /// + /// The unit to convert to. /// A DynamicViscosity with the specified unit. public DynamicViscosity ToUnit(DynamicViscosityUnit unit) { - var convertedValue = GetValueAs(unit); - return new DynamicViscosity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this DynamicViscosity to another DynamicViscosity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A DynamicViscosity with the specified unit. + public DynamicViscosity ToUnit(DynamicViscosityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(DynamicViscosity), Unit, typeof(DynamicViscosity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (DynamicViscosity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -785,7 +823,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is DynamicViscosityUnit unitAsDynamicViscosityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DynamicViscosityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsDynamicViscosityUnit); + return ToUnit(unitAsDynamicViscosityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is DynamicViscosityUnit unitAsDynamicViscosityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DynamicViscosityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsDynamicViscosityUnit, unitConverter); } /// @@ -810,65 +857,15 @@ public DynamicViscosity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(DynamicViscosityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case DynamicViscosityUnit.Centipoise: return (_value/10) * 1e-2d; - case DynamicViscosityUnit.MicropascalSecond: return (_value) * 1e-6d; - case DynamicViscosityUnit.MillipascalSecond: return (_value) * 1e-3d; - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return _value; - case DynamicViscosityUnit.PascalSecond: return _value; - case DynamicViscosityUnit.Poise: return _value/10; - case DynamicViscosityUnit.PoundForceSecondPerSquareFoot: return _value * 4.7880258980335843e1; - case DynamicViscosityUnit.PoundForceSecondPerSquareInch: return _value * 6.8947572931683613e3; - case DynamicViscosityUnit.PoundPerFootSecond: return _value * 1.4881639; - case DynamicViscosityUnit.Reyn: return _value * 6.8947572931683613e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(DynamicViscosityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal DynamicViscosity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new DynamicViscosity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(DynamicViscosityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case DynamicViscosityUnit.Centipoise: return (baseUnitValue*10) / 1e-2d; - case DynamicViscosityUnit.MicropascalSecond: return (baseUnitValue) / 1e-6d; - case DynamicViscosityUnit.MillipascalSecond: return (baseUnitValue) / 1e-3d; - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return baseUnitValue; - case DynamicViscosityUnit.PascalSecond: return baseUnitValue; - case DynamicViscosityUnit.Poise: return baseUnitValue*10; - case DynamicViscosityUnit.PoundForceSecondPerSquareFoot: return baseUnitValue / 4.7880258980335843e1; - case DynamicViscosityUnit.PoundForceSecondPerSquareInch: return baseUnitValue / 6.8947572931683613e3; - case DynamicViscosityUnit.PoundPerFootSecond: return baseUnitValue / 1.4881639; - case DynamicViscosityUnit.Reyn: return baseUnitValue / 6.8947572931683613e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs index 16321ac532..6dd2c96dc9 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs @@ -68,6 +68,8 @@ static ElectricAdmittance() new UnitInfo(ElectricAdmittanceUnit.Siemens, "Siemens", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricAdmittance); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -213,17 +220,17 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricAdmittanceUnit - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Microsiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Microsiemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Millisiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Millisiemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Nanosiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Nanosiemens)); + unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Microsiemens, quantity => new ElectricAdmittance((quantity.Value) / 1e-6d, ElectricAdmittanceUnit.Microsiemens)); + unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Millisiemens, quantity => new ElectricAdmittance((quantity.Value) / 1e-3d, ElectricAdmittanceUnit.Millisiemens)); + unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Nanosiemens, quantity => new ElectricAdmittance((quantity.Value) / 1e-9d, ElectricAdmittanceUnit.Nanosiemens)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Siemens, quantity => quantity); // Register in unit converter: ElectricAdmittanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Microsiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Millisiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Nanosiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Microsiemens, ElectricAdmittanceUnit.Siemens, quantity => new ElectricAdmittance((quantity.Value) * 1e-6d, ElectricAdmittanceUnit.Siemens)); + unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Millisiemens, ElectricAdmittanceUnit.Siemens, quantity => new ElectricAdmittance((quantity.Value) * 1e-3d, ElectricAdmittanceUnit.Siemens)); + unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Nanosiemens, ElectricAdmittanceUnit.Siemens, quantity => new ElectricAdmittance((quantity.Value) * 1e-9d, ElectricAdmittanceUnit.Siemens)); } /// @@ -667,11 +674,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricAdmittance to another ElectricAdmittance with the unit representation . /// + /// The unit to convert to. /// A ElectricAdmittance with the specified unit. public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricAdmittance(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricAdmittance to another ElectricAdmittance using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricAdmittance with the specified unit. + public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricAdmittance), Unit, typeof(ElectricAdmittance), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricAdmittance)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -680,7 +718,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricAdmittanceUnit unitAsElectricAdmittanceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricAdmittanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricAdmittanceUnit); + return ToUnit(unitAsElectricAdmittanceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricAdmittanceUnit unitAsElectricAdmittanceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricAdmittanceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricAdmittanceUnit, unitConverter); } /// @@ -705,53 +752,15 @@ public ElectricAdmittance ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricAdmittanceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricAdmittanceUnit.Microsiemens: return (_value) * 1e-6d; - case ElectricAdmittanceUnit.Millisiemens: return (_value) * 1e-3d; - case ElectricAdmittanceUnit.Nanosiemens: return (_value) * 1e-9d; - case ElectricAdmittanceUnit.Siemens: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricAdmittanceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricAdmittance ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricAdmittance(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricAdmittanceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricAdmittanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; - case ElectricAdmittanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; - case ElectricAdmittanceUnit.Nanosiemens: return (baseUnitValue) / 1e-9d; - case ElectricAdmittanceUnit.Siemens: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs index a8e75ecdb1..c45f4151e7 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs @@ -72,6 +72,8 @@ static ElectricCharge() new UnitInfo(ElectricChargeUnit.MilliampereHour, "MilliampereHours", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricCharge); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -110,6 +112,11 @@ public ElectricCharge(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -222,19 +229,19 @@ public ElectricCharge(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricChargeUnit - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.AmpereHour, quantity => quantity.ToUnit(ElectricChargeUnit.AmpereHour)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.KiloampereHour, quantity => quantity.ToUnit(ElectricChargeUnit.KiloampereHour)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.MegaampereHour, quantity => quantity.ToUnit(ElectricChargeUnit.MegaampereHour)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.MilliampereHour, quantity => quantity.ToUnit(ElectricChargeUnit.MilliampereHour)); + unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.AmpereHour, quantity => new ElectricCharge(quantity.Value*2.77777777777e-4, ElectricChargeUnit.AmpereHour)); + unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.KiloampereHour, quantity => new ElectricCharge((quantity.Value*2.77777777777e-4) / 1e3d, ElectricChargeUnit.KiloampereHour)); + unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.MegaampereHour, quantity => new ElectricCharge((quantity.Value*2.77777777777e-4) / 1e6d, ElectricChargeUnit.MegaampereHour)); + unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.MilliampereHour, quantity => new ElectricCharge((quantity.Value*2.77777777777e-4) / 1e-3d, ElectricChargeUnit.MilliampereHour)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.Coulomb, quantity => quantity); // Register in unit converter: ElectricChargeUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricChargeUnit.AmpereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricChargeUnit.KiloampereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricChargeUnit.MegaampereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricChargeUnit.MilliampereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricChargeUnit.AmpereHour, ElectricChargeUnit.Coulomb, quantity => new ElectricCharge(quantity.Value/2.77777777777e-4, ElectricChargeUnit.Coulomb)); + unitConverter.SetConversionFunction(ElectricChargeUnit.KiloampereHour, ElectricChargeUnit.Coulomb, quantity => new ElectricCharge((quantity.Value/2.77777777777e-4) * 1e3d, ElectricChargeUnit.Coulomb)); + unitConverter.SetConversionFunction(ElectricChargeUnit.MegaampereHour, ElectricChargeUnit.Coulomb, quantity => new ElectricCharge((quantity.Value/2.77777777777e-4) * 1e6d, ElectricChargeUnit.Coulomb)); + unitConverter.SetConversionFunction(ElectricChargeUnit.MilliampereHour, ElectricChargeUnit.Coulomb, quantity => new ElectricCharge((quantity.Value/2.77777777777e-4) * 1e-3d, ElectricChargeUnit.Coulomb)); } /// @@ -687,11 +694,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricCharge to another ElectricCharge with the unit representation . /// + /// The unit to convert to. /// A ElectricCharge with the specified unit. public ElectricCharge ToUnit(ElectricChargeUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricCharge(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricCharge to another ElectricCharge using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricCharge with the specified unit. + public ElectricCharge ToUnit(ElectricChargeUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricCharge), Unit, typeof(ElectricCharge), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricCharge)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -700,7 +738,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricChargeUnit unitAsElectricChargeUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricChargeUnit); + return ToUnit(unitAsElectricChargeUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricChargeUnit unitAsElectricChargeUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricChargeUnit, unitConverter); } /// @@ -725,55 +772,15 @@ public ElectricCharge ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricChargeUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricChargeUnit.AmpereHour: return _value/2.77777777777e-4; - case ElectricChargeUnit.Coulomb: return _value; - case ElectricChargeUnit.KiloampereHour: return (_value/2.77777777777e-4) * 1e3d; - case ElectricChargeUnit.MegaampereHour: return (_value/2.77777777777e-4) * 1e6d; - case ElectricChargeUnit.MilliampereHour: return (_value/2.77777777777e-4) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricChargeUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricCharge ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricCharge(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricChargeUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricChargeUnit.AmpereHour: return baseUnitValue*2.77777777777e-4; - case ElectricChargeUnit.Coulomb: return baseUnitValue; - case ElectricChargeUnit.KiloampereHour: return (baseUnitValue*2.77777777777e-4) / 1e3d; - case ElectricChargeUnit.MegaampereHour: return (baseUnitValue*2.77777777777e-4) / 1e6d; - case ElectricChargeUnit.MilliampereHour: return (baseUnitValue*2.77777777777e-4) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs index 2924adb33f..650ec31e1b 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs @@ -68,6 +68,8 @@ static ElectricChargeDensity() new UnitInfo(ElectricChargeDensityUnit.CoulombPerCubicMeter, "CoulombsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricChargeDensity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricChargeDensity to another ElectricChargeDensity with the unit representation . /// + /// The unit to convert to. /// A ElectricChargeDensity with the specified unit. public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricChargeDensity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricChargeDensity to another ElectricChargeDensity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricChargeDensity with the specified unit. + public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricChargeDensity), Unit, typeof(ElectricChargeDensity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricChargeDensity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricChargeDensityUnit unitAsElectricChargeDensityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricChargeDensityUnit); + return ToUnit(unitAsElectricChargeDensityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricChargeDensityUnit unitAsElectricChargeDensityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricChargeDensityUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public ElectricChargeDensity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricChargeDensityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricChargeDensityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricChargeDensity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricChargeDensity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricChargeDensityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs index 1abb8a59ce..4b0eee43ad 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs @@ -70,6 +70,8 @@ static ElectricConductance() new UnitInfo(ElectricConductanceUnit.Siemens, "Siemens", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricConductance); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -108,6 +110,11 @@ public ElectricConductance(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -210,15 +217,15 @@ public ElectricConductance(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricConductanceUnit - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Microsiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Microsiemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Millisiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Millisiemens)); + unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Microsiemens, quantity => new ElectricConductance((quantity.Value) / 1e-6d, ElectricConductanceUnit.Microsiemens)); + unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Millisiemens, quantity => new ElectricConductance((quantity.Value) / 1e-3d, ElectricConductanceUnit.Millisiemens)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Siemens, quantity => quantity); // Register in unit converter: ElectricConductanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricConductanceUnit.Microsiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Millisiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricConductanceUnit.Microsiemens, ElectricConductanceUnit.Siemens, quantity => new ElectricConductance((quantity.Value) * 1e-6d, ElectricConductanceUnit.Siemens)); + unitConverter.SetConversionFunction(ElectricConductanceUnit.Millisiemens, ElectricConductanceUnit.Siemens, quantity => new ElectricConductance((quantity.Value) * 1e-3d, ElectricConductanceUnit.Siemens)); } /// @@ -653,11 +660,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricConductance to another ElectricConductance with the unit representation . /// + /// The unit to convert to. /// A ElectricConductance with the specified unit. public ElectricConductance ToUnit(ElectricConductanceUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricConductance(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricConductance to another ElectricConductance using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricConductance with the specified unit. + public ElectricConductance ToUnit(ElectricConductanceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricConductance), Unit, typeof(ElectricConductance), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricConductance)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -666,7 +704,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricConductanceUnit unitAsElectricConductanceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricConductanceUnit); + return ToUnit(unitAsElectricConductanceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricConductanceUnit unitAsElectricConductanceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductanceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricConductanceUnit, unitConverter); } /// @@ -691,51 +738,15 @@ public ElectricConductance ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricConductanceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricConductanceUnit.Microsiemens: return (_value) * 1e-6d; - case ElectricConductanceUnit.Millisiemens: return (_value) * 1e-3d; - case ElectricConductanceUnit.Siemens: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricConductanceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricConductance ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricConductance(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricConductanceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricConductanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; - case ElectricConductanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; - case ElectricConductanceUnit.Siemens: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs index 9320255f6c..f1a0603574 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs @@ -70,6 +70,8 @@ static ElectricConductivity() new UnitInfo(ElectricConductivityUnit.SiemensPerMeter, "SiemensPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricConductivity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -108,6 +110,11 @@ public ElectricConductivity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -210,15 +217,15 @@ public ElectricConductivity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricConductivityUnit - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerFoot, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerFoot)); - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerInch, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerInch)); + unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerFoot, quantity => new ElectricConductivity(quantity.Value / 3.2808398950131234, ElectricConductivityUnit.SiemensPerFoot)); + unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerInch, quantity => new ElectricConductivity(quantity.Value / 3.937007874015748e1, ElectricConductivityUnit.SiemensPerInch)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity); // Register in unit converter: ElectricConductivityUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerFoot, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerInch, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerFoot, ElectricConductivityUnit.SiemensPerMeter, quantity => new ElectricConductivity(quantity.Value * 3.2808398950131234, ElectricConductivityUnit.SiemensPerMeter)); + unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerInch, ElectricConductivityUnit.SiemensPerMeter, quantity => new ElectricConductivity(quantity.Value * 3.937007874015748e1, ElectricConductivityUnit.SiemensPerMeter)); } /// @@ -653,11 +660,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricConductivity to another ElectricConductivity with the unit representation . /// + /// The unit to convert to. /// A ElectricConductivity with the specified unit. public ElectricConductivity ToUnit(ElectricConductivityUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricConductivity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricConductivity to another ElectricConductivity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricConductivity with the specified unit. + public ElectricConductivity ToUnit(ElectricConductivityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricConductivity), Unit, typeof(ElectricConductivity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricConductivity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -666,7 +704,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricConductivityUnit unitAsElectricConductivityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductivityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricConductivityUnit); + return ToUnit(unitAsElectricConductivityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricConductivityUnit unitAsElectricConductivityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductivityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricConductivityUnit, unitConverter); } /// @@ -691,51 +738,15 @@ public ElectricConductivity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricConductivityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricConductivityUnit.SiemensPerFoot: return _value * 3.2808398950131234; - case ElectricConductivityUnit.SiemensPerInch: return _value * 3.937007874015748e1; - case ElectricConductivityUnit.SiemensPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricConductivityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricConductivity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricConductivity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricConductivityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricConductivityUnit.SiemensPerFoot: return baseUnitValue / 3.2808398950131234; - case ElectricConductivityUnit.SiemensPerInch: return baseUnitValue / 3.937007874015748e1; - case ElectricConductivityUnit.SiemensPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs index b6e42ab0f6..9058c84dc8 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs @@ -72,6 +72,8 @@ static ElectricCurrent() new UnitInfo(ElectricCurrentUnit.Picoampere, "Picoamperes", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricCurrent); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -110,6 +112,11 @@ public ElectricCurrent(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -237,25 +244,25 @@ public ElectricCurrent(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricCurrentUnit - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Centiampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Centiampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Kiloampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Kiloampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Megaampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Megaampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Microampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Microampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Milliampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Milliampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Nanoampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Nanoampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Picoampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Picoampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Centiampere, quantity => new ElectricCurrent((quantity.Value) / 1e-2d, ElectricCurrentUnit.Centiampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Kiloampere, quantity => new ElectricCurrent((quantity.Value) / 1e3d, ElectricCurrentUnit.Kiloampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Megaampere, quantity => new ElectricCurrent((quantity.Value) / 1e6d, ElectricCurrentUnit.Megaampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Microampere, quantity => new ElectricCurrent((quantity.Value) / 1e-6d, ElectricCurrentUnit.Microampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Milliampere, quantity => new ElectricCurrent((quantity.Value) / 1e-3d, ElectricCurrentUnit.Milliampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Nanoampere, quantity => new ElectricCurrent((quantity.Value) / 1e-9d, ElectricCurrentUnit.Nanoampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Picoampere, quantity => new ElectricCurrent((quantity.Value) / 1e-12d, ElectricCurrentUnit.Picoampere)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Ampere, quantity => quantity); // Register in unit converter: ElectricCurrentUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricCurrentUnit.Centiampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Kiloampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Megaampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Microampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Milliampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Nanoampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Picoampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Centiampere, ElectricCurrentUnit.Ampere, quantity => new ElectricCurrent((quantity.Value) * 1e-2d, ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Kiloampere, ElectricCurrentUnit.Ampere, quantity => new ElectricCurrent((quantity.Value) * 1e3d, ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Megaampere, ElectricCurrentUnit.Ampere, quantity => new ElectricCurrent((quantity.Value) * 1e6d, ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Microampere, ElectricCurrentUnit.Ampere, quantity => new ElectricCurrent((quantity.Value) * 1e-6d, ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Milliampere, ElectricCurrentUnit.Ampere, quantity => new ElectricCurrent((quantity.Value) * 1e-3d, ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Nanoampere, ElectricCurrentUnit.Ampere, quantity => new ElectricCurrent((quantity.Value) * 1e-9d, ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction(ElectricCurrentUnit.Picoampere, ElectricCurrentUnit.Ampere, quantity => new ElectricCurrent((quantity.Value) * 1e-12d, ElectricCurrentUnit.Ampere)); } /// @@ -735,11 +742,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricCurrent to another ElectricCurrent with the unit representation . /// + /// The unit to convert to. /// A ElectricCurrent with the specified unit. public ElectricCurrent ToUnit(ElectricCurrentUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricCurrent(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricCurrent to another ElectricCurrent using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricCurrent with the specified unit. + public ElectricCurrent ToUnit(ElectricCurrentUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricCurrent), Unit, typeof(ElectricCurrent), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricCurrent)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -748,7 +786,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricCurrentUnit unitAsElectricCurrentUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricCurrentUnit); + return ToUnit(unitAsElectricCurrentUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricCurrentUnit unitAsElectricCurrentUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricCurrentUnit, unitConverter); } /// @@ -773,61 +820,15 @@ public ElectricCurrent ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricCurrentUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricCurrentUnit.Ampere: return _value; - case ElectricCurrentUnit.Centiampere: return (_value) * 1e-2d; - case ElectricCurrentUnit.Kiloampere: return (_value) * 1e3d; - case ElectricCurrentUnit.Megaampere: return (_value) * 1e6d; - case ElectricCurrentUnit.Microampere: return (_value) * 1e-6d; - case ElectricCurrentUnit.Milliampere: return (_value) * 1e-3d; - case ElectricCurrentUnit.Nanoampere: return (_value) * 1e-9d; - case ElectricCurrentUnit.Picoampere: return (_value) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricCurrentUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricCurrent ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricCurrent(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricCurrentUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricCurrentUnit.Ampere: return baseUnitValue; - case ElectricCurrentUnit.Centiampere: return (baseUnitValue) / 1e-2d; - case ElectricCurrentUnit.Kiloampere: return (baseUnitValue) / 1e3d; - case ElectricCurrentUnit.Megaampere: return (baseUnitValue) / 1e6d; - case ElectricCurrentUnit.Microampere: return (baseUnitValue) / 1e-6d; - case ElectricCurrentUnit.Milliampere: return (baseUnitValue) / 1e-3d; - case ElectricCurrentUnit.Nanoampere: return (baseUnitValue) / 1e-9d; - case ElectricCurrentUnit.Picoampere: return (baseUnitValue) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs index 4ad4174750..d56c032e32 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs @@ -70,6 +70,8 @@ static ElectricCurrentDensity() new UnitInfo(ElectricCurrentDensityUnit.AmperePerSquareMeter, "AmperesPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere)), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricCurrentDensity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -108,6 +110,11 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -210,15 +217,15 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricCurrentDensityUnit - unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareFoot, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareFoot)); - unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareInch, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareInch)); + unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareFoot, quantity => new ElectricCurrentDensity(quantity.Value / 1.0763910416709722e1, ElectricCurrentDensityUnit.AmperePerSquareFoot)); + unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareInch, quantity => new ElectricCurrentDensity(quantity.Value / 1.5500031000062000e3, ElectricCurrentDensityUnit.AmperePerSquareInch)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => quantity); // Register in unit converter: ElectricCurrentDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareFoot, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareInch, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareFoot, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => new ElectricCurrentDensity(quantity.Value * 1.0763910416709722e1, ElectricCurrentDensityUnit.AmperePerSquareMeter)); + unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareInch, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => new ElectricCurrentDensity(quantity.Value * 1.5500031000062000e3, ElectricCurrentDensityUnit.AmperePerSquareMeter)); } /// @@ -653,11 +660,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricCurrentDensity to another ElectricCurrentDensity with the unit representation . /// + /// The unit to convert to. /// A ElectricCurrentDensity with the specified unit. public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricCurrentDensity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricCurrentDensity to another ElectricCurrentDensity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricCurrentDensity with the specified unit. + public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricCurrentDensity), Unit, typeof(ElectricCurrentDensity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricCurrentDensity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -666,7 +704,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricCurrentDensityUnit unitAsElectricCurrentDensityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricCurrentDensityUnit); + return ToUnit(unitAsElectricCurrentDensityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricCurrentDensityUnit unitAsElectricCurrentDensityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricCurrentDensityUnit, unitConverter); } /// @@ -691,51 +738,15 @@ public ElectricCurrentDensity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricCurrentDensityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricCurrentDensityUnit.AmperePerSquareFoot: return _value * 1.0763910416709722e1; - case ElectricCurrentDensityUnit.AmperePerSquareInch: return _value * 1.5500031000062000e3; - case ElectricCurrentDensityUnit.AmperePerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricCurrentDensityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricCurrentDensity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricCurrentDensity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricCurrentDensityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricCurrentDensityUnit.AmperePerSquareFoot: return baseUnitValue / 1.0763910416709722e1; - case ElectricCurrentDensityUnit.AmperePerSquareInch: return baseUnitValue / 1.5500031000062000e3; - case ElectricCurrentDensityUnit.AmperePerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs index 539bc909f9..5eb7088c3b 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs @@ -68,6 +68,8 @@ static ElectricCurrentGradient() new UnitInfo(ElectricCurrentGradientUnit.AmperePerSecond, "AmperesPerSecond", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricCurrentGradient); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -213,17 +220,17 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricCurrentGradientUnit - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMicrosecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerMicrosecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMillisecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerMillisecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerNanosecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerNanosecond)); + unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMicrosecond, quantity => new ElectricCurrentGradient(quantity.Value/1E6, ElectricCurrentGradientUnit.AmperePerMicrosecond)); + unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMillisecond, quantity => new ElectricCurrentGradient(quantity.Value/1E3, ElectricCurrentGradientUnit.AmperePerMillisecond)); + unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerNanosecond, quantity => new ElectricCurrentGradient(quantity.Value/1E9, ElectricCurrentGradientUnit.AmperePerNanosecond)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity); // Register in unit converter: ElectricCurrentGradientUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerMicrosecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerMillisecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerNanosecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerMicrosecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => new ElectricCurrentGradient(quantity.Value*1E6, ElectricCurrentGradientUnit.AmperePerSecond)); + unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerMillisecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => new ElectricCurrentGradient(quantity.Value*1E3, ElectricCurrentGradientUnit.AmperePerSecond)); + unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerNanosecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => new ElectricCurrentGradient(quantity.Value*1E9, ElectricCurrentGradientUnit.AmperePerSecond)); } /// @@ -667,11 +674,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricCurrentGradient to another ElectricCurrentGradient with the unit representation . /// + /// The unit to convert to. /// A ElectricCurrentGradient with the specified unit. public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricCurrentGradient(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricCurrentGradient to another ElectricCurrentGradient using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricCurrentGradient with the specified unit. + public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricCurrentGradient), Unit, typeof(ElectricCurrentGradient), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricCurrentGradient)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -680,7 +718,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricCurrentGradientUnit unitAsElectricCurrentGradientUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentGradientUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricCurrentGradientUnit); + return ToUnit(unitAsElectricCurrentGradientUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricCurrentGradientUnit unitAsElectricCurrentGradientUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentGradientUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricCurrentGradientUnit, unitConverter); } /// @@ -705,53 +752,15 @@ public ElectricCurrentGradient ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricCurrentGradientUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricCurrentGradientUnit.AmperePerMicrosecond: return _value*1E6; - case ElectricCurrentGradientUnit.AmperePerMillisecond: return _value*1E3; - case ElectricCurrentGradientUnit.AmperePerNanosecond: return _value*1E9; - case ElectricCurrentGradientUnit.AmperePerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricCurrentGradientUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricCurrentGradient ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricCurrentGradient(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricCurrentGradientUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricCurrentGradientUnit.AmperePerMicrosecond: return baseUnitValue/1E6; - case ElectricCurrentGradientUnit.AmperePerMillisecond: return baseUnitValue/1E3; - case ElectricCurrentGradientUnit.AmperePerNanosecond: return baseUnitValue/1E9; - case ElectricCurrentGradientUnit.AmperePerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs index cd28d7c657..337e64f3a1 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs @@ -68,6 +68,8 @@ static ElectricField() new UnitInfo(ElectricFieldUnit.VoltPerMeter, "VoltsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricField); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public ElectricField(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricField to another ElectricField with the unit representation . /// + /// The unit to convert to. /// A ElectricField with the specified unit. public ElectricField ToUnit(ElectricFieldUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricField(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricField to another ElectricField using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricField with the specified unit. + public ElectricField ToUnit(ElectricFieldUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricField), Unit, typeof(ElectricField), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricField)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricFieldUnit unitAsElectricFieldUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricFieldUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricFieldUnit); + return ToUnit(unitAsElectricFieldUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricFieldUnit unitAsElectricFieldUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricFieldUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricFieldUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public ElectricField ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricFieldUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricFieldUnit.VoltPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricFieldUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricField ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricField(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricFieldUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricFieldUnit.VoltPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs index 09bf63c7d0..dd3409f6c9 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs @@ -71,6 +71,8 @@ static ElectricInductance() new UnitInfo(ElectricInductanceUnit.Nanohenry, "Nanohenries", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricInductance); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -109,6 +111,11 @@ public ElectricInductance(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -216,17 +223,17 @@ public ElectricInductance(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricInductanceUnit - unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Microhenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Microhenry)); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Millihenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Millihenry)); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Nanohenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Nanohenry)); + unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Microhenry, quantity => new ElectricInductance((quantity.Value) / 1e-6d, ElectricInductanceUnit.Microhenry)); + unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Millihenry, quantity => new ElectricInductance((quantity.Value) / 1e-3d, ElectricInductanceUnit.Millihenry)); + unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Nanohenry, quantity => new ElectricInductance((quantity.Value) / 1e-9d, ElectricInductanceUnit.Nanohenry)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Henry, quantity => quantity); // Register in unit converter: ElectricInductanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricInductanceUnit.Microhenry, ElectricInductanceUnit.Henry, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Millihenry, ElectricInductanceUnit.Henry, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Nanohenry, ElectricInductanceUnit.Henry, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricInductanceUnit.Microhenry, ElectricInductanceUnit.Henry, quantity => new ElectricInductance((quantity.Value) * 1e-6d, ElectricInductanceUnit.Henry)); + unitConverter.SetConversionFunction(ElectricInductanceUnit.Millihenry, ElectricInductanceUnit.Henry, quantity => new ElectricInductance((quantity.Value) * 1e-3d, ElectricInductanceUnit.Henry)); + unitConverter.SetConversionFunction(ElectricInductanceUnit.Nanohenry, ElectricInductanceUnit.Henry, quantity => new ElectricInductance((quantity.Value) * 1e-9d, ElectricInductanceUnit.Henry)); } /// @@ -670,11 +677,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricInductance to another ElectricInductance with the unit representation . /// + /// The unit to convert to. /// A ElectricInductance with the specified unit. public ElectricInductance ToUnit(ElectricInductanceUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricInductance(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricInductance to another ElectricInductance using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricInductance with the specified unit. + public ElectricInductance ToUnit(ElectricInductanceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricInductance), Unit, typeof(ElectricInductance), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricInductance)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -683,7 +721,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricInductanceUnit unitAsElectricInductanceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricInductanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricInductanceUnit); + return ToUnit(unitAsElectricInductanceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricInductanceUnit unitAsElectricInductanceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricInductanceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricInductanceUnit, unitConverter); } /// @@ -708,53 +755,15 @@ public ElectricInductance ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricInductanceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricInductanceUnit.Henry: return _value; - case ElectricInductanceUnit.Microhenry: return (_value) * 1e-6d; - case ElectricInductanceUnit.Millihenry: return (_value) * 1e-3d; - case ElectricInductanceUnit.Nanohenry: return (_value) * 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricInductanceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricInductance ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricInductance(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricInductanceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricInductanceUnit.Henry: return baseUnitValue; - case ElectricInductanceUnit.Microhenry: return (baseUnitValue) / 1e-6d; - case ElectricInductanceUnit.Millihenry: return (baseUnitValue) / 1e-3d; - case ElectricInductanceUnit.Nanohenry: return (baseUnitValue) / 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs index aaf1dbc1f7..3d34221b08 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs @@ -69,6 +69,8 @@ static ElectricPotential() new UnitInfo(ElectricPotentialUnit.Volt, "Volts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricPotential); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -107,6 +109,11 @@ public ElectricPotential(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -219,19 +226,19 @@ public ElectricPotential(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricPotentialUnit - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Kilovolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Kilovolt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Megavolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Megavolt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Microvolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Microvolt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Millivolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Millivolt)); + unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Kilovolt, quantity => new ElectricPotential((quantity.Value) / 1e3d, ElectricPotentialUnit.Kilovolt)); + unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Megavolt, quantity => new ElectricPotential((quantity.Value) / 1e6d, ElectricPotentialUnit.Megavolt)); + unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Microvolt, quantity => new ElectricPotential((quantity.Value) / 1e-6d, ElectricPotentialUnit.Microvolt)); + unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Millivolt, quantity => new ElectricPotential((quantity.Value) / 1e-3d, ElectricPotentialUnit.Millivolt)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Volt, quantity => quantity); // Register in unit converter: ElectricPotentialUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricPotentialUnit.Kilovolt, ElectricPotentialUnit.Volt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Megavolt, ElectricPotentialUnit.Volt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Microvolt, ElectricPotentialUnit.Volt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Millivolt, ElectricPotentialUnit.Volt, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricPotentialUnit.Kilovolt, ElectricPotentialUnit.Volt, quantity => new ElectricPotential((quantity.Value) * 1e3d, ElectricPotentialUnit.Volt)); + unitConverter.SetConversionFunction(ElectricPotentialUnit.Megavolt, ElectricPotentialUnit.Volt, quantity => new ElectricPotential((quantity.Value) * 1e6d, ElectricPotentialUnit.Volt)); + unitConverter.SetConversionFunction(ElectricPotentialUnit.Microvolt, ElectricPotentialUnit.Volt, quantity => new ElectricPotential((quantity.Value) * 1e-6d, ElectricPotentialUnit.Volt)); + unitConverter.SetConversionFunction(ElectricPotentialUnit.Millivolt, ElectricPotentialUnit.Volt, quantity => new ElectricPotential((quantity.Value) * 1e-3d, ElectricPotentialUnit.Volt)); } /// @@ -684,11 +691,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricPotential to another ElectricPotential with the unit representation . /// + /// The unit to convert to. /// A ElectricPotential with the specified unit. public ElectricPotential ToUnit(ElectricPotentialUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricPotential(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricPotential to another ElectricPotential using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricPotential with the specified unit. + public ElectricPotential ToUnit(ElectricPotentialUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricPotential), Unit, typeof(ElectricPotential), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricPotential)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -697,7 +735,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricPotentialUnit unitAsElectricPotentialUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricPotentialUnit); + return ToUnit(unitAsElectricPotentialUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricPotentialUnit unitAsElectricPotentialUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricPotentialUnit, unitConverter); } /// @@ -722,55 +769,15 @@ public ElectricPotential ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricPotentialUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricPotentialUnit.Kilovolt: return (_value) * 1e3d; - case ElectricPotentialUnit.Megavolt: return (_value) * 1e6d; - case ElectricPotentialUnit.Microvolt: return (_value) * 1e-6d; - case ElectricPotentialUnit.Millivolt: return (_value) * 1e-3d; - case ElectricPotentialUnit.Volt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricPotentialUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricPotential ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricPotential(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricPotentialUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricPotentialUnit.Kilovolt: return (baseUnitValue) / 1e3d; - case ElectricPotentialUnit.Megavolt: return (baseUnitValue) / 1e6d; - case ElectricPotentialUnit.Microvolt: return (baseUnitValue) / 1e-6d; - case ElectricPotentialUnit.Millivolt: return (baseUnitValue) / 1e-3d; - case ElectricPotentialUnit.Volt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs index 781c6f6391..b9a1b51444 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs @@ -69,6 +69,8 @@ static ElectricPotentialAc() new UnitInfo(ElectricPotentialAcUnit.VoltAc, "VoltsAc", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricPotentialAc); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -107,6 +109,11 @@ public ElectricPotentialAc(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -219,19 +226,19 @@ public ElectricPotentialAc(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricPotentialAcUnit - unitConverter.SetConversionFunction(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.KilovoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.KilovoltAc)); - unitConverter.SetConversionFunction(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MegavoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.MegavoltAc)); - unitConverter.SetConversionFunction(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MicrovoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.MicrovoltAc)); - unitConverter.SetConversionFunction(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MillivoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.MillivoltAc)); + unitConverter.SetConversionFunction(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.KilovoltAc, quantity => new ElectricPotentialAc((quantity.Value) / 1e3d, ElectricPotentialAcUnit.KilovoltAc)); + unitConverter.SetConversionFunction(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MegavoltAc, quantity => new ElectricPotentialAc((quantity.Value) / 1e6d, ElectricPotentialAcUnit.MegavoltAc)); + unitConverter.SetConversionFunction(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MicrovoltAc, quantity => new ElectricPotentialAc((quantity.Value) / 1e-6d, ElectricPotentialAcUnit.MicrovoltAc)); + unitConverter.SetConversionFunction(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MillivoltAc, quantity => new ElectricPotentialAc((quantity.Value) / 1e-3d, ElectricPotentialAcUnit.MillivoltAc)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity); // Register in unit converter: ElectricPotentialAcUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricPotentialAcUnit.KilovoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialAcUnit.MegavoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialAcUnit.MicrovoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialAcUnit.MillivoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricPotentialAcUnit.KilovoltAc, ElectricPotentialAcUnit.VoltAc, quantity => new ElectricPotentialAc((quantity.Value) * 1e3d, ElectricPotentialAcUnit.VoltAc)); + unitConverter.SetConversionFunction(ElectricPotentialAcUnit.MegavoltAc, ElectricPotentialAcUnit.VoltAc, quantity => new ElectricPotentialAc((quantity.Value) * 1e6d, ElectricPotentialAcUnit.VoltAc)); + unitConverter.SetConversionFunction(ElectricPotentialAcUnit.MicrovoltAc, ElectricPotentialAcUnit.VoltAc, quantity => new ElectricPotentialAc((quantity.Value) * 1e-6d, ElectricPotentialAcUnit.VoltAc)); + unitConverter.SetConversionFunction(ElectricPotentialAcUnit.MillivoltAc, ElectricPotentialAcUnit.VoltAc, quantity => new ElectricPotentialAc((quantity.Value) * 1e-3d, ElectricPotentialAcUnit.VoltAc)); } /// @@ -684,11 +691,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricPotentialAc to another ElectricPotentialAc with the unit representation . /// + /// The unit to convert to. /// A ElectricPotentialAc with the specified unit. public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricPotentialAc(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricPotentialAc to another ElectricPotentialAc using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricPotentialAc with the specified unit. + public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricPotentialAc), Unit, typeof(ElectricPotentialAc), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricPotentialAc)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -697,7 +735,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricPotentialAcUnit unitAsElectricPotentialAcUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialAcUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricPotentialAcUnit); + return ToUnit(unitAsElectricPotentialAcUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricPotentialAcUnit unitAsElectricPotentialAcUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialAcUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricPotentialAcUnit, unitConverter); } /// @@ -722,55 +769,15 @@ public ElectricPotentialAc ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricPotentialAcUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricPotentialAcUnit.KilovoltAc: return (_value) * 1e3d; - case ElectricPotentialAcUnit.MegavoltAc: return (_value) * 1e6d; - case ElectricPotentialAcUnit.MicrovoltAc: return (_value) * 1e-6d; - case ElectricPotentialAcUnit.MillivoltAc: return (_value) * 1e-3d; - case ElectricPotentialAcUnit.VoltAc: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricPotentialAcUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricPotentialAc ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricPotentialAc(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricPotentialAcUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricPotentialAcUnit.KilovoltAc: return (baseUnitValue) / 1e3d; - case ElectricPotentialAcUnit.MegavoltAc: return (baseUnitValue) / 1e6d; - case ElectricPotentialAcUnit.MicrovoltAc: return (baseUnitValue) / 1e-6d; - case ElectricPotentialAcUnit.MillivoltAc: return (baseUnitValue) / 1e-3d; - case ElectricPotentialAcUnit.VoltAc: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs index 12e7e64bed..ffdb9ee3ee 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs @@ -84,6 +84,8 @@ static ElectricPotentialChangeRate() new UnitInfo(ElectricPotentialChangeRateUnit.VoltPerSecond, "VoltsPerSeconds", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricPotentialChangeRate); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -122,6 +124,11 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -309,49 +316,49 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricPotentialChangeRateUnit - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerMinute)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerMinute)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerMinute)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerMinute)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerMinute)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerHour, quantity => new ElectricPotentialChangeRate((quantity.Value*3600) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerHour)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, quantity => new ElectricPotentialChangeRate((quantity.Value/1E6) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMinute, quantity => new ElectricPotentialChangeRate((quantity.Value*60) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerMinute)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerHour, quantity => new ElectricPotentialChangeRate((quantity.Value*3600) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerHour)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, quantity => new ElectricPotentialChangeRate((quantity.Value/1E6) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMinute, quantity => new ElectricPotentialChangeRate((quantity.Value*60) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerMinute)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerHour, quantity => new ElectricPotentialChangeRate((quantity.Value*3600) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerHour)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, quantity => new ElectricPotentialChangeRate((quantity.Value/1E6) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMinute, quantity => new ElectricPotentialChangeRate((quantity.Value*60) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerMinute)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerHour, quantity => new ElectricPotentialChangeRate((quantity.Value*3600) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerHour)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, quantity => new ElectricPotentialChangeRate((quantity.Value/1E6) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMinute, quantity => new ElectricPotentialChangeRate((quantity.Value*60) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerMinute)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerHour, quantity => new ElectricPotentialChangeRate(quantity.Value*3600, ElectricPotentialChangeRateUnit.VoltPerHour)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMicrosecond, quantity => new ElectricPotentialChangeRate(quantity.Value/1E6, ElectricPotentialChangeRateUnit.VoltPerMicrosecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMinute, quantity => new ElectricPotentialChangeRate(quantity.Value*60, ElectricPotentialChangeRateUnit.VoltPerMinute)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity); // Register in unit converter: ElectricPotentialChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value/3600) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value*1E6) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value/60) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value/3600) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value*1E6) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value/60) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value/3600) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value*1E6) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value/60) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value/3600) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value*1E6) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value/60) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate((quantity.Value) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate(quantity.Value/3600, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate(quantity.Value*1E6, ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => new ElectricPotentialChangeRate(quantity.Value/60, ElectricPotentialChangeRateUnit.VoltPerSecond)); } /// @@ -939,11 +946,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricPotentialChangeRate to another ElectricPotentialChangeRate with the unit representation . /// + /// The unit to convert to. /// A ElectricPotentialChangeRate with the specified unit. public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricPotentialChangeRate(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricPotentialChangeRate to another ElectricPotentialChangeRate using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricPotentialChangeRate with the specified unit. + public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricPotentialChangeRate), Unit, typeof(ElectricPotentialChangeRate), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricPotentialChangeRate)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -952,7 +990,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricPotentialChangeRateUnit unitAsElectricPotentialChangeRateUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricPotentialChangeRateUnit); + return ToUnit(unitAsElectricPotentialChangeRateUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricPotentialChangeRateUnit unitAsElectricPotentialChangeRateUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricPotentialChangeRateUnit, unitConverter); } /// @@ -977,85 +1024,15 @@ public ElectricPotentialChangeRate ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricPotentialChangeRateUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricPotentialChangeRateUnit.KilovoltPerHour: return (_value/3600) * 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond: return (_value*1E6) * 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerMinute: return (_value/60) * 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerSecond: return (_value) * 1e3d; - case ElectricPotentialChangeRateUnit.MegavoltPerHour: return (_value/3600) * 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond: return (_value*1E6) * 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerMinute: return (_value/60) * 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerSecond: return (_value) * 1e6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerHour: return (_value/3600) * 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond: return (_value*1E6) * 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerMinute: return (_value/60) * 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerSecond: return (_value) * 1e-6d; - case ElectricPotentialChangeRateUnit.MillivoltPerHour: return (_value/3600) * 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond: return (_value*1E6) * 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerMinute: return (_value/60) * 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerSecond: return (_value) * 1e-3d; - case ElectricPotentialChangeRateUnit.VoltPerHour: return _value/3600; - case ElectricPotentialChangeRateUnit.VoltPerMicrosecond: return _value*1E6; - case ElectricPotentialChangeRateUnit.VoltPerMinute: return _value/60; - case ElectricPotentialChangeRateUnit.VoltPerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricPotentialChangeRateUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricPotentialChangeRate ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricPotentialChangeRate(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricPotentialChangeRateUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricPotentialChangeRateUnit.KilovoltPerHour: return (baseUnitValue*3600) / 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond: return (baseUnitValue/1E6) / 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerMinute: return (baseUnitValue*60) / 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerSecond: return (baseUnitValue) / 1e3d; - case ElectricPotentialChangeRateUnit.MegavoltPerHour: return (baseUnitValue*3600) / 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond: return (baseUnitValue/1E6) / 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerMinute: return (baseUnitValue*60) / 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerSecond: return (baseUnitValue) / 1e6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerHour: return (baseUnitValue*3600) / 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond: return (baseUnitValue/1E6) / 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerMinute: return (baseUnitValue*60) / 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerSecond: return (baseUnitValue) / 1e-6d; - case ElectricPotentialChangeRateUnit.MillivoltPerHour: return (baseUnitValue*3600) / 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond: return (baseUnitValue/1E6) / 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerMinute: return (baseUnitValue*60) / 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerSecond: return (baseUnitValue) / 1e-3d; - case ElectricPotentialChangeRateUnit.VoltPerHour: return baseUnitValue*3600; - case ElectricPotentialChangeRateUnit.VoltPerMicrosecond: return baseUnitValue/1E6; - case ElectricPotentialChangeRateUnit.VoltPerMinute: return baseUnitValue*60; - case ElectricPotentialChangeRateUnit.VoltPerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs index e60219f0f1..78f412670a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs @@ -69,6 +69,8 @@ static ElectricPotentialDc() new UnitInfo(ElectricPotentialDcUnit.VoltDc, "VoltsDc", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricPotentialDc); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -107,6 +109,11 @@ public ElectricPotentialDc(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -219,19 +226,19 @@ public ElectricPotentialDc(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricPotentialDcUnit - unitConverter.SetConversionFunction(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.KilovoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.KilovoltDc)); - unitConverter.SetConversionFunction(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MegavoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.MegavoltDc)); - unitConverter.SetConversionFunction(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MicrovoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.MicrovoltDc)); - unitConverter.SetConversionFunction(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MillivoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.MillivoltDc)); + unitConverter.SetConversionFunction(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.KilovoltDc, quantity => new ElectricPotentialDc((quantity.Value) / 1e3d, ElectricPotentialDcUnit.KilovoltDc)); + unitConverter.SetConversionFunction(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MegavoltDc, quantity => new ElectricPotentialDc((quantity.Value) / 1e6d, ElectricPotentialDcUnit.MegavoltDc)); + unitConverter.SetConversionFunction(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MicrovoltDc, quantity => new ElectricPotentialDc((quantity.Value) / 1e-6d, ElectricPotentialDcUnit.MicrovoltDc)); + unitConverter.SetConversionFunction(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MillivoltDc, quantity => new ElectricPotentialDc((quantity.Value) / 1e-3d, ElectricPotentialDcUnit.MillivoltDc)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity); // Register in unit converter: ElectricPotentialDcUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricPotentialDcUnit.KilovoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialDcUnit.MegavoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialDcUnit.MicrovoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricPotentialDcUnit.MillivoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricPotentialDcUnit.KilovoltDc, ElectricPotentialDcUnit.VoltDc, quantity => new ElectricPotentialDc((quantity.Value) * 1e3d, ElectricPotentialDcUnit.VoltDc)); + unitConverter.SetConversionFunction(ElectricPotentialDcUnit.MegavoltDc, ElectricPotentialDcUnit.VoltDc, quantity => new ElectricPotentialDc((quantity.Value) * 1e6d, ElectricPotentialDcUnit.VoltDc)); + unitConverter.SetConversionFunction(ElectricPotentialDcUnit.MicrovoltDc, ElectricPotentialDcUnit.VoltDc, quantity => new ElectricPotentialDc((quantity.Value) * 1e-6d, ElectricPotentialDcUnit.VoltDc)); + unitConverter.SetConversionFunction(ElectricPotentialDcUnit.MillivoltDc, ElectricPotentialDcUnit.VoltDc, quantity => new ElectricPotentialDc((quantity.Value) * 1e-3d, ElectricPotentialDcUnit.VoltDc)); } /// @@ -684,11 +691,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricPotentialDc to another ElectricPotentialDc with the unit representation . /// + /// The unit to convert to. /// A ElectricPotentialDc with the specified unit. public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricPotentialDc(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricPotentialDc to another ElectricPotentialDc using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricPotentialDc with the specified unit. + public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricPotentialDc), Unit, typeof(ElectricPotentialDc), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricPotentialDc)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -697,7 +735,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricPotentialDcUnit unitAsElectricPotentialDcUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialDcUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricPotentialDcUnit); + return ToUnit(unitAsElectricPotentialDcUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricPotentialDcUnit unitAsElectricPotentialDcUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialDcUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricPotentialDcUnit, unitConverter); } /// @@ -722,55 +769,15 @@ public ElectricPotentialDc ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricPotentialDcUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricPotentialDcUnit.KilovoltDc: return (_value) * 1e3d; - case ElectricPotentialDcUnit.MegavoltDc: return (_value) * 1e6d; - case ElectricPotentialDcUnit.MicrovoltDc: return (_value) * 1e-6d; - case ElectricPotentialDcUnit.MillivoltDc: return (_value) * 1e-3d; - case ElectricPotentialDcUnit.VoltDc: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricPotentialDcUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricPotentialDc ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricPotentialDc(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricPotentialDcUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricPotentialDcUnit.KilovoltDc: return (baseUnitValue) / 1e3d; - case ElectricPotentialDcUnit.MegavoltDc: return (baseUnitValue) / 1e6d; - case ElectricPotentialDcUnit.MicrovoltDc: return (baseUnitValue) / 1e-6d; - case ElectricPotentialDcUnit.MillivoltDc: return (baseUnitValue) / 1e-3d; - case ElectricPotentialDcUnit.VoltDc: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs index 2e8bd70510..2e30530e76 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs @@ -70,6 +70,8 @@ static ElectricResistance() new UnitInfo(ElectricResistanceUnit.Ohm, "Ohms", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricResistance); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -108,6 +110,11 @@ public ElectricResistance(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -225,21 +232,21 @@ public ElectricResistance(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricResistanceUnit - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Gigaohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Gigaohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Kiloohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Kiloohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Megaohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Megaohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Microohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Microohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Milliohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Milliohm)); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Gigaohm, quantity => new ElectricResistance((quantity.Value) / 1e9d, ElectricResistanceUnit.Gigaohm)); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Kiloohm, quantity => new ElectricResistance((quantity.Value) / 1e3d, ElectricResistanceUnit.Kiloohm)); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Megaohm, quantity => new ElectricResistance((quantity.Value) / 1e6d, ElectricResistanceUnit.Megaohm)); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Microohm, quantity => new ElectricResistance((quantity.Value) / 1e-6d, ElectricResistanceUnit.Microohm)); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Milliohm, quantity => new ElectricResistance((quantity.Value) / 1e-3d, ElectricResistanceUnit.Milliohm)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Ohm, quantity => quantity); // Register in unit converter: ElectricResistanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricResistanceUnit.Gigaohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Kiloohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Megaohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Microohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Milliohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Gigaohm, ElectricResistanceUnit.Ohm, quantity => new ElectricResistance((quantity.Value) * 1e9d, ElectricResistanceUnit.Ohm)); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Kiloohm, ElectricResistanceUnit.Ohm, quantity => new ElectricResistance((quantity.Value) * 1e3d, ElectricResistanceUnit.Ohm)); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Megaohm, ElectricResistanceUnit.Ohm, quantity => new ElectricResistance((quantity.Value) * 1e6d, ElectricResistanceUnit.Ohm)); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Microohm, ElectricResistanceUnit.Ohm, quantity => new ElectricResistance((quantity.Value) * 1e-6d, ElectricResistanceUnit.Ohm)); + unitConverter.SetConversionFunction(ElectricResistanceUnit.Milliohm, ElectricResistanceUnit.Ohm, quantity => new ElectricResistance((quantity.Value) * 1e-3d, ElectricResistanceUnit.Ohm)); } /// @@ -701,11 +708,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricResistance to another ElectricResistance with the unit representation . /// + /// The unit to convert to. /// A ElectricResistance with the specified unit. public ElectricResistance ToUnit(ElectricResistanceUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricResistance(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricResistance to another ElectricResistance using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricResistance with the specified unit. + public ElectricResistance ToUnit(ElectricResistanceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricResistance), Unit, typeof(ElectricResistance), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricResistance)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -714,7 +752,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricResistanceUnit unitAsElectricResistanceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricResistanceUnit); + return ToUnit(unitAsElectricResistanceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricResistanceUnit unitAsElectricResistanceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricResistanceUnit, unitConverter); } /// @@ -739,57 +786,15 @@ public ElectricResistance ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricResistanceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricResistanceUnit.Gigaohm: return (_value) * 1e9d; - case ElectricResistanceUnit.Kiloohm: return (_value) * 1e3d; - case ElectricResistanceUnit.Megaohm: return (_value) * 1e6d; - case ElectricResistanceUnit.Microohm: return (_value) * 1e-6d; - case ElectricResistanceUnit.Milliohm: return (_value) * 1e-3d; - case ElectricResistanceUnit.Ohm: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricResistanceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricResistance ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricResistance(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricResistanceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricResistanceUnit.Gigaohm: return (baseUnitValue) / 1e9d; - case ElectricResistanceUnit.Kiloohm: return (baseUnitValue) / 1e3d; - case ElectricResistanceUnit.Megaohm: return (baseUnitValue) / 1e6d; - case ElectricResistanceUnit.Microohm: return (baseUnitValue) / 1e-6d; - case ElectricResistanceUnit.Milliohm: return (baseUnitValue) / 1e-3d; - case ElectricResistanceUnit.Ohm: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs index f8dfb06bf7..a627507c7d 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs @@ -81,6 +81,8 @@ static ElectricResistivity() new UnitInfo(ElectricResistivityUnit.PicoohmMeter, "PicoohmMeters", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricResistivity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -119,6 +121,11 @@ public ElectricResistivity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -276,37 +283,37 @@ public ElectricResistivity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricResistivityUnit - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.KiloohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.KiloohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MegaohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MegaohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MicroohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MicroohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MilliohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MilliohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.NanoohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.NanoohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.OhmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.PicoohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.PicoohmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmCentimeter, quantity => new ElectricResistivity((quantity.Value*100) / 1e3d, ElectricResistivityUnit.KiloohmCentimeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmMeter, quantity => new ElectricResistivity((quantity.Value) / 1e3d, ElectricResistivityUnit.KiloohmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmCentimeter, quantity => new ElectricResistivity((quantity.Value*100) / 1e6d, ElectricResistivityUnit.MegaohmCentimeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmMeter, quantity => new ElectricResistivity((quantity.Value) / 1e6d, ElectricResistivityUnit.MegaohmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmCentimeter, quantity => new ElectricResistivity((quantity.Value*100) / 1e-6d, ElectricResistivityUnit.MicroohmCentimeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmMeter, quantity => new ElectricResistivity((quantity.Value) / 1e-6d, ElectricResistivityUnit.MicroohmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmCentimeter, quantity => new ElectricResistivity((quantity.Value*100) / 1e-3d, ElectricResistivityUnit.MilliohmCentimeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmMeter, quantity => new ElectricResistivity((quantity.Value) / 1e-3d, ElectricResistivityUnit.MilliohmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmCentimeter, quantity => new ElectricResistivity((quantity.Value*100) / 1e-9d, ElectricResistivityUnit.NanoohmCentimeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmMeter, quantity => new ElectricResistivity((quantity.Value) / 1e-9d, ElectricResistivityUnit.NanoohmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.OhmCentimeter, quantity => new ElectricResistivity(quantity.Value*100, ElectricResistivityUnit.OhmCentimeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmCentimeter, quantity => new ElectricResistivity((quantity.Value*100) / 1e-12d, ElectricResistivityUnit.PicoohmCentimeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmMeter, quantity => new ElectricResistivity((quantity.Value) / 1e-12d, ElectricResistivityUnit.PicoohmMeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity); // Register in unit converter: ElectricResistivityUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricResistivityUnit.KiloohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.KiloohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MegaohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MegaohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MicroohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MicroohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MilliohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MilliohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.NanoohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.NanoohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.PicoohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricResistivityUnit.PicoohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricResistivityUnit.KiloohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value/100) * 1e3d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.KiloohmMeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value) * 1e3d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.MegaohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value/100) * 1e6d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.MegaohmMeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value) * 1e6d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.MicroohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value/100) * 1e-6d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.MicroohmMeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value) * 1e-6d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.MilliohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value/100) * 1e-3d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.MilliohmMeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value) * 1e-3d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.NanoohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value/100) * 1e-9d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.NanoohmMeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value) * 1e-9d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity(quantity.Value/100, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.PicoohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value/100) * 1e-12d, ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction(ElectricResistivityUnit.PicoohmMeter, ElectricResistivityUnit.OhmMeter, quantity => new ElectricResistivity((quantity.Value) * 1e-12d, ElectricResistivityUnit.OhmMeter)); } /// @@ -840,11 +847,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricResistivity to another ElectricResistivity with the unit representation . /// + /// The unit to convert to. /// A ElectricResistivity with the specified unit. public ElectricResistivity ToUnit(ElectricResistivityUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricResistivity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricResistivity to another ElectricResistivity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricResistivity with the specified unit. + public ElectricResistivity ToUnit(ElectricResistivityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricResistivity), Unit, typeof(ElectricResistivity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricResistivity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -853,7 +891,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricResistivityUnit unitAsElectricResistivityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistivityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricResistivityUnit); + return ToUnit(unitAsElectricResistivityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricResistivityUnit unitAsElectricResistivityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistivityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricResistivityUnit, unitConverter); } /// @@ -878,73 +925,15 @@ public ElectricResistivity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricResistivityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricResistivityUnit.KiloohmCentimeter: return (_value/100) * 1e3d; - case ElectricResistivityUnit.KiloohmMeter: return (_value) * 1e3d; - case ElectricResistivityUnit.MegaohmCentimeter: return (_value/100) * 1e6d; - case ElectricResistivityUnit.MegaohmMeter: return (_value) * 1e6d; - case ElectricResistivityUnit.MicroohmCentimeter: return (_value/100) * 1e-6d; - case ElectricResistivityUnit.MicroohmMeter: return (_value) * 1e-6d; - case ElectricResistivityUnit.MilliohmCentimeter: return (_value/100) * 1e-3d; - case ElectricResistivityUnit.MilliohmMeter: return (_value) * 1e-3d; - case ElectricResistivityUnit.NanoohmCentimeter: return (_value/100) * 1e-9d; - case ElectricResistivityUnit.NanoohmMeter: return (_value) * 1e-9d; - case ElectricResistivityUnit.OhmCentimeter: return _value/100; - case ElectricResistivityUnit.OhmMeter: return _value; - case ElectricResistivityUnit.PicoohmCentimeter: return (_value/100) * 1e-12d; - case ElectricResistivityUnit.PicoohmMeter: return (_value) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricResistivityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricResistivity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricResistivity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricResistivityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricResistivityUnit.KiloohmCentimeter: return (baseUnitValue*100) / 1e3d; - case ElectricResistivityUnit.KiloohmMeter: return (baseUnitValue) / 1e3d; - case ElectricResistivityUnit.MegaohmCentimeter: return (baseUnitValue*100) / 1e6d; - case ElectricResistivityUnit.MegaohmMeter: return (baseUnitValue) / 1e6d; - case ElectricResistivityUnit.MicroohmCentimeter: return (baseUnitValue*100) / 1e-6d; - case ElectricResistivityUnit.MicroohmMeter: return (baseUnitValue) / 1e-6d; - case ElectricResistivityUnit.MilliohmCentimeter: return (baseUnitValue*100) / 1e-3d; - case ElectricResistivityUnit.MilliohmMeter: return (baseUnitValue) / 1e-3d; - case ElectricResistivityUnit.NanoohmCentimeter: return (baseUnitValue*100) / 1e-9d; - case ElectricResistivityUnit.NanoohmMeter: return (baseUnitValue) / 1e-9d; - case ElectricResistivityUnit.OhmCentimeter: return baseUnitValue*100; - case ElectricResistivityUnit.OhmMeter: return baseUnitValue; - case ElectricResistivityUnit.PicoohmCentimeter: return (baseUnitValue*100) / 1e-12d; - case ElectricResistivityUnit.PicoohmMeter: return (baseUnitValue) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs index 0a1e0b9bba..8c11c9f3fa 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs @@ -70,6 +70,8 @@ static ElectricSurfaceChargeDensity() new UnitInfo(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, "CoulombsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, BaseUnit, Zero, BaseDimensions, QuantityType.ElectricSurfaceChargeDensity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -108,6 +110,11 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -210,15 +217,15 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ElectricSurfaceChargeDensityUnit - unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter)); - unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch)); + unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, quantity => new ElectricSurfaceChargeDensity(quantity.Value / 1.0e4, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter)); + unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, quantity => new ElectricSurfaceChargeDensity(quantity.Value / 1.5500031000062000e3, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => quantity); // Register in unit converter: ElectricSurfaceChargeDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => new ElectricSurfaceChargeDensity(quantity.Value * 1.0e4, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter)); + unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => new ElectricSurfaceChargeDensity(quantity.Value * 1.5500031000062000e3, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter)); } /// @@ -653,11 +660,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ElectricSurfaceChargeDensity to another ElectricSurfaceChargeDensity with the unit representation . /// + /// The unit to convert to. /// A ElectricSurfaceChargeDensity with the specified unit. public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit) { - var convertedValue = GetValueAs(unit); - return new ElectricSurfaceChargeDensity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ElectricSurfaceChargeDensity to another ElectricSurfaceChargeDensity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ElectricSurfaceChargeDensity with the specified unit. + public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ElectricSurfaceChargeDensity), Unit, typeof(ElectricSurfaceChargeDensity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ElectricSurfaceChargeDensity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -666,7 +704,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ElectricSurfaceChargeDensityUnit unitAsElectricSurfaceChargeDensityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSurfaceChargeDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricSurfaceChargeDensityUnit); + return ToUnit(unitAsElectricSurfaceChargeDensityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ElectricSurfaceChargeDensityUnit unitAsElectricSurfaceChargeDensityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSurfaceChargeDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsElectricSurfaceChargeDensityUnit, unitConverter); } /// @@ -691,51 +738,15 @@ public ElectricSurfaceChargeDensity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ElectricSurfaceChargeDensityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter: return _value * 1.0e4; - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch: return _value * 1.5500031000062000e3; - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ElectricSurfaceChargeDensityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ElectricSurfaceChargeDensity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ElectricSurfaceChargeDensity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ElectricSurfaceChargeDensityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter: return baseUnitValue / 1.0e4; - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch: return baseUnitValue / 1.5500031000062000e3; - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs index 776544db0f..55ce400bf1 100644 --- a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs @@ -100,6 +100,8 @@ static Energy() new UnitInfo(EnergyUnit.WattHour, "WattHours", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Energy); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -138,6 +140,11 @@ public Energy(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -405,81 +412,81 @@ public Energy(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> EnergyUnit - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.BritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.BritishThermalUnit)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Calorie, quantity => quantity.ToUnit(EnergyUnit.Calorie)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.DecathermEc, quantity => quantity.ToUnit(EnergyUnit.DecathermEc)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.DecathermImperial, quantity => quantity.ToUnit(EnergyUnit.DecathermImperial)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.DecathermUs, quantity => quantity.ToUnit(EnergyUnit.DecathermUs)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ElectronVolt, quantity => quantity.ToUnit(EnergyUnit.ElectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Erg, quantity => quantity.ToUnit(EnergyUnit.Erg)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.FootPound, quantity => quantity.ToUnit(EnergyUnit.FootPound)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigabritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.GigabritishThermalUnit)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigaelectronVolt, quantity => quantity.ToUnit(EnergyUnit.GigaelectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Gigajoule, quantity => quantity.ToUnit(EnergyUnit.Gigajoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigawattDay, quantity => quantity.ToUnit(EnergyUnit.GigawattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigawattHour, quantity => quantity.ToUnit(EnergyUnit.GigawattHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.HorsepowerHour, quantity => quantity.ToUnit(EnergyUnit.HorsepowerHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KilobritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.KilobritishThermalUnit)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Kilocalorie, quantity => quantity.ToUnit(EnergyUnit.Kilocalorie)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KiloelectronVolt, quantity => quantity.ToUnit(EnergyUnit.KiloelectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Kilojoule, quantity => quantity.ToUnit(EnergyUnit.Kilojoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KilowattDay, quantity => quantity.ToUnit(EnergyUnit.KilowattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KilowattHour, quantity => quantity.ToUnit(EnergyUnit.KilowattHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegabritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.MegabritishThermalUnit)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Megacalorie, quantity => quantity.ToUnit(EnergyUnit.Megacalorie)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegaelectronVolt, quantity => quantity.ToUnit(EnergyUnit.MegaelectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Megajoule, quantity => quantity.ToUnit(EnergyUnit.Megajoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegawattDay, quantity => quantity.ToUnit(EnergyUnit.MegawattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegawattHour, quantity => quantity.ToUnit(EnergyUnit.MegawattHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Millijoule, quantity => quantity.ToUnit(EnergyUnit.Millijoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.TeraelectronVolt, quantity => quantity.ToUnit(EnergyUnit.TeraelectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.TerawattDay, quantity => quantity.ToUnit(EnergyUnit.TerawattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.TerawattHour, quantity => quantity.ToUnit(EnergyUnit.TerawattHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ThermEc, quantity => quantity.ToUnit(EnergyUnit.ThermEc)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ThermImperial, quantity => quantity.ToUnit(EnergyUnit.ThermImperial)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ThermUs, quantity => quantity.ToUnit(EnergyUnit.ThermUs)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.WattDay, quantity => quantity.ToUnit(EnergyUnit.WattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.WattHour, quantity => quantity.ToUnit(EnergyUnit.WattHour)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.BritishThermalUnit, quantity => new Energy(quantity.Value/1055.05585262, EnergyUnit.BritishThermalUnit)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Calorie, quantity => new Energy(quantity.Value/4.184, EnergyUnit.Calorie)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.DecathermEc, quantity => new Energy((quantity.Value/1.05505585262e8) / 1e1d, EnergyUnit.DecathermEc)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.DecathermImperial, quantity => new Energy((quantity.Value/1.05505585257348e8) / 1e1d, EnergyUnit.DecathermImperial)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.DecathermUs, quantity => new Energy((quantity.Value/1.054804e8) / 1e1d, EnergyUnit.DecathermUs)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ElectronVolt, quantity => new Energy(quantity.Value/1.602176565e-19, EnergyUnit.ElectronVolt)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Erg, quantity => new Energy(quantity.Value/1e-7, EnergyUnit.Erg)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.FootPound, quantity => new Energy(quantity.Value/1.355817948, EnergyUnit.FootPound)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigabritishThermalUnit, quantity => new Energy((quantity.Value/1055.05585262) / 1e9d, EnergyUnit.GigabritishThermalUnit)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigaelectronVolt, quantity => new Energy((quantity.Value/1.602176565e-19) / 1e9d, EnergyUnit.GigaelectronVolt)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Gigajoule, quantity => new Energy((quantity.Value) / 1e9d, EnergyUnit.Gigajoule)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigawattDay, quantity => new Energy((quantity.Value/(24*3600d)) / 1e9d, EnergyUnit.GigawattDay)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigawattHour, quantity => new Energy((quantity.Value/3600d) / 1e9d, EnergyUnit.GigawattHour)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.HorsepowerHour, quantity => new Energy(quantity.Value/2.6845195377e6, EnergyUnit.HorsepowerHour)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KilobritishThermalUnit, quantity => new Energy((quantity.Value/1055.05585262) / 1e3d, EnergyUnit.KilobritishThermalUnit)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Kilocalorie, quantity => new Energy((quantity.Value/4.184) / 1e3d, EnergyUnit.Kilocalorie)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KiloelectronVolt, quantity => new Energy((quantity.Value/1.602176565e-19) / 1e3d, EnergyUnit.KiloelectronVolt)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Kilojoule, quantity => new Energy((quantity.Value) / 1e3d, EnergyUnit.Kilojoule)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KilowattDay, quantity => new Energy((quantity.Value/(24*3600d)) / 1e3d, EnergyUnit.KilowattDay)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KilowattHour, quantity => new Energy((quantity.Value/3600d) / 1e3d, EnergyUnit.KilowattHour)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegabritishThermalUnit, quantity => new Energy((quantity.Value/1055.05585262) / 1e6d, EnergyUnit.MegabritishThermalUnit)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Megacalorie, quantity => new Energy((quantity.Value/4.184) / 1e6d, EnergyUnit.Megacalorie)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegaelectronVolt, quantity => new Energy((quantity.Value/1.602176565e-19) / 1e6d, EnergyUnit.MegaelectronVolt)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Megajoule, quantity => new Energy((quantity.Value) / 1e6d, EnergyUnit.Megajoule)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegawattDay, quantity => new Energy((quantity.Value/(24*3600d)) / 1e6d, EnergyUnit.MegawattDay)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegawattHour, quantity => new Energy((quantity.Value/3600d) / 1e6d, EnergyUnit.MegawattHour)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Millijoule, quantity => new Energy((quantity.Value) / 1e-3d, EnergyUnit.Millijoule)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.TeraelectronVolt, quantity => new Energy((quantity.Value/1.602176565e-19) / 1e12d, EnergyUnit.TeraelectronVolt)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.TerawattDay, quantity => new Energy((quantity.Value/(24*3600d)) / 1e12d, EnergyUnit.TerawattDay)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.TerawattHour, quantity => new Energy((quantity.Value/3600d) / 1e12d, EnergyUnit.TerawattHour)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ThermEc, quantity => new Energy(quantity.Value/1.05505585262e8, EnergyUnit.ThermEc)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ThermImperial, quantity => new Energy(quantity.Value/1.05505585257348e8, EnergyUnit.ThermImperial)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ThermUs, quantity => new Energy(quantity.Value/1.054804e8, EnergyUnit.ThermUs)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.WattDay, quantity => new Energy(quantity.Value/(24*3600d), EnergyUnit.WattDay)); + unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.WattHour, quantity => new Energy(quantity.Value/3600d, EnergyUnit.WattHour)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Joule, quantity => quantity); // Register in unit converter: EnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(EnergyUnit.BritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.Calorie, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.DecathermEc, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.DecathermImperial, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.DecathermUs, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.ElectronVolt, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.Erg, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.FootPound, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.GigabritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.GigaelectronVolt, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.Gigajoule, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.GigawattDay, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.GigawattHour, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.HorsepowerHour, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.KilobritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.Kilocalorie, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.KiloelectronVolt, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.Kilojoule, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.KilowattDay, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.KilowattHour, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.MegabritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.Megacalorie, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.MegaelectronVolt, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.Megajoule, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.MegawattDay, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.MegawattHour, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.Millijoule, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.TeraelectronVolt, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.TerawattDay, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.TerawattHour, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.ThermEc, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.ThermImperial, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.ThermUs, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.WattDay, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EnergyUnit.WattHour, EnergyUnit.Joule, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(EnergyUnit.BritishThermalUnit, EnergyUnit.Joule, quantity => new Energy(quantity.Value*1055.05585262, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.Calorie, EnergyUnit.Joule, quantity => new Energy(quantity.Value*4.184, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.DecathermEc, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1.05505585262e8) * 1e1d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.DecathermImperial, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1.05505585257348e8) * 1e1d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.DecathermUs, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1.054804e8) * 1e1d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.ElectronVolt, EnergyUnit.Joule, quantity => new Energy(quantity.Value*1.602176565e-19, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.Erg, EnergyUnit.Joule, quantity => new Energy(quantity.Value*1e-7, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.FootPound, EnergyUnit.Joule, quantity => new Energy(quantity.Value*1.355817948, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.GigabritishThermalUnit, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1055.05585262) * 1e9d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.GigaelectronVolt, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1.602176565e-19) * 1e9d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.Gigajoule, EnergyUnit.Joule, quantity => new Energy((quantity.Value) * 1e9d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.GigawattDay, EnergyUnit.Joule, quantity => new Energy((quantity.Value*24*3600d) * 1e9d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.GigawattHour, EnergyUnit.Joule, quantity => new Energy((quantity.Value*3600d) * 1e9d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.HorsepowerHour, EnergyUnit.Joule, quantity => new Energy(quantity.Value*2.6845195377e6, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.KilobritishThermalUnit, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1055.05585262) * 1e3d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.Kilocalorie, EnergyUnit.Joule, quantity => new Energy((quantity.Value*4.184) * 1e3d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.KiloelectronVolt, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1.602176565e-19) * 1e3d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.Kilojoule, EnergyUnit.Joule, quantity => new Energy((quantity.Value) * 1e3d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.KilowattDay, EnergyUnit.Joule, quantity => new Energy((quantity.Value*24*3600d) * 1e3d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.KilowattHour, EnergyUnit.Joule, quantity => new Energy((quantity.Value*3600d) * 1e3d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.MegabritishThermalUnit, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1055.05585262) * 1e6d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.Megacalorie, EnergyUnit.Joule, quantity => new Energy((quantity.Value*4.184) * 1e6d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.MegaelectronVolt, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1.602176565e-19) * 1e6d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.Megajoule, EnergyUnit.Joule, quantity => new Energy((quantity.Value) * 1e6d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.MegawattDay, EnergyUnit.Joule, quantity => new Energy((quantity.Value*24*3600d) * 1e6d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.MegawattHour, EnergyUnit.Joule, quantity => new Energy((quantity.Value*3600d) * 1e6d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.Millijoule, EnergyUnit.Joule, quantity => new Energy((quantity.Value) * 1e-3d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.TeraelectronVolt, EnergyUnit.Joule, quantity => new Energy((quantity.Value*1.602176565e-19) * 1e12d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.TerawattDay, EnergyUnit.Joule, quantity => new Energy((quantity.Value*24*3600d) * 1e12d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.TerawattHour, EnergyUnit.Joule, quantity => new Energy((quantity.Value*3600d) * 1e12d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.ThermEc, EnergyUnit.Joule, quantity => new Energy(quantity.Value*1.05505585262e8, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.ThermImperial, EnergyUnit.Joule, quantity => new Energy(quantity.Value*1.05505585257348e8, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.ThermUs, EnergyUnit.Joule, quantity => new Energy(quantity.Value*1.054804e8, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.WattDay, EnergyUnit.Joule, quantity => new Energy(quantity.Value*24*3600d, EnergyUnit.Joule)); + unitConverter.SetConversionFunction(EnergyUnit.WattHour, EnergyUnit.Joule, quantity => new Energy(quantity.Value*3600d, EnergyUnit.Joule)); } /// @@ -1211,11 +1218,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Energy to another Energy with the unit representation . /// + /// The unit to convert to. /// A Energy with the specified unit. public Energy ToUnit(EnergyUnit unit) { - var convertedValue = GetValueAs(unit); - return new Energy(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Energy to another Energy using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Energy with the specified unit. + public Energy ToUnit(EnergyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Energy), Unit, typeof(Energy), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Energy)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1224,7 +1262,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is EnergyUnit unitAsEnergyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsEnergyUnit); + return ToUnit(unitAsEnergyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is EnergyUnit unitAsEnergyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsEnergyUnit, unitConverter); } /// @@ -1249,117 +1296,15 @@ public Energy ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(EnergyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case EnergyUnit.BritishThermalUnit: return _value*1055.05585262; - case EnergyUnit.Calorie: return _value*4.184; - case EnergyUnit.DecathermEc: return (_value*1.05505585262e8) * 1e1d; - case EnergyUnit.DecathermImperial: return (_value*1.05505585257348e8) * 1e1d; - case EnergyUnit.DecathermUs: return (_value*1.054804e8) * 1e1d; - case EnergyUnit.ElectronVolt: return _value*1.602176565e-19; - case EnergyUnit.Erg: return _value*1e-7; - case EnergyUnit.FootPound: return _value*1.355817948; - case EnergyUnit.GigabritishThermalUnit: return (_value*1055.05585262) * 1e9d; - case EnergyUnit.GigaelectronVolt: return (_value*1.602176565e-19) * 1e9d; - case EnergyUnit.Gigajoule: return (_value) * 1e9d; - case EnergyUnit.GigawattDay: return (_value*24*3600d) * 1e9d; - case EnergyUnit.GigawattHour: return (_value*3600d) * 1e9d; - case EnergyUnit.HorsepowerHour: return _value*2.6845195377e6; - case EnergyUnit.Joule: return _value; - case EnergyUnit.KilobritishThermalUnit: return (_value*1055.05585262) * 1e3d; - case EnergyUnit.Kilocalorie: return (_value*4.184) * 1e3d; - case EnergyUnit.KiloelectronVolt: return (_value*1.602176565e-19) * 1e3d; - case EnergyUnit.Kilojoule: return (_value) * 1e3d; - case EnergyUnit.KilowattDay: return (_value*24*3600d) * 1e3d; - case EnergyUnit.KilowattHour: return (_value*3600d) * 1e3d; - case EnergyUnit.MegabritishThermalUnit: return (_value*1055.05585262) * 1e6d; - case EnergyUnit.Megacalorie: return (_value*4.184) * 1e6d; - case EnergyUnit.MegaelectronVolt: return (_value*1.602176565e-19) * 1e6d; - case EnergyUnit.Megajoule: return (_value) * 1e6d; - case EnergyUnit.MegawattDay: return (_value*24*3600d) * 1e6d; - case EnergyUnit.MegawattHour: return (_value*3600d) * 1e6d; - case EnergyUnit.Millijoule: return (_value) * 1e-3d; - case EnergyUnit.TeraelectronVolt: return (_value*1.602176565e-19) * 1e12d; - case EnergyUnit.TerawattDay: return (_value*24*3600d) * 1e12d; - case EnergyUnit.TerawattHour: return (_value*3600d) * 1e12d; - case EnergyUnit.ThermEc: return _value*1.05505585262e8; - case EnergyUnit.ThermImperial: return _value*1.05505585257348e8; - case EnergyUnit.ThermUs: return _value*1.054804e8; - case EnergyUnit.WattDay: return _value*24*3600d; - case EnergyUnit.WattHour: return _value*3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(EnergyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Energy ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Energy(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(EnergyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case EnergyUnit.BritishThermalUnit: return baseUnitValue/1055.05585262; - case EnergyUnit.Calorie: return baseUnitValue/4.184; - case EnergyUnit.DecathermEc: return (baseUnitValue/1.05505585262e8) / 1e1d; - case EnergyUnit.DecathermImperial: return (baseUnitValue/1.05505585257348e8) / 1e1d; - case EnergyUnit.DecathermUs: return (baseUnitValue/1.054804e8) / 1e1d; - case EnergyUnit.ElectronVolt: return baseUnitValue/1.602176565e-19; - case EnergyUnit.Erg: return baseUnitValue/1e-7; - case EnergyUnit.FootPound: return baseUnitValue/1.355817948; - case EnergyUnit.GigabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e9d; - case EnergyUnit.GigaelectronVolt: return (baseUnitValue/1.602176565e-19) / 1e9d; - case EnergyUnit.Gigajoule: return (baseUnitValue) / 1e9d; - case EnergyUnit.GigawattDay: return (baseUnitValue/(24*3600d)) / 1e9d; - case EnergyUnit.GigawattHour: return (baseUnitValue/3600d) / 1e9d; - case EnergyUnit.HorsepowerHour: return baseUnitValue/2.6845195377e6; - case EnergyUnit.Joule: return baseUnitValue; - case EnergyUnit.KilobritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e3d; - case EnergyUnit.Kilocalorie: return (baseUnitValue/4.184) / 1e3d; - case EnergyUnit.KiloelectronVolt: return (baseUnitValue/1.602176565e-19) / 1e3d; - case EnergyUnit.Kilojoule: return (baseUnitValue) / 1e3d; - case EnergyUnit.KilowattDay: return (baseUnitValue/(24*3600d)) / 1e3d; - case EnergyUnit.KilowattHour: return (baseUnitValue/3600d) / 1e3d; - case EnergyUnit.MegabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e6d; - case EnergyUnit.Megacalorie: return (baseUnitValue/4.184) / 1e6d; - case EnergyUnit.MegaelectronVolt: return (baseUnitValue/1.602176565e-19) / 1e6d; - case EnergyUnit.Megajoule: return (baseUnitValue) / 1e6d; - case EnergyUnit.MegawattDay: return (baseUnitValue/(24*3600d)) / 1e6d; - case EnergyUnit.MegawattHour: return (baseUnitValue/3600d) / 1e6d; - case EnergyUnit.Millijoule: return (baseUnitValue) / 1e-3d; - case EnergyUnit.TeraelectronVolt: return (baseUnitValue/1.602176565e-19) / 1e12d; - case EnergyUnit.TerawattDay: return (baseUnitValue/(24*3600d)) / 1e12d; - case EnergyUnit.TerawattHour: return (baseUnitValue/3600d) / 1e12d; - case EnergyUnit.ThermEc: return baseUnitValue/1.05505585262e8; - case EnergyUnit.ThermImperial: return baseUnitValue/1.05505585257348e8; - case EnergyUnit.ThermUs: return baseUnitValue/1.054804e8; - case EnergyUnit.WattDay: return baseUnitValue/(24*3600d); - case EnergyUnit.WattHour: return baseUnitValue/3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs index 65421e979e..342c252f07 100644 --- a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs @@ -71,6 +71,8 @@ static Entropy() new UnitInfo(EntropyUnit.MegajoulePerKelvin, "MegajoulesPerKelvin", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Entropy); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -109,6 +111,11 @@ public Entropy(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -231,23 +238,23 @@ public Entropy(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> EntropyUnit - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.CaloriePerKelvin, quantity => quantity.ToUnit(EntropyUnit.CaloriePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.JoulePerDegreeCelsius, quantity => quantity.ToUnit(EntropyUnit.JoulePerDegreeCelsius)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.KilocaloriePerKelvin, quantity => quantity.ToUnit(EntropyUnit.KilocaloriePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerDegreeCelsius, quantity => quantity.ToUnit(EntropyUnit.KilojoulePerDegreeCelsius)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.KilojoulePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.MegajoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.MegajoulePerKelvin)); + unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.CaloriePerKelvin, quantity => new Entropy(quantity.Value/4.184, EntropyUnit.CaloriePerKelvin)); + unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.JoulePerDegreeCelsius, quantity => new Entropy(quantity.Value, EntropyUnit.JoulePerDegreeCelsius)); + unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.KilocaloriePerKelvin, quantity => new Entropy((quantity.Value/4.184) / 1e3d, EntropyUnit.KilocaloriePerKelvin)); + unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerDegreeCelsius, quantity => new Entropy((quantity.Value) / 1e3d, EntropyUnit.KilojoulePerDegreeCelsius)); + unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerKelvin, quantity => new Entropy((quantity.Value) / 1e3d, EntropyUnit.KilojoulePerKelvin)); + unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.MegajoulePerKelvin, quantity => new Entropy((quantity.Value) / 1e6d, EntropyUnit.MegajoulePerKelvin)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity); // Register in unit converter: EntropyUnit -> BaseUnit - unitConverter.SetConversionFunction(EntropyUnit.CaloriePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EntropyUnit.KilocaloriePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EntropyUnit.KilojoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EntropyUnit.KilojoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(EntropyUnit.MegajoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(EntropyUnit.CaloriePerKelvin, EntropyUnit.JoulePerKelvin, quantity => new Entropy(quantity.Value*4.184, EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction(EntropyUnit.JoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin, quantity => new Entropy(quantity.Value, EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction(EntropyUnit.KilocaloriePerKelvin, EntropyUnit.JoulePerKelvin, quantity => new Entropy((quantity.Value*4.184) * 1e3d, EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction(EntropyUnit.KilojoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin, quantity => new Entropy((quantity.Value) * 1e3d, EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction(EntropyUnit.KilojoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => new Entropy((quantity.Value) * 1e3d, EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction(EntropyUnit.MegajoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => new Entropy((quantity.Value) * 1e6d, EntropyUnit.JoulePerKelvin)); } /// @@ -718,11 +725,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Entropy to another Entropy with the unit representation . /// + /// The unit to convert to. /// A Entropy with the specified unit. public Entropy ToUnit(EntropyUnit unit) { - var convertedValue = GetValueAs(unit); - return new Entropy(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Entropy to another Entropy using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Entropy with the specified unit. + public Entropy ToUnit(EntropyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Entropy), Unit, typeof(Entropy), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Entropy)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -731,7 +769,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is EntropyUnit unitAsEntropyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EntropyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsEntropyUnit); + return ToUnit(unitAsEntropyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is EntropyUnit unitAsEntropyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EntropyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsEntropyUnit, unitConverter); } /// @@ -756,59 +803,15 @@ public Entropy ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(EntropyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case EntropyUnit.CaloriePerKelvin: return _value*4.184; - case EntropyUnit.JoulePerDegreeCelsius: return _value; - case EntropyUnit.JoulePerKelvin: return _value; - case EntropyUnit.KilocaloriePerKelvin: return (_value*4.184) * 1e3d; - case EntropyUnit.KilojoulePerDegreeCelsius: return (_value) * 1e3d; - case EntropyUnit.KilojoulePerKelvin: return (_value) * 1e3d; - case EntropyUnit.MegajoulePerKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(EntropyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Entropy ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Entropy(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(EntropyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case EntropyUnit.CaloriePerKelvin: return baseUnitValue/4.184; - case EntropyUnit.JoulePerDegreeCelsius: return baseUnitValue; - case EntropyUnit.JoulePerKelvin: return baseUnitValue; - case EntropyUnit.KilocaloriePerKelvin: return (baseUnitValue/4.184) / 1e3d; - case EntropyUnit.KilojoulePerDegreeCelsius: return (baseUnitValue) / 1e3d; - case EntropyUnit.KilojoulePerKelvin: return (baseUnitValue) / 1e3d; - case EntropyUnit.MegajoulePerKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Force.g.cs b/UnitsNet/GeneratedCode/Quantities/Force.g.cs index 968c89fe50..fe0fe1efd7 100644 --- a/UnitsNet/GeneratedCode/Quantities/Force.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Force.g.cs @@ -79,6 +79,8 @@ static Force() new UnitInfo(ForceUnit.TonneForce, "TonnesForce", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Force); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -117,6 +119,11 @@ public Force(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -279,39 +286,39 @@ public Force(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ForceUnit - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Decanewton, quantity => quantity.ToUnit(ForceUnit.Decanewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Dyn, quantity => quantity.ToUnit(ForceUnit.Dyn)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.KilogramForce, quantity => quantity.ToUnit(ForceUnit.KilogramForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Kilonewton, quantity => quantity.ToUnit(ForceUnit.Kilonewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.KiloPond, quantity => quantity.ToUnit(ForceUnit.KiloPond)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.KilopoundForce, quantity => quantity.ToUnit(ForceUnit.KilopoundForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Meganewton, quantity => quantity.ToUnit(ForceUnit.Meganewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Micronewton, quantity => quantity.ToUnit(ForceUnit.Micronewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Millinewton, quantity => quantity.ToUnit(ForceUnit.Millinewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.OunceForce, quantity => quantity.ToUnit(ForceUnit.OunceForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Poundal, quantity => quantity.ToUnit(ForceUnit.Poundal)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.PoundForce, quantity => quantity.ToUnit(ForceUnit.PoundForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.ShortTonForce, quantity => quantity.ToUnit(ForceUnit.ShortTonForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.TonneForce, quantity => quantity.ToUnit(ForceUnit.TonneForce)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Decanewton, quantity => new Force((quantity.Value) / 1e1d, ForceUnit.Decanewton)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Dyn, quantity => new Force(quantity.Value*1e5, ForceUnit.Dyn)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.KilogramForce, quantity => new Force(quantity.Value/9.80665002864, ForceUnit.KilogramForce)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Kilonewton, quantity => new Force((quantity.Value) / 1e3d, ForceUnit.Kilonewton)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.KiloPond, quantity => new Force(quantity.Value/9.80665002864, ForceUnit.KiloPond)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.KilopoundForce, quantity => new Force((quantity.Value/4.4482216152605095551842641431421) / 1e3d, ForceUnit.KilopoundForce)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Meganewton, quantity => new Force((quantity.Value) / 1e6d, ForceUnit.Meganewton)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Micronewton, quantity => new Force((quantity.Value) / 1e-6d, ForceUnit.Micronewton)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Millinewton, quantity => new Force((quantity.Value) / 1e-3d, ForceUnit.Millinewton)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.OunceForce, quantity => new Force(quantity.Value/2.780138509537812e-1, ForceUnit.OunceForce)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Poundal, quantity => new Force(quantity.Value/0.13825502798973041652092282466083, ForceUnit.Poundal)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.PoundForce, quantity => new Force(quantity.Value/4.4482216152605095551842641431421, ForceUnit.PoundForce)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.ShortTonForce, quantity => new Force(quantity.Value/8.896443230521e3, ForceUnit.ShortTonForce)); + unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.TonneForce, quantity => new Force(quantity.Value/9.80665002864e3, ForceUnit.TonneForce)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Newton, quantity => quantity); // Register in unit converter: ForceUnit -> BaseUnit - unitConverter.SetConversionFunction(ForceUnit.Decanewton, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.Dyn, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.KilogramForce, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.Kilonewton, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.KiloPond, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.KilopoundForce, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.Meganewton, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.Micronewton, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.Millinewton, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.OunceForce, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.Poundal, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.PoundForce, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.ShortTonForce, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceUnit.TonneForce, ForceUnit.Newton, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ForceUnit.Decanewton, ForceUnit.Newton, quantity => new Force((quantity.Value) * 1e1d, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.Dyn, ForceUnit.Newton, quantity => new Force(quantity.Value/1e5, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.KilogramForce, ForceUnit.Newton, quantity => new Force(quantity.Value*9.80665002864, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.Kilonewton, ForceUnit.Newton, quantity => new Force((quantity.Value) * 1e3d, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.KiloPond, ForceUnit.Newton, quantity => new Force(quantity.Value*9.80665002864, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.KilopoundForce, ForceUnit.Newton, quantity => new Force((quantity.Value*4.4482216152605095551842641431421) * 1e3d, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.Meganewton, ForceUnit.Newton, quantity => new Force((quantity.Value) * 1e6d, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.Micronewton, ForceUnit.Newton, quantity => new Force((quantity.Value) * 1e-6d, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.Millinewton, ForceUnit.Newton, quantity => new Force((quantity.Value) * 1e-3d, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.OunceForce, ForceUnit.Newton, quantity => new Force(quantity.Value*2.780138509537812e-1, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.Poundal, ForceUnit.Newton, quantity => new Force(quantity.Value*0.13825502798973041652092282466083, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.PoundForce, ForceUnit.Newton, quantity => new Force(quantity.Value*4.4482216152605095551842641431421, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.ShortTonForce, ForceUnit.Newton, quantity => new Force(quantity.Value*8.896443230521e3, ForceUnit.Newton)); + unitConverter.SetConversionFunction(ForceUnit.TonneForce, ForceUnit.Newton, quantity => new Force(quantity.Value*9.80665002864e3, ForceUnit.Newton)); } /// @@ -854,11 +861,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Force to another Force with the unit representation . /// + /// The unit to convert to. /// A Force with the specified unit. public Force ToUnit(ForceUnit unit) { - var convertedValue = GetValueAs(unit); - return new Force(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Force to another Force using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Force with the specified unit. + public Force ToUnit(ForceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Force), Unit, typeof(Force), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Force)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -867,7 +905,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ForceUnit unitAsForceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsForceUnit); + return ToUnit(unitAsForceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ForceUnit unitAsForceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsForceUnit, unitConverter); } /// @@ -892,75 +939,15 @@ public Force ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ForceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ForceUnit.Decanewton: return (_value) * 1e1d; - case ForceUnit.Dyn: return _value/1e5; - case ForceUnit.KilogramForce: return _value*9.80665002864; - case ForceUnit.Kilonewton: return (_value) * 1e3d; - case ForceUnit.KiloPond: return _value*9.80665002864; - case ForceUnit.KilopoundForce: return (_value*4.4482216152605095551842641431421) * 1e3d; - case ForceUnit.Meganewton: return (_value) * 1e6d; - case ForceUnit.Micronewton: return (_value) * 1e-6d; - case ForceUnit.Millinewton: return (_value) * 1e-3d; - case ForceUnit.Newton: return _value; - case ForceUnit.OunceForce: return _value*2.780138509537812e-1; - case ForceUnit.Poundal: return _value*0.13825502798973041652092282466083; - case ForceUnit.PoundForce: return _value*4.4482216152605095551842641431421; - case ForceUnit.ShortTonForce: return _value*8.896443230521e3; - case ForceUnit.TonneForce: return _value*9.80665002864e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ForceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Force ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Force(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ForceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ForceUnit.Decanewton: return (baseUnitValue) / 1e1d; - case ForceUnit.Dyn: return baseUnitValue*1e5; - case ForceUnit.KilogramForce: return baseUnitValue/9.80665002864; - case ForceUnit.Kilonewton: return (baseUnitValue) / 1e3d; - case ForceUnit.KiloPond: return baseUnitValue/9.80665002864; - case ForceUnit.KilopoundForce: return (baseUnitValue/4.4482216152605095551842641431421) / 1e3d; - case ForceUnit.Meganewton: return (baseUnitValue) / 1e6d; - case ForceUnit.Micronewton: return (baseUnitValue) / 1e-6d; - case ForceUnit.Millinewton: return (baseUnitValue) / 1e-3d; - case ForceUnit.Newton: return baseUnitValue; - case ForceUnit.OunceForce: return baseUnitValue/2.780138509537812e-1; - case ForceUnit.Poundal: return baseUnitValue/0.13825502798973041652092282466083; - case ForceUnit.PoundForce: return baseUnitValue/4.4482216152605095551842641431421; - case ForceUnit.ShortTonForce: return baseUnitValue/8.896443230521e3; - case ForceUnit.TonneForce: return baseUnitValue/9.80665002864e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs index 9fb55c453c..31a79483b1 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs @@ -79,6 +79,8 @@ static ForceChangeRate() new UnitInfo(ForceChangeRateUnit.PoundForcePerSecond, "PoundsForcePerSecond", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ForceChangeRate); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -117,6 +119,11 @@ public ForceChangeRate(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -279,39 +286,39 @@ public ForceChangeRate(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ForceChangeRateUnit - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.CentinewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.CentinewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.DecanewtonPerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.DecanewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecinewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.DecinewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.KilonewtonPerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.KilonewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.KilopoundForcePerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.KilopoundForcePerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MicronewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.MicronewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MillinewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.MillinewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NanonewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NanonewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NewtonPerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.PoundForcePerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.PoundForcePerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.CentinewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) / 1e-2d, ForceChangeRateUnit.CentinewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerMinute, quantity => new ForceChangeRate((quantity.Value*60) / 1e1d, ForceChangeRateUnit.DecanewtonPerMinute)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) / 1e1d, ForceChangeRateUnit.DecanewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecinewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) / 1e-1d, ForceChangeRateUnit.DecinewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerMinute, quantity => new ForceChangeRate((quantity.Value*60) / 1e3d, ForceChangeRateUnit.KilonewtonPerMinute)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) / 1e3d, ForceChangeRateUnit.KilonewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerMinute, quantity => new ForceChangeRate((quantity.Value/4.4482216152605095551842641431421*60) / 1e3d, ForceChangeRateUnit.KilopoundForcePerMinute)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerSecond, quantity => new ForceChangeRate((quantity.Value/4.4482216152605095551842641431421) / 1e3d, ForceChangeRateUnit.KilopoundForcePerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MicronewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) / 1e-6d, ForceChangeRateUnit.MicronewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MillinewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) / 1e-3d, ForceChangeRateUnit.MillinewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NanonewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) / 1e-9d, ForceChangeRateUnit.NanonewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NewtonPerMinute, quantity => new ForceChangeRate(quantity.Value*60, ForceChangeRateUnit.NewtonPerMinute)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerMinute, quantity => new ForceChangeRate(quantity.Value/4.4482216152605095551842641431421*60, ForceChangeRateUnit.PoundForcePerMinute)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerSecond, quantity => new ForceChangeRate(quantity.Value/4.4482216152605095551842641431421, ForceChangeRateUnit.PoundForcePerSecond)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity); // Register in unit converter: ForceChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(ForceChangeRateUnit.CentinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.DecanewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.DecanewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.DecinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.KilonewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.KilonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.KilopoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.KilopoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.MicronewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.MillinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NanonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.PoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForceChangeRateUnit.PoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ForceChangeRateUnit.CentinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) * 1e-2d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.DecanewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value/60) * 1e1d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.DecanewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) * 1e1d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.DecinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) * 1e-1d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.KilonewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value/60) * 1e3d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.KilonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) * 1e3d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.KilopoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value*4.4482216152605095551842641431421/60) * 1e3d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.KilopoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value*4.4482216152605095551842641431421) * 1e3d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.MicronewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) * 1e-6d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.MillinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) * 1e-3d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NanonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate((quantity.Value) * 1e-9d, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate(quantity.Value/60, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.PoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate(quantity.Value*4.4482216152605095551842641431421/60, ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction(ForceChangeRateUnit.PoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => new ForceChangeRate(quantity.Value*4.4482216152605095551842641431421, ForceChangeRateUnit.NewtonPerSecond)); } /// @@ -854,11 +861,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ForceChangeRate to another ForceChangeRate with the unit representation . /// + /// The unit to convert to. /// A ForceChangeRate with the specified unit. public ForceChangeRate ToUnit(ForceChangeRateUnit unit) { - var convertedValue = GetValueAs(unit); - return new ForceChangeRate(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ForceChangeRate to another ForceChangeRate using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ForceChangeRate with the specified unit. + public ForceChangeRate ToUnit(ForceChangeRateUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ForceChangeRate), Unit, typeof(ForceChangeRate), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ForceChangeRate)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -867,7 +905,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ForceChangeRateUnit unitAsForceChangeRateUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsForceChangeRateUnit); + return ToUnit(unitAsForceChangeRateUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ForceChangeRateUnit unitAsForceChangeRateUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsForceChangeRateUnit, unitConverter); } /// @@ -892,75 +939,15 @@ public ForceChangeRate ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ForceChangeRateUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: return (_value) * 1e-2d; - case ForceChangeRateUnit.DecanewtonPerMinute: return (_value/60) * 1e1d; - case ForceChangeRateUnit.DecanewtonPerSecond: return (_value) * 1e1d; - case ForceChangeRateUnit.DecinewtonPerSecond: return (_value) * 1e-1d; - case ForceChangeRateUnit.KilonewtonPerMinute: return (_value/60) * 1e3d; - case ForceChangeRateUnit.KilonewtonPerSecond: return (_value) * 1e3d; - case ForceChangeRateUnit.KilopoundForcePerMinute: return (_value*4.4482216152605095551842641431421/60) * 1e3d; - case ForceChangeRateUnit.KilopoundForcePerSecond: return (_value*4.4482216152605095551842641431421) * 1e3d; - case ForceChangeRateUnit.MicronewtonPerSecond: return (_value) * 1e-6d; - case ForceChangeRateUnit.MillinewtonPerSecond: return (_value) * 1e-3d; - case ForceChangeRateUnit.NanonewtonPerSecond: return (_value) * 1e-9d; - case ForceChangeRateUnit.NewtonPerMinute: return _value/60; - case ForceChangeRateUnit.NewtonPerSecond: return _value; - case ForceChangeRateUnit.PoundForcePerMinute: return _value*4.4482216152605095551842641431421/60; - case ForceChangeRateUnit.PoundForcePerSecond: return _value*4.4482216152605095551842641431421; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ForceChangeRateUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ForceChangeRate ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ForceChangeRate(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ForceChangeRateUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: return (baseUnitValue) / 1e-2d; - case ForceChangeRateUnit.DecanewtonPerMinute: return (baseUnitValue*60) / 1e1d; - case ForceChangeRateUnit.DecanewtonPerSecond: return (baseUnitValue) / 1e1d; - case ForceChangeRateUnit.DecinewtonPerSecond: return (baseUnitValue) / 1e-1d; - case ForceChangeRateUnit.KilonewtonPerMinute: return (baseUnitValue*60) / 1e3d; - case ForceChangeRateUnit.KilonewtonPerSecond: return (baseUnitValue) / 1e3d; - case ForceChangeRateUnit.KilopoundForcePerMinute: return (baseUnitValue/4.4482216152605095551842641431421*60) / 1e3d; - case ForceChangeRateUnit.KilopoundForcePerSecond: return (baseUnitValue/4.4482216152605095551842641431421) / 1e3d; - case ForceChangeRateUnit.MicronewtonPerSecond: return (baseUnitValue) / 1e-6d; - case ForceChangeRateUnit.MillinewtonPerSecond: return (baseUnitValue) / 1e-3d; - case ForceChangeRateUnit.NanonewtonPerSecond: return (baseUnitValue) / 1e-9d; - case ForceChangeRateUnit.NewtonPerMinute: return baseUnitValue*60; - case ForceChangeRateUnit.NewtonPerSecond: return baseUnitValue; - case ForceChangeRateUnit.PoundForcePerMinute: return baseUnitValue/4.4482216152605095551842641431421*60; - case ForceChangeRateUnit.PoundForcePerSecond: return baseUnitValue/4.4482216152605095551842641431421; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs index e5f536795a..d20ba0ec47 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs @@ -102,6 +102,8 @@ static ForcePerLength() new UnitInfo(ForcePerLengthUnit.TonneForcePerMillimeter, "TonnesForcePerMillimeter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ForcePerLength); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -140,6 +142,11 @@ public ForcePerLength(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -417,85 +424,85 @@ public ForcePerLength(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ForcePerLengthUnit - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.CentinewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.CentinewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.CentinewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecanewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecanewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecanewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecinewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecinewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecinewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilogramForcePerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilogramForcePerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilogramForcePerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilonewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilonewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilonewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerFoot, quantity => quantity.ToUnit(ForcePerLengthUnit.KilopoundForcePerFoot)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerInch, quantity => quantity.ToUnit(ForcePerLengthUnit.KilopoundForcePerInch)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MeganewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MeganewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MeganewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MicronewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MicronewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MicronewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MillinewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MillinewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MillinewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NanonewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NanonewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NanonewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerFoot, quantity => quantity.ToUnit(ForcePerLengthUnit.PoundForcePerFoot)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerInch, quantity => quantity.ToUnit(ForcePerLengthUnit.PoundForcePerInch)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerYard, quantity => quantity.ToUnit(ForcePerLengthUnit.PoundForcePerYard)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.TonneForcePerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.TonneForcePerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.TonneForcePerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerCentimeter, quantity => new ForcePerLength((quantity.Value/1e2) / 1e-2d, ForcePerLengthUnit.CentinewtonPerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMeter, quantity => new ForcePerLength((quantity.Value) / 1e-2d, ForcePerLengthUnit.CentinewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMillimeter, quantity => new ForcePerLength((quantity.Value/1e3) / 1e-2d, ForcePerLengthUnit.CentinewtonPerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerCentimeter, quantity => new ForcePerLength((quantity.Value/1e2) / 1e1d, ForcePerLengthUnit.DecanewtonPerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMeter, quantity => new ForcePerLength((quantity.Value) / 1e1d, ForcePerLengthUnit.DecanewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMillimeter, quantity => new ForcePerLength((quantity.Value/1e3) / 1e1d, ForcePerLengthUnit.DecanewtonPerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerCentimeter, quantity => new ForcePerLength((quantity.Value/1e2) / 1e-1d, ForcePerLengthUnit.DecinewtonPerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMeter, quantity => new ForcePerLength((quantity.Value) / 1e-1d, ForcePerLengthUnit.DecinewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMillimeter, quantity => new ForcePerLength((quantity.Value/1e3) / 1e-1d, ForcePerLengthUnit.DecinewtonPerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerCentimeter, quantity => new ForcePerLength(quantity.Value/980.665002864, ForcePerLengthUnit.KilogramForcePerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMeter, quantity => new ForcePerLength(quantity.Value/9.80665002864, ForcePerLengthUnit.KilogramForcePerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMillimeter, quantity => new ForcePerLength(quantity.Value/9.80665002864e3, ForcePerLengthUnit.KilogramForcePerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerCentimeter, quantity => new ForcePerLength((quantity.Value/1e2) / 1e3d, ForcePerLengthUnit.KilonewtonPerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMeter, quantity => new ForcePerLength((quantity.Value) / 1e3d, ForcePerLengthUnit.KilonewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMillimeter, quantity => new ForcePerLength((quantity.Value/1e3) / 1e3d, ForcePerLengthUnit.KilonewtonPerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerFoot, quantity => new ForcePerLength(quantity.Value/14593.90292, ForcePerLengthUnit.KilopoundForcePerFoot)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerInch, quantity => new ForcePerLength(quantity.Value/1.75126835e5, ForcePerLengthUnit.KilopoundForcePerInch)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerCentimeter, quantity => new ForcePerLength((quantity.Value/1e2) / 1e6d, ForcePerLengthUnit.MeganewtonPerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMeter, quantity => new ForcePerLength((quantity.Value) / 1e6d, ForcePerLengthUnit.MeganewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMillimeter, quantity => new ForcePerLength((quantity.Value/1e3) / 1e6d, ForcePerLengthUnit.MeganewtonPerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerCentimeter, quantity => new ForcePerLength((quantity.Value/1e2) / 1e-6d, ForcePerLengthUnit.MicronewtonPerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMeter, quantity => new ForcePerLength((quantity.Value) / 1e-6d, ForcePerLengthUnit.MicronewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMillimeter, quantity => new ForcePerLength((quantity.Value/1e3) / 1e-6d, ForcePerLengthUnit.MicronewtonPerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerCentimeter, quantity => new ForcePerLength((quantity.Value/1e2) / 1e-3d, ForcePerLengthUnit.MillinewtonPerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMeter, quantity => new ForcePerLength((quantity.Value) / 1e-3d, ForcePerLengthUnit.MillinewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMillimeter, quantity => new ForcePerLength((quantity.Value/1e3) / 1e-3d, ForcePerLengthUnit.MillinewtonPerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerCentimeter, quantity => new ForcePerLength((quantity.Value/1e2) / 1e-9d, ForcePerLengthUnit.NanonewtonPerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMeter, quantity => new ForcePerLength((quantity.Value) / 1e-9d, ForcePerLengthUnit.NanonewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMillimeter, quantity => new ForcePerLength((quantity.Value/1e3) / 1e-9d, ForcePerLengthUnit.NanonewtonPerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerCentimeter, quantity => new ForcePerLength(quantity.Value/1e2, ForcePerLengthUnit.NewtonPerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerMillimeter, quantity => new ForcePerLength(quantity.Value/1e3, ForcePerLengthUnit.NewtonPerMillimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerFoot, quantity => new ForcePerLength(quantity.Value/14.59390292, ForcePerLengthUnit.PoundForcePerFoot)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerInch, quantity => new ForcePerLength(quantity.Value/1.75126835e2, ForcePerLengthUnit.PoundForcePerInch)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerYard, quantity => new ForcePerLength(quantity.Value/4.864634307, ForcePerLengthUnit.PoundForcePerYard)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerCentimeter, quantity => new ForcePerLength(quantity.Value/9.80665002864e5, ForcePerLengthUnit.TonneForcePerCentimeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMeter, quantity => new ForcePerLength(quantity.Value/9.80665002864e3, ForcePerLengthUnit.TonneForcePerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMillimeter, quantity => new ForcePerLength(quantity.Value/9.80665002864e6, ForcePerLengthUnit.TonneForcePerMillimeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity); // Register in unit converter: ForcePerLengthUnit -> BaseUnit - unitConverter.SetConversionFunction(ForcePerLengthUnit.CentinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.CentinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.CentinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecanewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecanewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecanewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilogramForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilogramForcePerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilogramForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilopoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilopoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MeganewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MeganewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MeganewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MicronewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MicronewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MicronewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MillinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MillinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MillinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NanonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NanonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NanonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.PoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.PoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.PoundForcePerYard, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.TonneForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.TonneForcePerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ForcePerLengthUnit.TonneForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ForcePerLengthUnit.CentinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e2) * 1e-2d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.CentinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value) * 1e-2d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.CentinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e3) * 1e-2d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.DecanewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e2) * 1e1d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.DecanewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value) * 1e1d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.DecanewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e3) * 1e1d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.DecinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e2) * 1e-1d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.DecinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value) * 1e-1d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.DecinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e3) * 1e-1d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.KilogramForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*980.665002864, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.KilogramForcePerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*9.80665002864, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.KilogramForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*9.80665002864e3, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.KilonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e2) * 1e3d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.KilonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value) * 1e3d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.KilonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e3) * 1e3d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.KilopoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*14593.90292, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.KilopoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*1.75126835e5, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.MeganewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e2) * 1e6d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.MeganewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value) * 1e6d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.MeganewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e3) * 1e6d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.MicronewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e2) * 1e-6d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.MicronewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value) * 1e-6d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.MicronewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e3) * 1e-6d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.MillinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e2) * 1e-3d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.MillinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value) * 1e-3d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.MillinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e3) * 1e-3d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NanonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e2) * 1e-9d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NanonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value) * 1e-9d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NanonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength((quantity.Value*1e3) * 1e-9d, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*1e2, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*1e3, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.PoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*14.59390292, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.PoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*1.75126835e2, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.PoundForcePerYard, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*4.864634307, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.TonneForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*9.80665002864e5, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.TonneForcePerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*9.80665002864e3, ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction(ForcePerLengthUnit.TonneForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => new ForcePerLength(quantity.Value*9.80665002864e6, ForcePerLengthUnit.NewtonPerMeter)); } /// @@ -1245,11 +1252,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ForcePerLength to another ForcePerLength with the unit representation . /// + /// The unit to convert to. /// A ForcePerLength with the specified unit. public ForcePerLength ToUnit(ForcePerLengthUnit unit) { - var convertedValue = GetValueAs(unit); - return new ForcePerLength(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ForcePerLength to another ForcePerLength using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ForcePerLength with the specified unit. + public ForcePerLength ToUnit(ForcePerLengthUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ForcePerLength), Unit, typeof(ForcePerLength), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ForcePerLength)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1258,7 +1296,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ForcePerLengthUnit unitAsForcePerLengthUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForcePerLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsForcePerLengthUnit); + return ToUnit(unitAsForcePerLengthUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ForcePerLengthUnit unitAsForcePerLengthUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForcePerLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsForcePerLengthUnit, unitConverter); } /// @@ -1283,121 +1330,15 @@ public ForcePerLength ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ForcePerLengthUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ForcePerLengthUnit.CentinewtonPerCentimeter: return (_value*1e2) * 1e-2d; - case ForcePerLengthUnit.CentinewtonPerMeter: return (_value) * 1e-2d; - case ForcePerLengthUnit.CentinewtonPerMillimeter: return (_value*1e3) * 1e-2d; - case ForcePerLengthUnit.DecanewtonPerCentimeter: return (_value*1e2) * 1e1d; - case ForcePerLengthUnit.DecanewtonPerMeter: return (_value) * 1e1d; - case ForcePerLengthUnit.DecanewtonPerMillimeter: return (_value*1e3) * 1e1d; - case ForcePerLengthUnit.DecinewtonPerCentimeter: return (_value*1e2) * 1e-1d; - case ForcePerLengthUnit.DecinewtonPerMeter: return (_value) * 1e-1d; - case ForcePerLengthUnit.DecinewtonPerMillimeter: return (_value*1e3) * 1e-1d; - case ForcePerLengthUnit.KilogramForcePerCentimeter: return _value*980.665002864; - case ForcePerLengthUnit.KilogramForcePerMeter: return _value*9.80665002864; - case ForcePerLengthUnit.KilogramForcePerMillimeter: return _value*9.80665002864e3; - case ForcePerLengthUnit.KilonewtonPerCentimeter: return (_value*1e2) * 1e3d; - case ForcePerLengthUnit.KilonewtonPerMeter: return (_value) * 1e3d; - case ForcePerLengthUnit.KilonewtonPerMillimeter: return (_value*1e3) * 1e3d; - case ForcePerLengthUnit.KilopoundForcePerFoot: return _value*14593.90292; - case ForcePerLengthUnit.KilopoundForcePerInch: return _value*1.75126835e5; - case ForcePerLengthUnit.MeganewtonPerCentimeter: return (_value*1e2) * 1e6d; - case ForcePerLengthUnit.MeganewtonPerMeter: return (_value) * 1e6d; - case ForcePerLengthUnit.MeganewtonPerMillimeter: return (_value*1e3) * 1e6d; - case ForcePerLengthUnit.MicronewtonPerCentimeter: return (_value*1e2) * 1e-6d; - case ForcePerLengthUnit.MicronewtonPerMeter: return (_value) * 1e-6d; - case ForcePerLengthUnit.MicronewtonPerMillimeter: return (_value*1e3) * 1e-6d; - case ForcePerLengthUnit.MillinewtonPerCentimeter: return (_value*1e2) * 1e-3d; - case ForcePerLengthUnit.MillinewtonPerMeter: return (_value) * 1e-3d; - case ForcePerLengthUnit.MillinewtonPerMillimeter: return (_value*1e3) * 1e-3d; - case ForcePerLengthUnit.NanonewtonPerCentimeter: return (_value*1e2) * 1e-9d; - case ForcePerLengthUnit.NanonewtonPerMeter: return (_value) * 1e-9d; - case ForcePerLengthUnit.NanonewtonPerMillimeter: return (_value*1e3) * 1e-9d; - case ForcePerLengthUnit.NewtonPerCentimeter: return _value*1e2; - case ForcePerLengthUnit.NewtonPerMeter: return _value; - case ForcePerLengthUnit.NewtonPerMillimeter: return _value*1e3; - case ForcePerLengthUnit.PoundForcePerFoot: return _value*14.59390292; - case ForcePerLengthUnit.PoundForcePerInch: return _value*1.75126835e2; - case ForcePerLengthUnit.PoundForcePerYard: return _value*4.864634307; - case ForcePerLengthUnit.TonneForcePerCentimeter: return _value*9.80665002864e5; - case ForcePerLengthUnit.TonneForcePerMeter: return _value*9.80665002864e3; - case ForcePerLengthUnit.TonneForcePerMillimeter: return _value*9.80665002864e6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ForcePerLengthUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ForcePerLength ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ForcePerLength(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ForcePerLengthUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ForcePerLengthUnit.CentinewtonPerCentimeter: return (baseUnitValue/1e2) / 1e-2d; - case ForcePerLengthUnit.CentinewtonPerMeter: return (baseUnitValue) / 1e-2d; - case ForcePerLengthUnit.CentinewtonPerMillimeter: return (baseUnitValue/1e3) / 1e-2d; - case ForcePerLengthUnit.DecanewtonPerCentimeter: return (baseUnitValue/1e2) / 1e1d; - case ForcePerLengthUnit.DecanewtonPerMeter: return (baseUnitValue) / 1e1d; - case ForcePerLengthUnit.DecanewtonPerMillimeter: return (baseUnitValue/1e3) / 1e1d; - case ForcePerLengthUnit.DecinewtonPerCentimeter: return (baseUnitValue/1e2) / 1e-1d; - case ForcePerLengthUnit.DecinewtonPerMeter: return (baseUnitValue) / 1e-1d; - case ForcePerLengthUnit.DecinewtonPerMillimeter: return (baseUnitValue/1e3) / 1e-1d; - case ForcePerLengthUnit.KilogramForcePerCentimeter: return baseUnitValue/980.665002864; - case ForcePerLengthUnit.KilogramForcePerMeter: return baseUnitValue/9.80665002864; - case ForcePerLengthUnit.KilogramForcePerMillimeter: return baseUnitValue/9.80665002864e3; - case ForcePerLengthUnit.KilonewtonPerCentimeter: return (baseUnitValue/1e2) / 1e3d; - case ForcePerLengthUnit.KilonewtonPerMeter: return (baseUnitValue) / 1e3d; - case ForcePerLengthUnit.KilonewtonPerMillimeter: return (baseUnitValue/1e3) / 1e3d; - case ForcePerLengthUnit.KilopoundForcePerFoot: return baseUnitValue/14593.90292; - case ForcePerLengthUnit.KilopoundForcePerInch: return baseUnitValue/1.75126835e5; - case ForcePerLengthUnit.MeganewtonPerCentimeter: return (baseUnitValue/1e2) / 1e6d; - case ForcePerLengthUnit.MeganewtonPerMeter: return (baseUnitValue) / 1e6d; - case ForcePerLengthUnit.MeganewtonPerMillimeter: return (baseUnitValue/1e3) / 1e6d; - case ForcePerLengthUnit.MicronewtonPerCentimeter: return (baseUnitValue/1e2) / 1e-6d; - case ForcePerLengthUnit.MicronewtonPerMeter: return (baseUnitValue) / 1e-6d; - case ForcePerLengthUnit.MicronewtonPerMillimeter: return (baseUnitValue/1e3) / 1e-6d; - case ForcePerLengthUnit.MillinewtonPerCentimeter: return (baseUnitValue/1e2) / 1e-3d; - case ForcePerLengthUnit.MillinewtonPerMeter: return (baseUnitValue) / 1e-3d; - case ForcePerLengthUnit.MillinewtonPerMillimeter: return (baseUnitValue/1e3) / 1e-3d; - case ForcePerLengthUnit.NanonewtonPerCentimeter: return (baseUnitValue/1e2) / 1e-9d; - case ForcePerLengthUnit.NanonewtonPerMeter: return (baseUnitValue) / 1e-9d; - case ForcePerLengthUnit.NanonewtonPerMillimeter: return (baseUnitValue/1e3) / 1e-9d; - case ForcePerLengthUnit.NewtonPerCentimeter: return baseUnitValue/1e2; - case ForcePerLengthUnit.NewtonPerMeter: return baseUnitValue; - case ForcePerLengthUnit.NewtonPerMillimeter: return baseUnitValue/1e3; - case ForcePerLengthUnit.PoundForcePerFoot: return baseUnitValue/14.59390292; - case ForcePerLengthUnit.PoundForcePerInch: return baseUnitValue/1.75126835e2; - case ForcePerLengthUnit.PoundForcePerYard: return baseUnitValue/4.864634307; - case ForcePerLengthUnit.TonneForcePerCentimeter: return baseUnitValue/9.80665002864e5; - case ForcePerLengthUnit.TonneForcePerMeter: return baseUnitValue/9.80665002864e3; - case ForcePerLengthUnit.TonneForcePerMillimeter: return baseUnitValue/9.80665002864e6; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs index a676e82788..43abae81b3 100644 --- a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs @@ -75,6 +75,8 @@ static Frequency() new UnitInfo(FrequencyUnit.Terahertz, "Terahertz", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Frequency); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -113,6 +115,11 @@ public Frequency(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -255,31 +262,31 @@ public Frequency(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> FrequencyUnit - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.BeatPerMinute, quantity => quantity.ToUnit(FrequencyUnit.BeatPerMinute)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.BUnit, quantity => quantity.ToUnit(FrequencyUnit.BUnit)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.CyclePerHour, quantity => quantity.ToUnit(FrequencyUnit.CyclePerHour)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.CyclePerMinute, quantity => quantity.ToUnit(FrequencyUnit.CyclePerMinute)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Gigahertz, quantity => quantity.ToUnit(FrequencyUnit.Gigahertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Kilohertz, quantity => quantity.ToUnit(FrequencyUnit.Kilohertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Megahertz, quantity => quantity.ToUnit(FrequencyUnit.Megahertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.PerSecond, quantity => quantity.ToUnit(FrequencyUnit.PerSecond)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.RadianPerSecond, quantity => quantity.ToUnit(FrequencyUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Terahertz, quantity => quantity.ToUnit(FrequencyUnit.Terahertz)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.BeatPerMinute, quantity => new Frequency(quantity.Value*60, FrequencyUnit.BeatPerMinute)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.BUnit, quantity => new Frequency(quantity.Value * quantity.Value * 1e-3, FrequencyUnit.BUnit)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.CyclePerHour, quantity => new Frequency(quantity.Value*3600, FrequencyUnit.CyclePerHour)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.CyclePerMinute, quantity => new Frequency(quantity.Value*60, FrequencyUnit.CyclePerMinute)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Gigahertz, quantity => new Frequency((quantity.Value) / 1e9d, FrequencyUnit.Gigahertz)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Kilohertz, quantity => new Frequency((quantity.Value) / 1e3d, FrequencyUnit.Kilohertz)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Megahertz, quantity => new Frequency((quantity.Value) / 1e6d, FrequencyUnit.Megahertz)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.PerSecond, quantity => new Frequency(quantity.Value, FrequencyUnit.PerSecond)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.RadianPerSecond, quantity => new Frequency(quantity.Value*6.2831853072, FrequencyUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Terahertz, quantity => new Frequency((quantity.Value) / 1e12d, FrequencyUnit.Terahertz)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Hertz, quantity => quantity); // Register in unit converter: FrequencyUnit -> BaseUnit - unitConverter.SetConversionFunction(FrequencyUnit.BeatPerMinute, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FrequencyUnit.BUnit, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FrequencyUnit.CyclePerHour, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FrequencyUnit.CyclePerMinute, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FrequencyUnit.Gigahertz, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FrequencyUnit.Kilohertz, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FrequencyUnit.Megahertz, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FrequencyUnit.PerSecond, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FrequencyUnit.RadianPerSecond, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FrequencyUnit.Terahertz, FrequencyUnit.Hertz, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(FrequencyUnit.BeatPerMinute, FrequencyUnit.Hertz, quantity => new Frequency(quantity.Value/60, FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction(FrequencyUnit.BUnit, FrequencyUnit.Hertz, quantity => new Frequency(Math.Sqrt(quantity.Value * 1e3), FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction(FrequencyUnit.CyclePerHour, FrequencyUnit.Hertz, quantity => new Frequency(quantity.Value/3600, FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction(FrequencyUnit.CyclePerMinute, FrequencyUnit.Hertz, quantity => new Frequency(quantity.Value/60, FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction(FrequencyUnit.Gigahertz, FrequencyUnit.Hertz, quantity => new Frequency((quantity.Value) * 1e9d, FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction(FrequencyUnit.Kilohertz, FrequencyUnit.Hertz, quantity => new Frequency((quantity.Value) * 1e3d, FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction(FrequencyUnit.Megahertz, FrequencyUnit.Hertz, quantity => new Frequency((quantity.Value) * 1e6d, FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction(FrequencyUnit.PerSecond, FrequencyUnit.Hertz, quantity => new Frequency(quantity.Value, FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction(FrequencyUnit.RadianPerSecond, FrequencyUnit.Hertz, quantity => new Frequency(quantity.Value/6.2831853072, FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction(FrequencyUnit.Terahertz, FrequencyUnit.Hertz, quantity => new Frequency((quantity.Value) * 1e12d, FrequencyUnit.Hertz)); } /// @@ -786,11 +793,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Frequency to another Frequency with the unit representation . /// + /// The unit to convert to. /// A Frequency with the specified unit. public Frequency ToUnit(FrequencyUnit unit) { - var convertedValue = GetValueAs(unit); - return new Frequency(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Frequency to another Frequency using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Frequency with the specified unit. + public Frequency ToUnit(FrequencyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Frequency), Unit, typeof(Frequency), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Frequency)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -799,7 +837,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is FrequencyUnit unitAsFrequencyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FrequencyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsFrequencyUnit); + return ToUnit(unitAsFrequencyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is FrequencyUnit unitAsFrequencyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FrequencyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsFrequencyUnit, unitConverter); } /// @@ -824,67 +871,15 @@ public Frequency ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(FrequencyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case FrequencyUnit.BeatPerMinute: return _value/60; - case FrequencyUnit.BUnit: return Math.Sqrt(_value * 1e3); - case FrequencyUnit.CyclePerHour: return _value/3600; - case FrequencyUnit.CyclePerMinute: return _value/60; - case FrequencyUnit.Gigahertz: return (_value) * 1e9d; - case FrequencyUnit.Hertz: return _value; - case FrequencyUnit.Kilohertz: return (_value) * 1e3d; - case FrequencyUnit.Megahertz: return (_value) * 1e6d; - case FrequencyUnit.PerSecond: return _value; - case FrequencyUnit.RadianPerSecond: return _value/6.2831853072; - case FrequencyUnit.Terahertz: return (_value) * 1e12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(FrequencyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Frequency ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Frequency(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(FrequencyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case FrequencyUnit.BeatPerMinute: return baseUnitValue*60; - case FrequencyUnit.BUnit: return baseUnitValue * baseUnitValue * 1e-3; - case FrequencyUnit.CyclePerHour: return baseUnitValue*3600; - case FrequencyUnit.CyclePerMinute: return baseUnitValue*60; - case FrequencyUnit.Gigahertz: return (baseUnitValue) / 1e9d; - case FrequencyUnit.Hertz: return baseUnitValue; - case FrequencyUnit.Kilohertz: return (baseUnitValue) / 1e3d; - case FrequencyUnit.Megahertz: return (baseUnitValue) / 1e6d; - case FrequencyUnit.PerSecond: return baseUnitValue; - case FrequencyUnit.RadianPerSecond: return baseUnitValue*6.2831853072; - case FrequencyUnit.Terahertz: return (baseUnitValue) / 1e12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs index 881f7ad0d4..f8a889effe 100644 --- a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs @@ -71,6 +71,8 @@ static FuelEfficiency() new UnitInfo(FuelEfficiencyUnit.MilePerUsGallon, "MilesPerUsGallon", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.FuelEfficiency); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -109,6 +111,11 @@ public FuelEfficiency(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -216,17 +223,17 @@ public FuelEfficiency(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> FuelEfficiencyUnit - unitConverter.SetConversionFunction(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.KilometerPerLiter, quantity => quantity.ToUnit(FuelEfficiencyUnit.KilometerPerLiter)); - unitConverter.SetConversionFunction(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.MilePerUkGallon, quantity => quantity.ToUnit(FuelEfficiencyUnit.MilePerUkGallon)); - unitConverter.SetConversionFunction(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.MilePerUsGallon, quantity => quantity.ToUnit(FuelEfficiencyUnit.MilePerUsGallon)); + unitConverter.SetConversionFunction(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.KilometerPerLiter, quantity => new FuelEfficiency(100/quantity.Value, FuelEfficiencyUnit.KilometerPerLiter)); + unitConverter.SetConversionFunction(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.MilePerUkGallon, quantity => new FuelEfficiency((100*4.54609188)/(1.609344*quantity.Value), FuelEfficiencyUnit.MilePerUkGallon)); + unitConverter.SetConversionFunction(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.MilePerUsGallon, quantity => new FuelEfficiency((100*3.785411784)/(1.609344*quantity.Value), FuelEfficiencyUnit.MilePerUsGallon)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => quantity); // Register in unit converter: FuelEfficiencyUnit -> BaseUnit - unitConverter.SetConversionFunction(FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FuelEfficiencyUnit.MilePerUkGallon, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(FuelEfficiencyUnit.MilePerUsGallon, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => new FuelEfficiency(100/quantity.Value, FuelEfficiencyUnit.LiterPer100Kilometers)); + unitConverter.SetConversionFunction(FuelEfficiencyUnit.MilePerUkGallon, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => new FuelEfficiency((100*4.54609188)/(1.609344*quantity.Value), FuelEfficiencyUnit.LiterPer100Kilometers)); + unitConverter.SetConversionFunction(FuelEfficiencyUnit.MilePerUsGallon, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => new FuelEfficiency((100*3.785411784)/(1.609344*quantity.Value), FuelEfficiencyUnit.LiterPer100Kilometers)); } /// @@ -670,11 +677,42 @@ double IQuantity.As(Enum unit) /// /// Converts this FuelEfficiency to another FuelEfficiency with the unit representation . /// + /// The unit to convert to. /// A FuelEfficiency with the specified unit. public FuelEfficiency ToUnit(FuelEfficiencyUnit unit) { - var convertedValue = GetValueAs(unit); - return new FuelEfficiency(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this FuelEfficiency to another FuelEfficiency using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A FuelEfficiency with the specified unit. + public FuelEfficiency ToUnit(FuelEfficiencyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(FuelEfficiency), Unit, typeof(FuelEfficiency), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (FuelEfficiency)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -683,7 +721,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is FuelEfficiencyUnit unitAsFuelEfficiencyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsFuelEfficiencyUnit); + return ToUnit(unitAsFuelEfficiencyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is FuelEfficiencyUnit unitAsFuelEfficiencyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsFuelEfficiencyUnit, unitConverter); } /// @@ -708,53 +755,15 @@ public FuelEfficiency ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(FuelEfficiencyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case FuelEfficiencyUnit.KilometerPerLiter: return 100/_value; - case FuelEfficiencyUnit.LiterPer100Kilometers: return _value; - case FuelEfficiencyUnit.MilePerUkGallon: return (100*4.54609188)/(1.609344*_value); - case FuelEfficiencyUnit.MilePerUsGallon: return (100*3.785411784)/(1.609344*_value); - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(FuelEfficiencyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal FuelEfficiency ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new FuelEfficiency(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(FuelEfficiencyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case FuelEfficiencyUnit.KilometerPerLiter: return 100/baseUnitValue; - case FuelEfficiencyUnit.LiterPer100Kilometers: return baseUnitValue; - case FuelEfficiencyUnit.MilePerUkGallon: return (100*4.54609188)/(1.609344*baseUnitValue); - case FuelEfficiencyUnit.MilePerUsGallon: return (100*3.785411784)/(1.609344*baseUnitValue); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs index d9b05778ca..b9c909cf55 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs @@ -82,6 +82,8 @@ static HeatFlux() new UnitInfo(HeatFluxUnit.WattPerSquareMeter, "WattsPerSquareMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second)), }, BaseUnit, Zero, BaseDimensions, QuantityType.HeatFlux); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -120,6 +122,11 @@ public HeatFlux(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -297,45 +304,45 @@ public HeatFlux(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> HeatFluxUnit - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerHourSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerHourSquareFoot)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerMinuteSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerMinuteSquareFoot)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerSecondSquareFoot)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareInch, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerSecondSquareInch)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CaloriePerSecondSquareCentimeter, quantity => quantity.ToUnit(HeatFluxUnit.CaloriePerSecondSquareCentimeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CentiwattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.CentiwattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.DeciwattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.DeciwattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerHourSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.KilocaloriePerHourSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, quantity => quantity.ToUnit(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilowattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.KilowattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MicrowattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.MicrowattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MilliwattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.MilliwattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.NanowattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.NanowattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundForcePerFootSecond, quantity => quantity.ToUnit(HeatFluxUnit.PoundForcePerFootSecond)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundPerSecondCubed, quantity => quantity.ToUnit(HeatFluxUnit.PoundPerSecondCubed)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareFoot)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareInch, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareInch)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerHourSquareFoot, quantity => new HeatFlux(quantity.Value/3.15459075, HeatFluxUnit.BtuPerHourSquareFoot)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerMinuteSquareFoot, quantity => new HeatFlux(quantity.Value/1.89275445e2, HeatFluxUnit.BtuPerMinuteSquareFoot)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareFoot, quantity => new HeatFlux(quantity.Value/1.13565267e4, HeatFluxUnit.BtuPerSecondSquareFoot)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareInch, quantity => new HeatFlux(quantity.Value/1.63533984e6, HeatFluxUnit.BtuPerSecondSquareInch)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CaloriePerSecondSquareCentimeter, quantity => new HeatFlux(quantity.Value/4.1868e4, HeatFluxUnit.CaloriePerSecondSquareCentimeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CentiwattPerSquareMeter, quantity => new HeatFlux((quantity.Value) / 1e-2d, HeatFluxUnit.CentiwattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.DeciwattPerSquareMeter, quantity => new HeatFlux((quantity.Value) / 1e-1d, HeatFluxUnit.DeciwattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerHourSquareMeter, quantity => new HeatFlux(quantity.Value/1.163, HeatFluxUnit.KilocaloriePerHourSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, quantity => new HeatFlux((quantity.Value/4.1868e4) / 1e3d, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilowattPerSquareMeter, quantity => new HeatFlux((quantity.Value) / 1e3d, HeatFluxUnit.KilowattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MicrowattPerSquareMeter, quantity => new HeatFlux((quantity.Value) / 1e-6d, HeatFluxUnit.MicrowattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MilliwattPerSquareMeter, quantity => new HeatFlux((quantity.Value) / 1e-3d, HeatFluxUnit.MilliwattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.NanowattPerSquareMeter, quantity => new HeatFlux((quantity.Value) / 1e-9d, HeatFluxUnit.NanowattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundForcePerFootSecond, quantity => new HeatFlux(quantity.Value/1.459390293720636e1, HeatFluxUnit.PoundForcePerFootSecond)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundPerSecondCubed, quantity => new HeatFlux(quantity.Value/4.5359237e-1, HeatFluxUnit.PoundPerSecondCubed)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareFoot, quantity => new HeatFlux(quantity.Value/1.07639e1, HeatFluxUnit.WattPerSquareFoot)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareInch, quantity => new HeatFlux(quantity.Value/1.5500031e3, HeatFluxUnit.WattPerSquareInch)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity); // Register in unit converter: HeatFluxUnit -> BaseUnit - unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerHourSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerMinuteSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerSecondSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerSecondSquareInch, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.CaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.CentiwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.DeciwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.KilocaloriePerHourSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.KilowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.MicrowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.MilliwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.NanowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.PoundForcePerFootSecond, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.PoundPerSecondCubed, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareInch, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerHourSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*3.15459075, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerMinuteSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*1.89275445e2, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerSecondSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*1.13565267e4, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerSecondSquareInch, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*1.63533984e6, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.CaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*4.1868e4, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.CentiwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux((quantity.Value) * 1e-2d, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.DeciwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux((quantity.Value) * 1e-1d, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.KilocaloriePerHourSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*1.163, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux((quantity.Value*4.1868e4) * 1e3d, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.KilowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux((quantity.Value) * 1e3d, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.MicrowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux((quantity.Value) * 1e-6d, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.MilliwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux((quantity.Value) * 1e-3d, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.NanowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux((quantity.Value) * 1e-9d, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.PoundForcePerFootSecond, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*1.459390293720636e1, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.PoundPerSecondCubed, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*4.5359237e-1, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*1.07639e1, HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareInch, HeatFluxUnit.WattPerSquareMeter, quantity => new HeatFlux(quantity.Value*1.5500031e3, HeatFluxUnit.WattPerSquareMeter)); } /// @@ -905,11 +912,42 @@ double IQuantity.As(Enum unit) /// /// Converts this HeatFlux to another HeatFlux with the unit representation . /// + /// The unit to convert to. /// A HeatFlux with the specified unit. public HeatFlux ToUnit(HeatFluxUnit unit) { - var convertedValue = GetValueAs(unit); - return new HeatFlux(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this HeatFlux to another HeatFlux using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A HeatFlux with the specified unit. + public HeatFlux ToUnit(HeatFluxUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(HeatFlux), Unit, typeof(HeatFlux), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (HeatFlux)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -918,7 +956,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is HeatFluxUnit unitAsHeatFluxUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatFluxUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsHeatFluxUnit); + return ToUnit(unitAsHeatFluxUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is HeatFluxUnit unitAsHeatFluxUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatFluxUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsHeatFluxUnit, unitConverter); } /// @@ -943,81 +990,15 @@ public HeatFlux ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(HeatFluxUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case HeatFluxUnit.BtuPerHourSquareFoot: return _value*3.15459075; - case HeatFluxUnit.BtuPerMinuteSquareFoot: return _value*1.89275445e2; - case HeatFluxUnit.BtuPerSecondSquareFoot: return _value*1.13565267e4; - case HeatFluxUnit.BtuPerSecondSquareInch: return _value*1.63533984e6; - case HeatFluxUnit.CaloriePerSecondSquareCentimeter: return _value*4.1868e4; - case HeatFluxUnit.CentiwattPerSquareMeter: return (_value) * 1e-2d; - case HeatFluxUnit.DeciwattPerSquareMeter: return (_value) * 1e-1d; - case HeatFluxUnit.KilocaloriePerHourSquareMeter: return _value*1.163; - case HeatFluxUnit.KilocaloriePerSecondSquareCentimeter: return (_value*4.1868e4) * 1e3d; - case HeatFluxUnit.KilowattPerSquareMeter: return (_value) * 1e3d; - case HeatFluxUnit.MicrowattPerSquareMeter: return (_value) * 1e-6d; - case HeatFluxUnit.MilliwattPerSquareMeter: return (_value) * 1e-3d; - case HeatFluxUnit.NanowattPerSquareMeter: return (_value) * 1e-9d; - case HeatFluxUnit.PoundForcePerFootSecond: return _value*1.459390293720636e1; - case HeatFluxUnit.PoundPerSecondCubed: return _value*4.5359237e-1; - case HeatFluxUnit.WattPerSquareFoot: return _value*1.07639e1; - case HeatFluxUnit.WattPerSquareInch: return _value*1.5500031e3; - case HeatFluxUnit.WattPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(HeatFluxUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal HeatFlux ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new HeatFlux(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(HeatFluxUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case HeatFluxUnit.BtuPerHourSquareFoot: return baseUnitValue/3.15459075; - case HeatFluxUnit.BtuPerMinuteSquareFoot: return baseUnitValue/1.89275445e2; - case HeatFluxUnit.BtuPerSecondSquareFoot: return baseUnitValue/1.13565267e4; - case HeatFluxUnit.BtuPerSecondSquareInch: return baseUnitValue/1.63533984e6; - case HeatFluxUnit.CaloriePerSecondSquareCentimeter: return baseUnitValue/4.1868e4; - case HeatFluxUnit.CentiwattPerSquareMeter: return (baseUnitValue) / 1e-2d; - case HeatFluxUnit.DeciwattPerSquareMeter: return (baseUnitValue) / 1e-1d; - case HeatFluxUnit.KilocaloriePerHourSquareMeter: return baseUnitValue/1.163; - case HeatFluxUnit.KilocaloriePerSecondSquareCentimeter: return (baseUnitValue/4.1868e4) / 1e3d; - case HeatFluxUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; - case HeatFluxUnit.MicrowattPerSquareMeter: return (baseUnitValue) / 1e-6d; - case HeatFluxUnit.MilliwattPerSquareMeter: return (baseUnitValue) / 1e-3d; - case HeatFluxUnit.NanowattPerSquareMeter: return (baseUnitValue) / 1e-9d; - case HeatFluxUnit.PoundForcePerFootSecond: return baseUnitValue/1.459390293720636e1; - case HeatFluxUnit.PoundPerSecondCubed: return baseUnitValue/4.5359237e-1; - case HeatFluxUnit.WattPerSquareFoot: return baseUnitValue/1.07639e1; - case HeatFluxUnit.WattPerSquareInch: return baseUnitValue/1.5500031e3; - case HeatFluxUnit.WattPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs index 035fb2a2cd..d68bbf0e57 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs @@ -67,6 +67,8 @@ static HeatTransferCoefficient() new UnitInfo(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, "WattsPerSquareMeterKelvin", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.HeatTransferCoefficient); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -105,6 +107,11 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -207,15 +214,15 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> HeatTransferCoefficientUnit - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit)); - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius)); + unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, quantity => new HeatTransferCoefficient(quantity.Value / 5.6782633411134878, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit)); + unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, quantity => new HeatTransferCoefficient(quantity.Value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity); // Register in unit converter: HeatTransferCoefficientUnit -> BaseUnit - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => new HeatTransferCoefficient(quantity.Value * 5.6782633411134878, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin)); + unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => new HeatTransferCoefficient(quantity.Value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin)); } /// @@ -650,11 +657,42 @@ double IQuantity.As(Enum unit) /// /// Converts this HeatTransferCoefficient to another HeatTransferCoefficient with the unit representation . /// + /// The unit to convert to. /// A HeatTransferCoefficient with the specified unit. public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) { - var convertedValue = GetValueAs(unit); - return new HeatTransferCoefficient(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this HeatTransferCoefficient to another HeatTransferCoefficient using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A HeatTransferCoefficient with the specified unit. + public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(HeatTransferCoefficient), Unit, typeof(HeatTransferCoefficient), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (HeatTransferCoefficient)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -663,7 +701,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is HeatTransferCoefficientUnit unitAsHeatTransferCoefficientUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatTransferCoefficientUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsHeatTransferCoefficientUnit); + return ToUnit(unitAsHeatTransferCoefficientUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is HeatTransferCoefficientUnit unitAsHeatTransferCoefficientUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatTransferCoefficientUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsHeatTransferCoefficientUnit, unitConverter); } /// @@ -688,51 +735,15 @@ public HeatTransferCoefficient ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(HeatTransferCoefficientUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit: return _value * 5.6782633411134878; - case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return _value; - case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(HeatTransferCoefficientUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal HeatTransferCoefficient ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new HeatTransferCoefficient(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(HeatTransferCoefficientUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit: return baseUnitValue / 5.6782633411134878; - case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return baseUnitValue; - case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs index 497a8c8acc..c8cad2b403 100644 --- a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs @@ -71,6 +71,8 @@ static Illuminance() new UnitInfo(IlluminanceUnit.Millilux, "Millilux", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Illuminance); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -109,6 +111,11 @@ public Illuminance(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -216,17 +223,17 @@ public Illuminance(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> IlluminanceUnit - unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Kilolux, quantity => quantity.ToUnit(IlluminanceUnit.Kilolux)); - unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Megalux, quantity => quantity.ToUnit(IlluminanceUnit.Megalux)); - unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Millilux, quantity => quantity.ToUnit(IlluminanceUnit.Millilux)); + unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Kilolux, quantity => new Illuminance((quantity.Value) / 1e3d, IlluminanceUnit.Kilolux)); + unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Megalux, quantity => new Illuminance((quantity.Value) / 1e6d, IlluminanceUnit.Megalux)); + unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Millilux, quantity => new Illuminance((quantity.Value) / 1e-3d, IlluminanceUnit.Millilux)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Lux, quantity => quantity); // Register in unit converter: IlluminanceUnit -> BaseUnit - unitConverter.SetConversionFunction(IlluminanceUnit.Kilolux, IlluminanceUnit.Lux, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IlluminanceUnit.Megalux, IlluminanceUnit.Lux, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IlluminanceUnit.Millilux, IlluminanceUnit.Lux, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(IlluminanceUnit.Kilolux, IlluminanceUnit.Lux, quantity => new Illuminance((quantity.Value) * 1e3d, IlluminanceUnit.Lux)); + unitConverter.SetConversionFunction(IlluminanceUnit.Megalux, IlluminanceUnit.Lux, quantity => new Illuminance((quantity.Value) * 1e6d, IlluminanceUnit.Lux)); + unitConverter.SetConversionFunction(IlluminanceUnit.Millilux, IlluminanceUnit.Lux, quantity => new Illuminance((quantity.Value) * 1e-3d, IlluminanceUnit.Lux)); } /// @@ -670,11 +677,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Illuminance to another Illuminance with the unit representation . /// + /// The unit to convert to. /// A Illuminance with the specified unit. public Illuminance ToUnit(IlluminanceUnit unit) { - var convertedValue = GetValueAs(unit); - return new Illuminance(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Illuminance to another Illuminance using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Illuminance with the specified unit. + public Illuminance ToUnit(IlluminanceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Illuminance), Unit, typeof(Illuminance), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Illuminance)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -683,7 +721,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is IlluminanceUnit unitAsIlluminanceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IlluminanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsIlluminanceUnit); + return ToUnit(unitAsIlluminanceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is IlluminanceUnit unitAsIlluminanceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IlluminanceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsIlluminanceUnit, unitConverter); } /// @@ -708,53 +755,15 @@ public Illuminance ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(IlluminanceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case IlluminanceUnit.Kilolux: return (_value) * 1e3d; - case IlluminanceUnit.Lux: return _value; - case IlluminanceUnit.Megalux: return (_value) * 1e6d; - case IlluminanceUnit.Millilux: return (_value) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(IlluminanceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Illuminance ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Illuminance(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(IlluminanceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case IlluminanceUnit.Kilolux: return (baseUnitValue) / 1e3d; - case IlluminanceUnit.Lux: return baseUnitValue; - case IlluminanceUnit.Megalux: return (baseUnitValue) / 1e6d; - case IlluminanceUnit.Millilux: return (baseUnitValue) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Information.g.cs b/UnitsNet/GeneratedCode/Quantities/Information.g.cs index 4925ace301..be8ff4f661 100644 --- a/UnitsNet/GeneratedCode/Quantities/Information.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Information.g.cs @@ -90,6 +90,8 @@ static Information() new UnitInfo(InformationUnit.Terabyte, "Terabytes", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Information); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -128,6 +130,11 @@ public Information(decimal value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -350,61 +357,61 @@ public Information(decimal value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> InformationUnit - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Byte, quantity => quantity.ToUnit(InformationUnit.Byte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exabit, quantity => quantity.ToUnit(InformationUnit.Exabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exabyte, quantity => quantity.ToUnit(InformationUnit.Exabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exbibit, quantity => quantity.ToUnit(InformationUnit.Exbibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exbibyte, quantity => quantity.ToUnit(InformationUnit.Exbibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gibibit, quantity => quantity.ToUnit(InformationUnit.Gibibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gibibyte, quantity => quantity.ToUnit(InformationUnit.Gibibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gigabit, quantity => quantity.ToUnit(InformationUnit.Gigabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gigabyte, quantity => quantity.ToUnit(InformationUnit.Gigabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kibibit, quantity => quantity.ToUnit(InformationUnit.Kibibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kibibyte, quantity => quantity.ToUnit(InformationUnit.Kibibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kilobit, quantity => quantity.ToUnit(InformationUnit.Kilobit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kilobyte, quantity => quantity.ToUnit(InformationUnit.Kilobyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Mebibit, quantity => quantity.ToUnit(InformationUnit.Mebibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Mebibyte, quantity => quantity.ToUnit(InformationUnit.Mebibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Megabit, quantity => quantity.ToUnit(InformationUnit.Megabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Megabyte, quantity => quantity.ToUnit(InformationUnit.Megabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Pebibit, quantity => quantity.ToUnit(InformationUnit.Pebibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Pebibyte, quantity => quantity.ToUnit(InformationUnit.Pebibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Petabit, quantity => quantity.ToUnit(InformationUnit.Petabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Petabyte, quantity => quantity.ToUnit(InformationUnit.Petabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Tebibit, quantity => quantity.ToUnit(InformationUnit.Tebibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Tebibyte, quantity => quantity.ToUnit(InformationUnit.Tebibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Terabit, quantity => quantity.ToUnit(InformationUnit.Terabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Terabyte, quantity => quantity.ToUnit(InformationUnit.Terabyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Byte, quantity => new Information(quantity.Value/8m, InformationUnit.Byte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exabit, quantity => new Information((quantity.Value) / 1e18m, InformationUnit.Exabit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exabyte, quantity => new Information((quantity.Value/8m) / 1e18m, InformationUnit.Exabyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exbibit, quantity => new Information((quantity.Value) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Exbibit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exbibyte, quantity => new Information((quantity.Value/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Exbibyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gibibit, quantity => new Information((quantity.Value) / (1024m * 1024 * 1024), InformationUnit.Gibibit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gibibyte, quantity => new Information((quantity.Value/8m) / (1024m * 1024 * 1024), InformationUnit.Gibibyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gigabit, quantity => new Information((quantity.Value) / 1e9m, InformationUnit.Gigabit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gigabyte, quantity => new Information((quantity.Value/8m) / 1e9m, InformationUnit.Gigabyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kibibit, quantity => new Information((quantity.Value) / 1024m, InformationUnit.Kibibit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kibibyte, quantity => new Information((quantity.Value/8m) / 1024m, InformationUnit.Kibibyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kilobit, quantity => new Information((quantity.Value) / 1e3m, InformationUnit.Kilobit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kilobyte, quantity => new Information((quantity.Value/8m) / 1e3m, InformationUnit.Kilobyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Mebibit, quantity => new Information((quantity.Value) / (1024m * 1024), InformationUnit.Mebibit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Mebibyte, quantity => new Information((quantity.Value/8m) / (1024m * 1024), InformationUnit.Mebibyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Megabit, quantity => new Information((quantity.Value) / 1e6m, InformationUnit.Megabit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Megabyte, quantity => new Information((quantity.Value/8m) / 1e6m, InformationUnit.Megabyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Pebibit, quantity => new Information((quantity.Value) / (1024m * 1024 * 1024 * 1024 * 1024), InformationUnit.Pebibit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Pebibyte, quantity => new Information((quantity.Value/8m) / (1024m * 1024 * 1024 * 1024 * 1024), InformationUnit.Pebibyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Petabit, quantity => new Information((quantity.Value) / 1e15m, InformationUnit.Petabit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Petabyte, quantity => new Information((quantity.Value/8m) / 1e15m, InformationUnit.Petabyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Tebibit, quantity => new Information((quantity.Value) / (1024m * 1024 * 1024 * 1024), InformationUnit.Tebibit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Tebibyte, quantity => new Information((quantity.Value/8m) / (1024m * 1024 * 1024 * 1024), InformationUnit.Tebibyte)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Terabit, quantity => new Information((quantity.Value) / 1e12m, InformationUnit.Terabit)); + unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Terabyte, quantity => new Information((quantity.Value/8m) / 1e12m, InformationUnit.Terabyte)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Bit, quantity => quantity); // Register in unit converter: InformationUnit -> BaseUnit - unitConverter.SetConversionFunction(InformationUnit.Byte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Exabit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Exabyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Exbibit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Exbibyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Gibibit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Gibibyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Gigabit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Gigabyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Kibibit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Kibibyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Kilobit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Kilobyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Mebibit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Mebibyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Megabit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Megabyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Pebibit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Pebibyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Petabit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Petabyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Tebibit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Tebibyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Terabit, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(InformationUnit.Terabyte, InformationUnit.Bit, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(InformationUnit.Byte, InformationUnit.Bit, quantity => new Information(quantity.Value*8m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Exabit, InformationUnit.Bit, quantity => new Information((quantity.Value) * 1e18m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Exabyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * 1e18m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Exbibit, InformationUnit.Bit, quantity => new Information((quantity.Value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Exbibyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Gibibit, InformationUnit.Bit, quantity => new Information((quantity.Value) * (1024m * 1024 * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Gibibyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * (1024m * 1024 * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Gigabit, InformationUnit.Bit, quantity => new Information((quantity.Value) * 1e9m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Gigabyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * 1e9m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Kibibit, InformationUnit.Bit, quantity => new Information((quantity.Value) * 1024m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Kibibyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * 1024m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Kilobit, InformationUnit.Bit, quantity => new Information((quantity.Value) * 1e3m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Kilobyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * 1e3m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Mebibit, InformationUnit.Bit, quantity => new Information((quantity.Value) * (1024m * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Mebibyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * (1024m * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Megabit, InformationUnit.Bit, quantity => new Information((quantity.Value) * 1e6m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Megabyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * 1e6m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Pebibit, InformationUnit.Bit, quantity => new Information((quantity.Value) * (1024m * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Pebibyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * (1024m * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Petabit, InformationUnit.Bit, quantity => new Information((quantity.Value) * 1e15m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Petabyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * 1e15m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Tebibit, InformationUnit.Bit, quantity => new Information((quantity.Value) * (1024m * 1024 * 1024 * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Tebibyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * (1024m * 1024 * 1024 * 1024), InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Terabit, InformationUnit.Bit, quantity => new Information((quantity.Value) * 1e12m, InformationUnit.Bit)); + unitConverter.SetConversionFunction(InformationUnit.Terabyte, InformationUnit.Bit, quantity => new Information((quantity.Value*8m) * 1e12m, InformationUnit.Bit)); } /// @@ -1046,11 +1053,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Information to another Information with the unit representation . /// + /// The unit to convert to. /// A Information with the specified unit. public Information ToUnit(InformationUnit unit) { - var convertedValue = GetValueAs(unit); - return new Information(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Information to another Information using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Information with the specified unit. + public Information ToUnit(InformationUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Information), Unit, typeof(Information), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Information)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1059,7 +1097,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is InformationUnit unitAsInformationUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(InformationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsInformationUnit); + return ToUnit(unitAsInformationUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is InformationUnit unitAsInformationUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(InformationUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsInformationUnit, unitConverter); } /// @@ -1084,97 +1131,15 @@ public Information ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(InformationUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private decimal GetValueInBaseUnit() - { - switch(Unit) - { - case InformationUnit.Bit: return _value; - case InformationUnit.Byte: return _value*8m; - case InformationUnit.Exabit: return (_value) * 1e18m; - case InformationUnit.Exabyte: return (_value*8m) * 1e18m; - case InformationUnit.Exbibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Exbibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Gibibit: return (_value) * (1024m * 1024 * 1024); - case InformationUnit.Gibibyte: return (_value*8m) * (1024m * 1024 * 1024); - case InformationUnit.Gigabit: return (_value) * 1e9m; - case InformationUnit.Gigabyte: return (_value*8m) * 1e9m; - case InformationUnit.Kibibit: return (_value) * 1024m; - case InformationUnit.Kibibyte: return (_value*8m) * 1024m; - case InformationUnit.Kilobit: return (_value) * 1e3m; - case InformationUnit.Kilobyte: return (_value*8m) * 1e3m; - case InformationUnit.Mebibit: return (_value) * (1024m * 1024); - case InformationUnit.Mebibyte: return (_value*8m) * (1024m * 1024); - case InformationUnit.Megabit: return (_value) * 1e6m; - case InformationUnit.Megabyte: return (_value*8m) * 1e6m; - case InformationUnit.Pebibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Pebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Petabit: return (_value) * 1e15m; - case InformationUnit.Petabyte: return (_value*8m) * 1e15m; - case InformationUnit.Tebibit: return (_value) * (1024m * 1024 * 1024 * 1024); - case InformationUnit.Tebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024); - case InformationUnit.Terabit: return (_value) * 1e12m; - case InformationUnit.Terabyte: return (_value*8m) * 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(InformationUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Information ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Information(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private decimal GetValueAs(InformationUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case InformationUnit.Bit: return baseUnitValue; - case InformationUnit.Byte: return baseUnitValue/8m; - case InformationUnit.Exabit: return (baseUnitValue) / 1e18m; - case InformationUnit.Exabyte: return (baseUnitValue/8m) / 1e18m; - case InformationUnit.Exbibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Exbibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Gibibit: return (baseUnitValue) / (1024m * 1024 * 1024); - case InformationUnit.Gibibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024); - case InformationUnit.Gigabit: return (baseUnitValue) / 1e9m; - case InformationUnit.Gigabyte: return (baseUnitValue/8m) / 1e9m; - case InformationUnit.Kibibit: return (baseUnitValue) / 1024m; - case InformationUnit.Kibibyte: return (baseUnitValue/8m) / 1024m; - case InformationUnit.Kilobit: return (baseUnitValue) / 1e3m; - case InformationUnit.Kilobyte: return (baseUnitValue/8m) / 1e3m; - case InformationUnit.Mebibit: return (baseUnitValue) / (1024m * 1024); - case InformationUnit.Mebibyte: return (baseUnitValue/8m) / (1024m * 1024); - case InformationUnit.Megabit: return (baseUnitValue) / 1e6m; - case InformationUnit.Megabyte: return (baseUnitValue/8m) / 1e6m; - case InformationUnit.Pebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Pebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Petabit: return (baseUnitValue) / 1e15m; - case InformationUnit.Petabyte: return (baseUnitValue/8m) / 1e15m; - case InformationUnit.Tebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); - case InformationUnit.Tebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024); - case InformationUnit.Terabit: return (baseUnitValue) / 1e12m; - case InformationUnit.Terabyte: return (baseUnitValue/8m) / 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (decimal)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs index de6e2f75fa..465440fd78 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs @@ -78,6 +78,8 @@ static Irradiance() new UnitInfo(IrradianceUnit.WattPerSquareMeter, "WattsPerSquareMeter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Irradiance); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -116,6 +118,11 @@ public Irradiance(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -273,37 +280,37 @@ public Irradiance(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> IrradianceUnit - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.KilowattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.KilowattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.MegawattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.MegawattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.MicrowattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.MicrowattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.MilliwattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.MilliwattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.NanowattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.NanowattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.PicowattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.PicowattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.WattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareCentimeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareCentimeter, quantity => new Irradiance((quantity.Value*0.0001) / 1e3d, IrradianceUnit.KilowattPerSquareCentimeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareMeter, quantity => new Irradiance((quantity.Value) / 1e3d, IrradianceUnit.KilowattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareCentimeter, quantity => new Irradiance((quantity.Value*0.0001) / 1e6d, IrradianceUnit.MegawattPerSquareCentimeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareMeter, quantity => new Irradiance((quantity.Value) / 1e6d, IrradianceUnit.MegawattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareCentimeter, quantity => new Irradiance((quantity.Value*0.0001) / 1e-6d, IrradianceUnit.MicrowattPerSquareCentimeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareMeter, quantity => new Irradiance((quantity.Value) / 1e-6d, IrradianceUnit.MicrowattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareCentimeter, quantity => new Irradiance((quantity.Value*0.0001) / 1e-3d, IrradianceUnit.MilliwattPerSquareCentimeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareMeter, quantity => new Irradiance((quantity.Value) / 1e-3d, IrradianceUnit.MilliwattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareCentimeter, quantity => new Irradiance((quantity.Value*0.0001) / 1e-9d, IrradianceUnit.NanowattPerSquareCentimeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareMeter, quantity => new Irradiance((quantity.Value) / 1e-9d, IrradianceUnit.NanowattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareCentimeter, quantity => new Irradiance((quantity.Value*0.0001) / 1e-12d, IrradianceUnit.PicowattPerSquareCentimeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareMeter, quantity => new Irradiance((quantity.Value) / 1e-12d, IrradianceUnit.PicowattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.WattPerSquareCentimeter, quantity => new Irradiance(quantity.Value*0.0001, IrradianceUnit.WattPerSquareCentimeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity); // Register in unit converter: IrradianceUnit -> BaseUnit - unitConverter.SetConversionFunction(IrradianceUnit.KilowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.KilowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.MegawattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.MegawattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.MicrowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.MicrowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.MilliwattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.MilliwattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.NanowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.NanowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.PicowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.PicowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(IrradianceUnit.KilowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value*10000) * 1e3d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.KilowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value) * 1e3d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.MegawattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value*10000) * 1e6d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.MegawattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value) * 1e6d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.MicrowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value*10000) * 1e-6d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.MicrowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value) * 1e-6d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.MilliwattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value*10000) * 1e-3d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.MilliwattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value) * 1e-3d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.NanowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value*10000) * 1e-9d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.NanowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value) * 1e-9d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.PicowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value*10000) * 1e-12d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.PicowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance((quantity.Value) * 1e-12d, IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => new Irradiance(quantity.Value*10000, IrradianceUnit.WattPerSquareMeter)); } /// @@ -837,11 +844,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Irradiance to another Irradiance with the unit representation . /// + /// The unit to convert to. /// A Irradiance with the specified unit. public Irradiance ToUnit(IrradianceUnit unit) { - var convertedValue = GetValueAs(unit); - return new Irradiance(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Irradiance to another Irradiance using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Irradiance with the specified unit. + public Irradiance ToUnit(IrradianceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Irradiance), Unit, typeof(Irradiance), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Irradiance)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -850,7 +888,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is IrradianceUnit unitAsIrradianceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradianceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsIrradianceUnit); + return ToUnit(unitAsIrradianceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is IrradianceUnit unitAsIrradianceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradianceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsIrradianceUnit, unitConverter); } /// @@ -875,73 +922,15 @@ public Irradiance ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(IrradianceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case IrradianceUnit.KilowattPerSquareCentimeter: return (_value*10000) * 1e3d; - case IrradianceUnit.KilowattPerSquareMeter: return (_value) * 1e3d; - case IrradianceUnit.MegawattPerSquareCentimeter: return (_value*10000) * 1e6d; - case IrradianceUnit.MegawattPerSquareMeter: return (_value) * 1e6d; - case IrradianceUnit.MicrowattPerSquareCentimeter: return (_value*10000) * 1e-6d; - case IrradianceUnit.MicrowattPerSquareMeter: return (_value) * 1e-6d; - case IrradianceUnit.MilliwattPerSquareCentimeter: return (_value*10000) * 1e-3d; - case IrradianceUnit.MilliwattPerSquareMeter: return (_value) * 1e-3d; - case IrradianceUnit.NanowattPerSquareCentimeter: return (_value*10000) * 1e-9d; - case IrradianceUnit.NanowattPerSquareMeter: return (_value) * 1e-9d; - case IrradianceUnit.PicowattPerSquareCentimeter: return (_value*10000) * 1e-12d; - case IrradianceUnit.PicowattPerSquareMeter: return (_value) * 1e-12d; - case IrradianceUnit.WattPerSquareCentimeter: return _value*10000; - case IrradianceUnit.WattPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(IrradianceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Irradiance ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Irradiance(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(IrradianceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case IrradianceUnit.KilowattPerSquareCentimeter: return (baseUnitValue*0.0001) / 1e3d; - case IrradianceUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; - case IrradianceUnit.MegawattPerSquareCentimeter: return (baseUnitValue*0.0001) / 1e6d; - case IrradianceUnit.MegawattPerSquareMeter: return (baseUnitValue) / 1e6d; - case IrradianceUnit.MicrowattPerSquareCentimeter: return (baseUnitValue*0.0001) / 1e-6d; - case IrradianceUnit.MicrowattPerSquareMeter: return (baseUnitValue) / 1e-6d; - case IrradianceUnit.MilliwattPerSquareCentimeter: return (baseUnitValue*0.0001) / 1e-3d; - case IrradianceUnit.MilliwattPerSquareMeter: return (baseUnitValue) / 1e-3d; - case IrradianceUnit.NanowattPerSquareCentimeter: return (baseUnitValue*0.0001) / 1e-9d; - case IrradianceUnit.NanowattPerSquareMeter: return (baseUnitValue) / 1e-9d; - case IrradianceUnit.PicowattPerSquareCentimeter: return (baseUnitValue*0.0001) / 1e-12d; - case IrradianceUnit.PicowattPerSquareMeter: return (baseUnitValue) / 1e-12d; - case IrradianceUnit.WattPerSquareCentimeter: return baseUnitValue*0.0001; - case IrradianceUnit.WattPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs index 68c0a9c674..ab538380dd 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs @@ -74,6 +74,8 @@ static Irradiation() new UnitInfo(IrradiationUnit.WattHourPerSquareMeter, "WattHoursPerSquareMeter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Irradiation); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -112,6 +114,11 @@ public Irradiation(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -234,23 +241,23 @@ public Irradiation(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> IrradiationUnit - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareCentimeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareMillimeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMillimeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilojoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.KilojoulePerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilowattHourPerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.KilowattHourPerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.MillijoulePerSquareCentimeter, quantity => quantity.ToUnit(IrradiationUnit.MillijoulePerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.WattHourPerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.WattHourPerSquareMeter)); + unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareCentimeter, quantity => new Irradiation(quantity.Value/1e4, IrradiationUnit.JoulePerSquareCentimeter)); + unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareMillimeter, quantity => new Irradiation(quantity.Value/1e6, IrradiationUnit.JoulePerSquareMillimeter)); + unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilojoulePerSquareMeter, quantity => new Irradiation((quantity.Value) / 1e3d, IrradiationUnit.KilojoulePerSquareMeter)); + unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilowattHourPerSquareMeter, quantity => new Irradiation((quantity.Value/3600d) / 1e3d, IrradiationUnit.KilowattHourPerSquareMeter)); + unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.MillijoulePerSquareCentimeter, quantity => new Irradiation((quantity.Value/1e4) / 1e-3d, IrradiationUnit.MillijoulePerSquareCentimeter)); + unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.WattHourPerSquareMeter, quantity => new Irradiation(quantity.Value/3600d, IrradiationUnit.WattHourPerSquareMeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity); // Register in unit converter: IrradiationUnit -> BaseUnit - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMillimeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradiationUnit.KilojoulePerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradiationUnit.KilowattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradiationUnit.MillijoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(IrradiationUnit.WattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter, quantity => new Irradiation(quantity.Value*1e4, IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMillimeter, IrradiationUnit.JoulePerSquareMeter, quantity => new Irradiation(quantity.Value*1e6, IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction(IrradiationUnit.KilojoulePerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => new Irradiation((quantity.Value) * 1e3d, IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction(IrradiationUnit.KilowattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => new Irradiation((quantity.Value*3600d) * 1e3d, IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction(IrradiationUnit.MillijoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter, quantity => new Irradiation((quantity.Value*1e4) * 1e-3d, IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction(IrradiationUnit.WattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => new Irradiation(quantity.Value*3600d, IrradiationUnit.JoulePerSquareMeter)); } /// @@ -721,11 +728,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Irradiation to another Irradiation with the unit representation . /// + /// The unit to convert to. /// A Irradiation with the specified unit. public Irradiation ToUnit(IrradiationUnit unit) { - var convertedValue = GetValueAs(unit); - return new Irradiation(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Irradiation to another Irradiation using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Irradiation with the specified unit. + public Irradiation ToUnit(IrradiationUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Irradiation), Unit, typeof(Irradiation), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Irradiation)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -734,7 +772,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is IrradiationUnit unitAsIrradiationUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradiationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsIrradiationUnit); + return ToUnit(unitAsIrradiationUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is IrradiationUnit unitAsIrradiationUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradiationUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsIrradiationUnit, unitConverter); } /// @@ -759,59 +806,15 @@ public Irradiation ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(IrradiationUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case IrradiationUnit.JoulePerSquareCentimeter: return _value*1e4; - case IrradiationUnit.JoulePerSquareMeter: return _value; - case IrradiationUnit.JoulePerSquareMillimeter: return _value*1e6; - case IrradiationUnit.KilojoulePerSquareMeter: return (_value) * 1e3d; - case IrradiationUnit.KilowattHourPerSquareMeter: return (_value*3600d) * 1e3d; - case IrradiationUnit.MillijoulePerSquareCentimeter: return (_value*1e4) * 1e-3d; - case IrradiationUnit.WattHourPerSquareMeter: return _value*3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(IrradiationUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Irradiation ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Irradiation(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(IrradiationUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case IrradiationUnit.JoulePerSquareCentimeter: return baseUnitValue/1e4; - case IrradiationUnit.JoulePerSquareMeter: return baseUnitValue; - case IrradiationUnit.JoulePerSquareMillimeter: return baseUnitValue/1e6; - case IrradiationUnit.KilojoulePerSquareMeter: return (baseUnitValue) / 1e3d; - case IrradiationUnit.KilowattHourPerSquareMeter: return (baseUnitValue/3600d) / 1e3d; - case IrradiationUnit.MillijoulePerSquareCentimeter: return (baseUnitValue/1e4) / 1e-3d; - case IrradiationUnit.WattHourPerSquareMeter: return baseUnitValue/3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs index 6aa8e06c84..8c7ad7c34c 100644 --- a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs @@ -76,6 +76,8 @@ static KinematicViscosity() new UnitInfo(KinematicViscosityUnit.Stokes, "Stokes", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.KinematicViscosity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -114,6 +116,11 @@ public KinematicViscosity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -246,27 +253,27 @@ public KinematicViscosity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> KinematicViscosityUnit - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Centistokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Centistokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Decistokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Decistokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Kilostokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Kilostokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Microstokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Microstokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Millistokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Millistokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Nanostokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Nanostokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.SquareFootPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareFootPerSecond)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Stokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Stokes)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Centistokes, quantity => new KinematicViscosity((quantity.Value*1e4) / 1e-2d, KinematicViscosityUnit.Centistokes)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Decistokes, quantity => new KinematicViscosity((quantity.Value*1e4) / 1e-1d, KinematicViscosityUnit.Decistokes)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Kilostokes, quantity => new KinematicViscosity((quantity.Value*1e4) / 1e3d, KinematicViscosityUnit.Kilostokes)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Microstokes, quantity => new KinematicViscosity((quantity.Value*1e4) / 1e-6d, KinematicViscosityUnit.Microstokes)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Millistokes, quantity => new KinematicViscosity((quantity.Value*1e4) / 1e-3d, KinematicViscosityUnit.Millistokes)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Nanostokes, quantity => new KinematicViscosity((quantity.Value*1e4) / 1e-9d, KinematicViscosityUnit.Nanostokes)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.SquareFootPerSecond, quantity => new KinematicViscosity(quantity.Value*10.7639, KinematicViscosityUnit.SquareFootPerSecond)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Stokes, quantity => new KinematicViscosity(quantity.Value*1e4, KinematicViscosityUnit.Stokes)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity); // Register in unit converter: KinematicViscosityUnit -> BaseUnit - unitConverter.SetConversionFunction(KinematicViscosityUnit.Centistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Decistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Kilostokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Microstokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Millistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Nanostokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareFootPerSecond, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Stokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(KinematicViscosityUnit.Centistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => new KinematicViscosity((quantity.Value/1e4) * 1e-2d, KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.Decistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => new KinematicViscosity((quantity.Value/1e4) * 1e-1d, KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.Kilostokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => new KinematicViscosity((quantity.Value/1e4) * 1e3d, KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.Microstokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => new KinematicViscosity((quantity.Value/1e4) * 1e-6d, KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.Millistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => new KinematicViscosity((quantity.Value/1e4) * 1e-3d, KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.Nanostokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => new KinematicViscosity((quantity.Value/1e4) * 1e-9d, KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareFootPerSecond, KinematicViscosityUnit.SquareMeterPerSecond, quantity => new KinematicViscosity(quantity.Value/10.7639, KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction(KinematicViscosityUnit.Stokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => new KinematicViscosity(quantity.Value/1e4, KinematicViscosityUnit.SquareMeterPerSecond)); } /// @@ -755,11 +762,42 @@ double IQuantity.As(Enum unit) /// /// Converts this KinematicViscosity to another KinematicViscosity with the unit representation . /// + /// The unit to convert to. /// A KinematicViscosity with the specified unit. public KinematicViscosity ToUnit(KinematicViscosityUnit unit) { - var convertedValue = GetValueAs(unit); - return new KinematicViscosity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this KinematicViscosity to another KinematicViscosity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A KinematicViscosity with the specified unit. + public KinematicViscosity ToUnit(KinematicViscosityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(KinematicViscosity), Unit, typeof(KinematicViscosity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (KinematicViscosity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -768,7 +806,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is KinematicViscosityUnit unitAsKinematicViscosityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(KinematicViscosityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsKinematicViscosityUnit); + return ToUnit(unitAsKinematicViscosityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is KinematicViscosityUnit unitAsKinematicViscosityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(KinematicViscosityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsKinematicViscosityUnit, unitConverter); } /// @@ -793,63 +840,15 @@ public KinematicViscosity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(KinematicViscosityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case KinematicViscosityUnit.Centistokes: return (_value/1e4) * 1e-2d; - case KinematicViscosityUnit.Decistokes: return (_value/1e4) * 1e-1d; - case KinematicViscosityUnit.Kilostokes: return (_value/1e4) * 1e3d; - case KinematicViscosityUnit.Microstokes: return (_value/1e4) * 1e-6d; - case KinematicViscosityUnit.Millistokes: return (_value/1e4) * 1e-3d; - case KinematicViscosityUnit.Nanostokes: return (_value/1e4) * 1e-9d; - case KinematicViscosityUnit.SquareFootPerSecond: return _value/10.7639; - case KinematicViscosityUnit.SquareMeterPerSecond: return _value; - case KinematicViscosityUnit.Stokes: return _value/1e4; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(KinematicViscosityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal KinematicViscosity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new KinematicViscosity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(KinematicViscosityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case KinematicViscosityUnit.Centistokes: return (baseUnitValue*1e4) / 1e-2d; - case KinematicViscosityUnit.Decistokes: return (baseUnitValue*1e4) / 1e-1d; - case KinematicViscosityUnit.Kilostokes: return (baseUnitValue*1e4) / 1e3d; - case KinematicViscosityUnit.Microstokes: return (baseUnitValue*1e4) / 1e-6d; - case KinematicViscosityUnit.Millistokes: return (baseUnitValue*1e4) / 1e-3d; - case KinematicViscosityUnit.Nanostokes: return (baseUnitValue*1e4) / 1e-9d; - case KinematicViscosityUnit.SquareFootPerSecond: return baseUnitValue*10.7639; - case KinematicViscosityUnit.SquareMeterPerSecond: return baseUnitValue; - case KinematicViscosityUnit.Stokes: return baseUnitValue*1e4; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs b/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs index 85bb46a2aa..631689eaab 100644 --- a/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs @@ -66,6 +66,8 @@ static LapseRate() new UnitInfo(LapseRateUnit.DegreeCelsiusPerKilometer, "DegreesCelciusPerKilometer", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.LapseRate); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -104,6 +106,11 @@ public LapseRate(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -617,11 +624,42 @@ double IQuantity.As(Enum unit) /// /// Converts this LapseRate to another LapseRate with the unit representation . /// + /// The unit to convert to. /// A LapseRate with the specified unit. public LapseRate ToUnit(LapseRateUnit unit) { - var convertedValue = GetValueAs(unit); - return new LapseRate(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this LapseRate to another LapseRate using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A LapseRate with the specified unit. + public LapseRate ToUnit(LapseRateUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(LapseRate), Unit, typeof(LapseRate), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (LapseRate)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -630,7 +668,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is LapseRateUnit unitAsLapseRateUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LapseRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLapseRateUnit); + return ToUnit(unitAsLapseRateUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is LapseRateUnit unitAsLapseRateUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LapseRateUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsLapseRateUnit, unitConverter); } /// @@ -655,47 +702,15 @@ public LapseRate ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(LapseRateUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(LapseRateUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal LapseRate ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new LapseRate(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(LapseRateUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Length.g.cs b/UnitsNet/GeneratedCode/Quantities/Length.g.cs index ad8af61b2f..8d9c598f31 100644 --- a/UnitsNet/GeneratedCode/Quantities/Length.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Length.g.cs @@ -97,6 +97,8 @@ static Length() new UnitInfo(LengthUnit.Yard, "Yards", new BaseUnits(length: LengthUnit.Yard)), }, BaseUnit, Zero, BaseDimensions, QuantityType.Length); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -135,6 +137,11 @@ public Length(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -387,75 +394,75 @@ public Length(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> LengthUnit - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.AstronomicalUnit, quantity => quantity.ToUnit(LengthUnit.AstronomicalUnit)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Centimeter, quantity => quantity.ToUnit(LengthUnit.Centimeter)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Chain, quantity => quantity.ToUnit(LengthUnit.Chain)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Decimeter, quantity => quantity.ToUnit(LengthUnit.Decimeter)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.DtpPica, quantity => quantity.ToUnit(LengthUnit.DtpPica)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.DtpPoint, quantity => quantity.ToUnit(LengthUnit.DtpPoint)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Fathom, quantity => quantity.ToUnit(LengthUnit.Fathom)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Foot, quantity => quantity.ToUnit(LengthUnit.Foot)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Hand, quantity => quantity.ToUnit(LengthUnit.Hand)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Hectometer, quantity => quantity.ToUnit(LengthUnit.Hectometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, quantity => quantity.ToUnit(LengthUnit.Inch)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.KilolightYear, quantity => quantity.ToUnit(LengthUnit.KilolightYear)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Kilometer, quantity => quantity.ToUnit(LengthUnit.Kilometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Kiloparsec, quantity => quantity.ToUnit(LengthUnit.Kiloparsec)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.LightYear, quantity => quantity.ToUnit(LengthUnit.LightYear)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.MegalightYear, quantity => quantity.ToUnit(LengthUnit.MegalightYear)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Megaparsec, quantity => quantity.ToUnit(LengthUnit.Megaparsec)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Microinch, quantity => quantity.ToUnit(LengthUnit.Microinch)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Micrometer, quantity => quantity.ToUnit(LengthUnit.Micrometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Mil, quantity => quantity.ToUnit(LengthUnit.Mil)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Mile, quantity => quantity.ToUnit(LengthUnit.Mile)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Millimeter, quantity => quantity.ToUnit(LengthUnit.Millimeter)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Nanometer, quantity => quantity.ToUnit(LengthUnit.Nanometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.NauticalMile, quantity => quantity.ToUnit(LengthUnit.NauticalMile)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Parsec, quantity => quantity.ToUnit(LengthUnit.Parsec)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.PrinterPica, quantity => quantity.ToUnit(LengthUnit.PrinterPica)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.PrinterPoint, quantity => quantity.ToUnit(LengthUnit.PrinterPoint)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Shackle, quantity => quantity.ToUnit(LengthUnit.Shackle)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.SolarRadius, quantity => quantity.ToUnit(LengthUnit.SolarRadius)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Twip, quantity => quantity.ToUnit(LengthUnit.Twip)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.UsSurveyFoot, quantity => quantity.ToUnit(LengthUnit.UsSurveyFoot)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Yard, quantity => quantity.ToUnit(LengthUnit.Yard)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.AstronomicalUnit, quantity => new Length(quantity.Value / 1.4959787070e11, LengthUnit.AstronomicalUnit)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Centimeter, quantity => new Length((quantity.Value) / 1e-2d, LengthUnit.Centimeter)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Chain, quantity => new Length(quantity.Value/20.1168, LengthUnit.Chain)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Decimeter, quantity => new Length((quantity.Value) / 1e-1d, LengthUnit.Decimeter)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.DtpPica, quantity => new Length(quantity.Value*236.220472441, LengthUnit.DtpPica)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.DtpPoint, quantity => new Length((quantity.Value/2.54e-2)*72, LengthUnit.DtpPoint)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Fathom, quantity => new Length(quantity.Value/1.8288, LengthUnit.Fathom)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Foot, quantity => new Length(quantity.Value/0.3048, LengthUnit.Foot)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Hand, quantity => new Length(quantity.Value / 1.016e-1, LengthUnit.Hand)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Hectometer, quantity => new Length((quantity.Value) / 1e2d, LengthUnit.Hectometer)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, quantity => new Length(quantity.Value/2.54e-2, LengthUnit.Inch)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.KilolightYear, quantity => new Length((quantity.Value / 9.46073047258e15) / 1e3d, LengthUnit.KilolightYear)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Kilometer, quantity => new Length((quantity.Value) / 1e3d, LengthUnit.Kilometer)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Kiloparsec, quantity => new Length((quantity.Value / 3.08567758128e16) / 1e3d, LengthUnit.Kiloparsec)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.LightYear, quantity => new Length(quantity.Value / 9.46073047258e15, LengthUnit.LightYear)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.MegalightYear, quantity => new Length((quantity.Value / 9.46073047258e15) / 1e6d, LengthUnit.MegalightYear)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Megaparsec, quantity => new Length((quantity.Value / 3.08567758128e16) / 1e6d, LengthUnit.Megaparsec)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Microinch, quantity => new Length(quantity.Value/2.54e-8, LengthUnit.Microinch)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Micrometer, quantity => new Length((quantity.Value) / 1e-6d, LengthUnit.Micrometer)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Mil, quantity => new Length(quantity.Value/2.54e-5, LengthUnit.Mil)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Mile, quantity => new Length(quantity.Value/1609.34, LengthUnit.Mile)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Millimeter, quantity => new Length((quantity.Value) / 1e-3d, LengthUnit.Millimeter)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Nanometer, quantity => new Length((quantity.Value) / 1e-9d, LengthUnit.Nanometer)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.NauticalMile, quantity => new Length(quantity.Value/1852, LengthUnit.NauticalMile)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Parsec, quantity => new Length(quantity.Value / 3.08567758128e16, LengthUnit.Parsec)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.PrinterPica, quantity => new Length(quantity.Value*237.106301584, LengthUnit.PrinterPica)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.PrinterPoint, quantity => new Length((quantity.Value/2.54e-2)*72.27, LengthUnit.PrinterPoint)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Shackle, quantity => new Length(quantity.Value/27.432, LengthUnit.Shackle)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.SolarRadius, quantity => new Length(quantity.Value / 6.95510000E+08, LengthUnit.SolarRadius)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Twip, quantity => new Length(quantity.Value*56692.913385826, LengthUnit.Twip)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.UsSurveyFoot, quantity => new Length(quantity.Value*3937/1200, LengthUnit.UsSurveyFoot)); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Yard, quantity => new Length(quantity.Value/0.9144, LengthUnit.Yard)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Meter, quantity => quantity); // Register in unit converter: LengthUnit -> BaseUnit - unitConverter.SetConversionFunction(LengthUnit.AstronomicalUnit, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Centimeter, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Chain, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Decimeter, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.DtpPica, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.DtpPoint, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Fathom, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Foot, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Hand, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Hectometer, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Inch, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.KilolightYear, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Kilometer, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Kiloparsec, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.LightYear, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.MegalightYear, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Megaparsec, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Microinch, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Micrometer, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Mil, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Mile, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Millimeter, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Nanometer, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.NauticalMile, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Parsec, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.PrinterPica, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.PrinterPoint, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Shackle, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.SolarRadius, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Twip, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.UsSurveyFoot, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LengthUnit.Yard, LengthUnit.Meter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(LengthUnit.AstronomicalUnit, LengthUnit.Meter, quantity => new Length(quantity.Value * 1.4959787070e11, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Centimeter, LengthUnit.Meter, quantity => new Length((quantity.Value) * 1e-2d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Chain, LengthUnit.Meter, quantity => new Length(quantity.Value*20.1168, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Decimeter, LengthUnit.Meter, quantity => new Length((quantity.Value) * 1e-1d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.DtpPica, LengthUnit.Meter, quantity => new Length(quantity.Value/236.220472441, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.DtpPoint, LengthUnit.Meter, quantity => new Length((quantity.Value/72)*2.54e-2, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Fathom, LengthUnit.Meter, quantity => new Length(quantity.Value*1.8288, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Foot, LengthUnit.Meter, quantity => new Length(quantity.Value*0.3048, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Hand, LengthUnit.Meter, quantity => new Length(quantity.Value * 1.016e-1, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Hectometer, LengthUnit.Meter, quantity => new Length((quantity.Value) * 1e2d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Inch, LengthUnit.Meter, quantity => new Length(quantity.Value*2.54e-2, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.KilolightYear, LengthUnit.Meter, quantity => new Length((quantity.Value * 9.46073047258e15) * 1e3d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Kilometer, LengthUnit.Meter, quantity => new Length((quantity.Value) * 1e3d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Kiloparsec, LengthUnit.Meter, quantity => new Length((quantity.Value * 3.08567758128e16) * 1e3d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.LightYear, LengthUnit.Meter, quantity => new Length(quantity.Value * 9.46073047258e15, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.MegalightYear, LengthUnit.Meter, quantity => new Length((quantity.Value * 9.46073047258e15) * 1e6d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Megaparsec, LengthUnit.Meter, quantity => new Length((quantity.Value * 3.08567758128e16) * 1e6d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Microinch, LengthUnit.Meter, quantity => new Length(quantity.Value*2.54e-8, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Micrometer, LengthUnit.Meter, quantity => new Length((quantity.Value) * 1e-6d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Mil, LengthUnit.Meter, quantity => new Length(quantity.Value*2.54e-5, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Mile, LengthUnit.Meter, quantity => new Length(quantity.Value*1609.34, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Millimeter, LengthUnit.Meter, quantity => new Length((quantity.Value) * 1e-3d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Nanometer, LengthUnit.Meter, quantity => new Length((quantity.Value) * 1e-9d, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.NauticalMile, LengthUnit.Meter, quantity => new Length(quantity.Value*1852, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Parsec, LengthUnit.Meter, quantity => new Length(quantity.Value * 3.08567758128e16, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.PrinterPica, LengthUnit.Meter, quantity => new Length(quantity.Value/237.106301584, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.PrinterPoint, LengthUnit.Meter, quantity => new Length((quantity.Value/72.27)*2.54e-2, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Shackle, LengthUnit.Meter, quantity => new Length(quantity.Value*27.432, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.SolarRadius, LengthUnit.Meter, quantity => new Length(quantity.Value * 6.95510000E+08, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Twip, LengthUnit.Meter, quantity => new Length(quantity.Value/56692.913385826, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.UsSurveyFoot, LengthUnit.Meter, quantity => new Length(quantity.Value*1200/3937, LengthUnit.Meter)); + unitConverter.SetConversionFunction(LengthUnit.Yard, LengthUnit.Meter, quantity => new Length(quantity.Value*0.9144, LengthUnit.Meter)); } /// @@ -1160,11 +1167,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Length to another Length with the unit representation . /// + /// The unit to convert to. /// A Length with the specified unit. public Length ToUnit(LengthUnit unit) { - var convertedValue = GetValueAs(unit); - return new Length(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Length to another Length using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Length with the specified unit. + public Length ToUnit(LengthUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Length), Unit, typeof(Length), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Length)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1173,7 +1211,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is LengthUnit unitAsLengthUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLengthUnit); + return ToUnit(unitAsLengthUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is LengthUnit unitAsLengthUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LengthUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsLengthUnit, unitConverter); } /// @@ -1198,111 +1245,15 @@ public Length ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(LengthUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case LengthUnit.AstronomicalUnit: return _value * 1.4959787070e11; - case LengthUnit.Centimeter: return (_value) * 1e-2d; - case LengthUnit.Chain: return _value*20.1168; - case LengthUnit.Decimeter: return (_value) * 1e-1d; - case LengthUnit.DtpPica: return _value/236.220472441; - case LengthUnit.DtpPoint: return (_value/72)*2.54e-2; - case LengthUnit.Fathom: return _value*1.8288; - case LengthUnit.Foot: return _value*0.3048; - case LengthUnit.Hand: return _value * 1.016e-1; - case LengthUnit.Hectometer: return (_value) * 1e2d; - case LengthUnit.Inch: return _value*2.54e-2; - case LengthUnit.KilolightYear: return (_value * 9.46073047258e15) * 1e3d; - case LengthUnit.Kilometer: return (_value) * 1e3d; - case LengthUnit.Kiloparsec: return (_value * 3.08567758128e16) * 1e3d; - case LengthUnit.LightYear: return _value * 9.46073047258e15; - case LengthUnit.MegalightYear: return (_value * 9.46073047258e15) * 1e6d; - case LengthUnit.Megaparsec: return (_value * 3.08567758128e16) * 1e6d; - case LengthUnit.Meter: return _value; - case LengthUnit.Microinch: return _value*2.54e-8; - case LengthUnit.Micrometer: return (_value) * 1e-6d; - case LengthUnit.Mil: return _value*2.54e-5; - case LengthUnit.Mile: return _value*1609.34; - case LengthUnit.Millimeter: return (_value) * 1e-3d; - case LengthUnit.Nanometer: return (_value) * 1e-9d; - case LengthUnit.NauticalMile: return _value*1852; - case LengthUnit.Parsec: return _value * 3.08567758128e16; - case LengthUnit.PrinterPica: return _value/237.106301584; - case LengthUnit.PrinterPoint: return (_value/72.27)*2.54e-2; - case LengthUnit.Shackle: return _value*27.432; - case LengthUnit.SolarRadius: return _value * 6.95510000E+08; - case LengthUnit.Twip: return _value/56692.913385826; - case LengthUnit.UsSurveyFoot: return _value*1200/3937; - case LengthUnit.Yard: return _value*0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(LengthUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Length ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Length(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(LengthUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case LengthUnit.AstronomicalUnit: return baseUnitValue / 1.4959787070e11; - case LengthUnit.Centimeter: return (baseUnitValue) / 1e-2d; - case LengthUnit.Chain: return baseUnitValue/20.1168; - case LengthUnit.Decimeter: return (baseUnitValue) / 1e-1d; - case LengthUnit.DtpPica: return baseUnitValue*236.220472441; - case LengthUnit.DtpPoint: return (baseUnitValue/2.54e-2)*72; - case LengthUnit.Fathom: return baseUnitValue/1.8288; - case LengthUnit.Foot: return baseUnitValue/0.3048; - case LengthUnit.Hand: return baseUnitValue / 1.016e-1; - case LengthUnit.Hectometer: return (baseUnitValue) / 1e2d; - case LengthUnit.Inch: return baseUnitValue/2.54e-2; - case LengthUnit.KilolightYear: return (baseUnitValue / 9.46073047258e15) / 1e3d; - case LengthUnit.Kilometer: return (baseUnitValue) / 1e3d; - case LengthUnit.Kiloparsec: return (baseUnitValue / 3.08567758128e16) / 1e3d; - case LengthUnit.LightYear: return baseUnitValue / 9.46073047258e15; - case LengthUnit.MegalightYear: return (baseUnitValue / 9.46073047258e15) / 1e6d; - case LengthUnit.Megaparsec: return (baseUnitValue / 3.08567758128e16) / 1e6d; - case LengthUnit.Meter: return baseUnitValue; - case LengthUnit.Microinch: return baseUnitValue/2.54e-8; - case LengthUnit.Micrometer: return (baseUnitValue) / 1e-6d; - case LengthUnit.Mil: return baseUnitValue/2.54e-5; - case LengthUnit.Mile: return baseUnitValue/1609.34; - case LengthUnit.Millimeter: return (baseUnitValue) / 1e-3d; - case LengthUnit.Nanometer: return (baseUnitValue) / 1e-9d; - case LengthUnit.NauticalMile: return baseUnitValue/1852; - case LengthUnit.Parsec: return baseUnitValue / 3.08567758128e16; - case LengthUnit.PrinterPica: return baseUnitValue*237.106301584; - case LengthUnit.PrinterPoint: return (baseUnitValue/2.54e-2)*72.27; - case LengthUnit.Shackle: return baseUnitValue/27.432; - case LengthUnit.SolarRadius: return baseUnitValue / 6.95510000E+08; - case LengthUnit.Twip: return baseUnitValue*56692.913385826; - case LengthUnit.UsSurveyFoot: return baseUnitValue*3937/1200; - case LengthUnit.Yard: return baseUnitValue/0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Level.g.cs b/UnitsNet/GeneratedCode/Quantities/Level.g.cs index fb919dba5e..9a49ff10bb 100644 --- a/UnitsNet/GeneratedCode/Quantities/Level.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Level.g.cs @@ -66,6 +66,8 @@ static Level() new UnitInfo(LevelUnit.Neper, "Nepers", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Level); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -104,6 +106,11 @@ public Level(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -201,13 +208,13 @@ public Level(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> LevelUnit - unitConverter.SetConversionFunction(LevelUnit.Decibel, LevelUnit.Neper, quantity => quantity.ToUnit(LevelUnit.Neper)); + unitConverter.SetConversionFunction(LevelUnit.Decibel, LevelUnit.Neper, quantity => new Level(0.115129254*quantity.Value, LevelUnit.Neper)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(LevelUnit.Decibel, LevelUnit.Decibel, quantity => quantity); // Register in unit converter: LevelUnit -> BaseUnit - unitConverter.SetConversionFunction(LevelUnit.Neper, LevelUnit.Decibel, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(LevelUnit.Neper, LevelUnit.Decibel, quantity => new Level((1/0.115129254)*quantity.Value, LevelUnit.Decibel)); } /// @@ -641,11 +648,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Level to another Level with the unit representation . /// + /// The unit to convert to. /// A Level with the specified unit. public Level ToUnit(LevelUnit unit) { - var convertedValue = GetValueAs(unit); - return new Level(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Level to another Level using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Level with the specified unit. + public Level ToUnit(LevelUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Level), Unit, typeof(Level), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Level)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -654,7 +692,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is LevelUnit unitAsLevelUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LevelUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLevelUnit); + return ToUnit(unitAsLevelUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is LevelUnit unitAsLevelUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LevelUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsLevelUnit, unitConverter); } /// @@ -679,49 +726,15 @@ public Level ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(LevelUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case LevelUnit.Decibel: return _value; - case LevelUnit.Neper: return (1/0.115129254)*_value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(LevelUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Level ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Level(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(LevelUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case LevelUnit.Decibel: return baseUnitValue; - case LevelUnit.Neper: return 0.115129254*baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs index 039c1e412e..5a80f9c715 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs @@ -81,6 +81,8 @@ static LinearDensity() new UnitInfo(LinearDensityUnit.PoundPerInch, "PoundsPerInch", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.LinearDensity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -119,6 +121,11 @@ public LinearDensity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -276,37 +283,37 @@ public LinearDensity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> LinearDensityUnit - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.GramPerCentimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.GramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.GramPerMillimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerCentimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMillimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerCentimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerMillimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerCentimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerMillimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerFoot, quantity => quantity.ToUnit(LinearDensityUnit.PoundPerFoot)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerInch, quantity => quantity.ToUnit(LinearDensityUnit.PoundPerInch)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerCentimeter, quantity => new LinearDensity(quantity.Value/1e-1, LinearDensityUnit.GramPerCentimeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMeter, quantity => new LinearDensity(quantity.Value/1e-3, LinearDensityUnit.GramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMillimeter, quantity => new LinearDensity(quantity.Value, LinearDensityUnit.GramPerMillimeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerCentimeter, quantity => new LinearDensity((quantity.Value/1e-1) / 1e3d, LinearDensityUnit.KilogramPerCentimeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerMillimeter, quantity => new LinearDensity((quantity.Value) / 1e3d, LinearDensityUnit.KilogramPerMillimeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerCentimeter, quantity => new LinearDensity((quantity.Value/1e-1) / 1e-6d, LinearDensityUnit.MicrogramPerCentimeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMeter, quantity => new LinearDensity((quantity.Value/1e-3) / 1e-6d, LinearDensityUnit.MicrogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMillimeter, quantity => new LinearDensity((quantity.Value) / 1e-6d, LinearDensityUnit.MicrogramPerMillimeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerCentimeter, quantity => new LinearDensity((quantity.Value/1e-1) / 1e-3d, LinearDensityUnit.MilligramPerCentimeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMeter, quantity => new LinearDensity((quantity.Value/1e-3) / 1e-3d, LinearDensityUnit.MilligramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMillimeter, quantity => new LinearDensity((quantity.Value) / 1e-3d, LinearDensityUnit.MilligramPerMillimeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerFoot, quantity => new LinearDensity(quantity.Value/1.48816394, LinearDensityUnit.PoundPerFoot)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerInch, quantity => new LinearDensity(quantity.Value*5.5997415e-2, LinearDensityUnit.PoundPerInch)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity); // Register in unit converter: LinearDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(LinearDensityUnit.GramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.GramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.GramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.PoundPerFoot, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearDensityUnit.PoundPerInch, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(LinearDensityUnit.GramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity(quantity.Value*1e-1, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.GramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity(quantity.Value*1e-3, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.GramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity(quantity.Value, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity((quantity.Value*1e-1) * 1e3d, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity((quantity.Value) * 1e3d, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity((quantity.Value*1e-1) * 1e-6d, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity((quantity.Value*1e-3) * 1e-6d, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity((quantity.Value) * 1e-6d, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity((quantity.Value*1e-1) * 1e-3d, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity((quantity.Value*1e-3) * 1e-3d, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity((quantity.Value) * 1e-3d, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.PoundPerFoot, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity(quantity.Value*1.48816394, LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction(LinearDensityUnit.PoundPerInch, LinearDensityUnit.KilogramPerMeter, quantity => new LinearDensity(quantity.Value/5.5997415e-2, LinearDensityUnit.KilogramPerMeter)); } /// @@ -840,11 +847,42 @@ double IQuantity.As(Enum unit) /// /// Converts this LinearDensity to another LinearDensity with the unit representation . /// + /// The unit to convert to. /// A LinearDensity with the specified unit. public LinearDensity ToUnit(LinearDensityUnit unit) { - var convertedValue = GetValueAs(unit); - return new LinearDensity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this LinearDensity to another LinearDensity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A LinearDensity with the specified unit. + public LinearDensity ToUnit(LinearDensityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(LinearDensity), Unit, typeof(LinearDensity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (LinearDensity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -853,7 +891,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is LinearDensityUnit unitAsLinearDensityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLinearDensityUnit); + return ToUnit(unitAsLinearDensityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is LinearDensityUnit unitAsLinearDensityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsLinearDensityUnit, unitConverter); } /// @@ -878,73 +925,15 @@ public LinearDensity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(LinearDensityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case LinearDensityUnit.GramPerCentimeter: return _value*1e-1; - case LinearDensityUnit.GramPerMeter: return _value*1e-3; - case LinearDensityUnit.GramPerMillimeter: return _value; - case LinearDensityUnit.KilogramPerCentimeter: return (_value*1e-1) * 1e3d; - case LinearDensityUnit.KilogramPerMeter: return (_value*1e-3) * 1e3d; - case LinearDensityUnit.KilogramPerMillimeter: return (_value) * 1e3d; - case LinearDensityUnit.MicrogramPerCentimeter: return (_value*1e-1) * 1e-6d; - case LinearDensityUnit.MicrogramPerMeter: return (_value*1e-3) * 1e-6d; - case LinearDensityUnit.MicrogramPerMillimeter: return (_value) * 1e-6d; - case LinearDensityUnit.MilligramPerCentimeter: return (_value*1e-1) * 1e-3d; - case LinearDensityUnit.MilligramPerMeter: return (_value*1e-3) * 1e-3d; - case LinearDensityUnit.MilligramPerMillimeter: return (_value) * 1e-3d; - case LinearDensityUnit.PoundPerFoot: return _value*1.48816394; - case LinearDensityUnit.PoundPerInch: return _value/5.5997415e-2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(LinearDensityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal LinearDensity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new LinearDensity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(LinearDensityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case LinearDensityUnit.GramPerCentimeter: return baseUnitValue/1e-1; - case LinearDensityUnit.GramPerMeter: return baseUnitValue/1e-3; - case LinearDensityUnit.GramPerMillimeter: return baseUnitValue; - case LinearDensityUnit.KilogramPerCentimeter: return (baseUnitValue/1e-1) / 1e3d; - case LinearDensityUnit.KilogramPerMeter: return (baseUnitValue/1e-3) / 1e3d; - case LinearDensityUnit.KilogramPerMillimeter: return (baseUnitValue) / 1e3d; - case LinearDensityUnit.MicrogramPerCentimeter: return (baseUnitValue/1e-1) / 1e-6d; - case LinearDensityUnit.MicrogramPerMeter: return (baseUnitValue/1e-3) / 1e-6d; - case LinearDensityUnit.MicrogramPerMillimeter: return (baseUnitValue) / 1e-6d; - case LinearDensityUnit.MilligramPerCentimeter: return (baseUnitValue/1e-1) / 1e-3d; - case LinearDensityUnit.MilligramPerMeter: return (baseUnitValue/1e-3) / 1e-3d; - case LinearDensityUnit.MilligramPerMillimeter: return (baseUnitValue) / 1e-3d; - case LinearDensityUnit.PoundPerFoot: return baseUnitValue/1.48816394; - case LinearDensityUnit.PoundPerInch: return baseUnitValue*5.5997415e-2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs index d4a8867c95..b6190259cb 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs @@ -92,6 +92,8 @@ static LinearPowerDensity() new UnitInfo(LinearPowerDensityUnit.WattPerMillimeter, "WattsPerMillimeter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.LinearPowerDensity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -130,6 +132,11 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -342,59 +349,59 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> LinearPowerDensityUnit - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerMillimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerMillimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerMillimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerMillimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMillimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerCentimeter, quantity => new LinearPowerDensity((quantity.Value/1e2) / 1e9d, LinearPowerDensityUnit.GigawattPerCentimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerFoot, quantity => new LinearPowerDensity((quantity.Value/3.280839895) / 1e9d, LinearPowerDensityUnit.GigawattPerFoot)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerInch, quantity => new LinearPowerDensity((quantity.Value/39.37007874) / 1e9d, LinearPowerDensityUnit.GigawattPerInch)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMeter, quantity => new LinearPowerDensity((quantity.Value) / 1e9d, LinearPowerDensityUnit.GigawattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMillimeter, quantity => new LinearPowerDensity((quantity.Value/1e3) / 1e9d, LinearPowerDensityUnit.GigawattPerMillimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerCentimeter, quantity => new LinearPowerDensity((quantity.Value/1e2) / 1e3d, LinearPowerDensityUnit.KilowattPerCentimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerFoot, quantity => new LinearPowerDensity((quantity.Value/3.280839895) / 1e3d, LinearPowerDensityUnit.KilowattPerFoot)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerInch, quantity => new LinearPowerDensity((quantity.Value/39.37007874) / 1e3d, LinearPowerDensityUnit.KilowattPerInch)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMeter, quantity => new LinearPowerDensity((quantity.Value) / 1e3d, LinearPowerDensityUnit.KilowattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMillimeter, quantity => new LinearPowerDensity((quantity.Value/1e3) / 1e3d, LinearPowerDensityUnit.KilowattPerMillimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerCentimeter, quantity => new LinearPowerDensity((quantity.Value/1e2) / 1e6d, LinearPowerDensityUnit.MegawattPerCentimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerFoot, quantity => new LinearPowerDensity((quantity.Value/3.280839895) / 1e6d, LinearPowerDensityUnit.MegawattPerFoot)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerInch, quantity => new LinearPowerDensity((quantity.Value/39.37007874) / 1e6d, LinearPowerDensityUnit.MegawattPerInch)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMeter, quantity => new LinearPowerDensity((quantity.Value) / 1e6d, LinearPowerDensityUnit.MegawattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMillimeter, quantity => new LinearPowerDensity((quantity.Value/1e3) / 1e6d, LinearPowerDensityUnit.MegawattPerMillimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerCentimeter, quantity => new LinearPowerDensity((quantity.Value/1e2) / 1e-3d, LinearPowerDensityUnit.MilliwattPerCentimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerFoot, quantity => new LinearPowerDensity((quantity.Value/3.280839895) / 1e-3d, LinearPowerDensityUnit.MilliwattPerFoot)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerInch, quantity => new LinearPowerDensity((quantity.Value/39.37007874) / 1e-3d, LinearPowerDensityUnit.MilliwattPerInch)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMeter, quantity => new LinearPowerDensity((quantity.Value) / 1e-3d, LinearPowerDensityUnit.MilliwattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMillimeter, quantity => new LinearPowerDensity((quantity.Value/1e3) / 1e-3d, LinearPowerDensityUnit.MilliwattPerMillimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerCentimeter, quantity => new LinearPowerDensity(quantity.Value/1e2, LinearPowerDensityUnit.WattPerCentimeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerFoot, quantity => new LinearPowerDensity(quantity.Value/3.280839895, LinearPowerDensityUnit.WattPerFoot)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerInch, quantity => new LinearPowerDensity(quantity.Value/39.37007874, LinearPowerDensityUnit.WattPerInch)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerMillimeter, quantity => new LinearPowerDensity(quantity.Value/1e3, LinearPowerDensityUnit.WattPerMillimeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity); // Register in unit converter: LinearPowerDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*1e2) * 1e9d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*3.280839895) * 1e9d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*39.37007874) * 1e9d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value) * 1e9d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*1e3) * 1e9d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*1e2) * 1e3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*3.280839895) * 1e3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*39.37007874) * 1e3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value) * 1e3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*1e3) * 1e3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*1e2) * 1e6d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*3.280839895) * 1e6d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*39.37007874) * 1e6d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value) * 1e6d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*1e3) * 1e6d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*1e2) * 1e-3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*3.280839895) * 1e-3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*39.37007874) * 1e-3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value) * 1e-3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity((quantity.Value*1e3) * 1e-3d, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity(quantity.Value*1e2, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity(quantity.Value*3.280839895, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity(quantity.Value*39.37007874, LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => new LinearPowerDensity(quantity.Value*1e3, LinearPowerDensityUnit.WattPerMeter)); } /// @@ -1027,11 +1034,42 @@ double IQuantity.As(Enum unit) /// /// Converts this LinearPowerDensity to another LinearPowerDensity with the unit representation . /// + /// The unit to convert to. /// A LinearPowerDensity with the specified unit. public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit) { - var convertedValue = GetValueAs(unit); - return new LinearPowerDensity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this LinearPowerDensity to another LinearPowerDensity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A LinearPowerDensity with the specified unit. + public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(LinearPowerDensity), Unit, typeof(LinearPowerDensity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (LinearPowerDensity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1040,7 +1078,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is LinearPowerDensityUnit unitAsLinearPowerDensityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearPowerDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLinearPowerDensityUnit); + return ToUnit(unitAsLinearPowerDensityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is LinearPowerDensityUnit unitAsLinearPowerDensityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearPowerDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsLinearPowerDensityUnit, unitConverter); } /// @@ -1065,95 +1112,15 @@ public LinearPowerDensity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(LinearPowerDensityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case LinearPowerDensityUnit.GigawattPerCentimeter: return (_value*1e2) * 1e9d; - case LinearPowerDensityUnit.GigawattPerFoot: return (_value*3.280839895) * 1e9d; - case LinearPowerDensityUnit.GigawattPerInch: return (_value*39.37007874) * 1e9d; - case LinearPowerDensityUnit.GigawattPerMeter: return (_value) * 1e9d; - case LinearPowerDensityUnit.GigawattPerMillimeter: return (_value*1e3) * 1e9d; - case LinearPowerDensityUnit.KilowattPerCentimeter: return (_value*1e2) * 1e3d; - case LinearPowerDensityUnit.KilowattPerFoot: return (_value*3.280839895) * 1e3d; - case LinearPowerDensityUnit.KilowattPerInch: return (_value*39.37007874) * 1e3d; - case LinearPowerDensityUnit.KilowattPerMeter: return (_value) * 1e3d; - case LinearPowerDensityUnit.KilowattPerMillimeter: return (_value*1e3) * 1e3d; - case LinearPowerDensityUnit.MegawattPerCentimeter: return (_value*1e2) * 1e6d; - case LinearPowerDensityUnit.MegawattPerFoot: return (_value*3.280839895) * 1e6d; - case LinearPowerDensityUnit.MegawattPerInch: return (_value*39.37007874) * 1e6d; - case LinearPowerDensityUnit.MegawattPerMeter: return (_value) * 1e6d; - case LinearPowerDensityUnit.MegawattPerMillimeter: return (_value*1e3) * 1e6d; - case LinearPowerDensityUnit.MilliwattPerCentimeter: return (_value*1e2) * 1e-3d; - case LinearPowerDensityUnit.MilliwattPerFoot: return (_value*3.280839895) * 1e-3d; - case LinearPowerDensityUnit.MilliwattPerInch: return (_value*39.37007874) * 1e-3d; - case LinearPowerDensityUnit.MilliwattPerMeter: return (_value) * 1e-3d; - case LinearPowerDensityUnit.MilliwattPerMillimeter: return (_value*1e3) * 1e-3d; - case LinearPowerDensityUnit.WattPerCentimeter: return _value*1e2; - case LinearPowerDensityUnit.WattPerFoot: return _value*3.280839895; - case LinearPowerDensityUnit.WattPerInch: return _value*39.37007874; - case LinearPowerDensityUnit.WattPerMeter: return _value; - case LinearPowerDensityUnit.WattPerMillimeter: return _value*1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(LinearPowerDensityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal LinearPowerDensity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new LinearPowerDensity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(LinearPowerDensityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case LinearPowerDensityUnit.GigawattPerCentimeter: return (baseUnitValue/1e2) / 1e9d; - case LinearPowerDensityUnit.GigawattPerFoot: return (baseUnitValue/3.280839895) / 1e9d; - case LinearPowerDensityUnit.GigawattPerInch: return (baseUnitValue/39.37007874) / 1e9d; - case LinearPowerDensityUnit.GigawattPerMeter: return (baseUnitValue) / 1e9d; - case LinearPowerDensityUnit.GigawattPerMillimeter: return (baseUnitValue/1e3) / 1e9d; - case LinearPowerDensityUnit.KilowattPerCentimeter: return (baseUnitValue/1e2) / 1e3d; - case LinearPowerDensityUnit.KilowattPerFoot: return (baseUnitValue/3.280839895) / 1e3d; - case LinearPowerDensityUnit.KilowattPerInch: return (baseUnitValue/39.37007874) / 1e3d; - case LinearPowerDensityUnit.KilowattPerMeter: return (baseUnitValue) / 1e3d; - case LinearPowerDensityUnit.KilowattPerMillimeter: return (baseUnitValue/1e3) / 1e3d; - case LinearPowerDensityUnit.MegawattPerCentimeter: return (baseUnitValue/1e2) / 1e6d; - case LinearPowerDensityUnit.MegawattPerFoot: return (baseUnitValue/3.280839895) / 1e6d; - case LinearPowerDensityUnit.MegawattPerInch: return (baseUnitValue/39.37007874) / 1e6d; - case LinearPowerDensityUnit.MegawattPerMeter: return (baseUnitValue) / 1e6d; - case LinearPowerDensityUnit.MegawattPerMillimeter: return (baseUnitValue/1e3) / 1e6d; - case LinearPowerDensityUnit.MilliwattPerCentimeter: return (baseUnitValue/1e2) / 1e-3d; - case LinearPowerDensityUnit.MilliwattPerFoot: return (baseUnitValue/3.280839895) / 1e-3d; - case LinearPowerDensityUnit.MilliwattPerInch: return (baseUnitValue/39.37007874) / 1e-3d; - case LinearPowerDensityUnit.MilliwattPerMeter: return (baseUnitValue) / 1e-3d; - case LinearPowerDensityUnit.MilliwattPerMillimeter: return (baseUnitValue/1e3) / 1e-3d; - case LinearPowerDensityUnit.WattPerCentimeter: return baseUnitValue/1e2; - case LinearPowerDensityUnit.WattPerFoot: return baseUnitValue/3.280839895; - case LinearPowerDensityUnit.WattPerInch: return baseUnitValue/39.37007874; - case LinearPowerDensityUnit.WattPerMeter: return baseUnitValue; - case LinearPowerDensityUnit.WattPerMillimeter: return baseUnitValue/1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs index 4ea6686f54..a35ea5b25b 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs @@ -81,6 +81,8 @@ static Luminosity() new UnitInfo(LuminosityUnit.Watt, "Watts", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Luminosity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -119,6 +121,11 @@ public Luminosity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -276,37 +283,37 @@ public Luminosity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> LuminosityUnit - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Decawatt, quantity => quantity.ToUnit(LuminosityUnit.Decawatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Deciwatt, quantity => quantity.ToUnit(LuminosityUnit.Deciwatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Femtowatt, quantity => quantity.ToUnit(LuminosityUnit.Femtowatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Gigawatt, quantity => quantity.ToUnit(LuminosityUnit.Gigawatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Kilowatt, quantity => quantity.ToUnit(LuminosityUnit.Kilowatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Megawatt, quantity => quantity.ToUnit(LuminosityUnit.Megawatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Microwatt, quantity => quantity.ToUnit(LuminosityUnit.Microwatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Milliwatt, quantity => quantity.ToUnit(LuminosityUnit.Milliwatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Nanowatt, quantity => quantity.ToUnit(LuminosityUnit.Nanowatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Petawatt, quantity => quantity.ToUnit(LuminosityUnit.Petawatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Picowatt, quantity => quantity.ToUnit(LuminosityUnit.Picowatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.SolarLuminosity, quantity => quantity.ToUnit(LuminosityUnit.SolarLuminosity)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Terawatt, quantity => quantity.ToUnit(LuminosityUnit.Terawatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Decawatt, quantity => new Luminosity((quantity.Value) / 1e1d, LuminosityUnit.Decawatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Deciwatt, quantity => new Luminosity((quantity.Value) / 1e-1d, LuminosityUnit.Deciwatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Femtowatt, quantity => new Luminosity((quantity.Value) / 1e-15d, LuminosityUnit.Femtowatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Gigawatt, quantity => new Luminosity((quantity.Value) / 1e9d, LuminosityUnit.Gigawatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Kilowatt, quantity => new Luminosity((quantity.Value) / 1e3d, LuminosityUnit.Kilowatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Megawatt, quantity => new Luminosity((quantity.Value) / 1e6d, LuminosityUnit.Megawatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Microwatt, quantity => new Luminosity((quantity.Value) / 1e-6d, LuminosityUnit.Microwatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Milliwatt, quantity => new Luminosity((quantity.Value) / 1e-3d, LuminosityUnit.Milliwatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Nanowatt, quantity => new Luminosity((quantity.Value) / 1e-9d, LuminosityUnit.Nanowatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Petawatt, quantity => new Luminosity((quantity.Value) / 1e15d, LuminosityUnit.Petawatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Picowatt, quantity => new Luminosity((quantity.Value) / 1e-12d, LuminosityUnit.Picowatt)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.SolarLuminosity, quantity => new Luminosity(quantity.Value / 3.846e26, LuminosityUnit.SolarLuminosity)); + unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Terawatt, quantity => new Luminosity((quantity.Value) / 1e12d, LuminosityUnit.Terawatt)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Watt, quantity => quantity); // Register in unit converter: LuminosityUnit -> BaseUnit - unitConverter.SetConversionFunction(LuminosityUnit.Decawatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Deciwatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Femtowatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Gigawatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Kilowatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Megawatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Microwatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Milliwatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Nanowatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Petawatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Picowatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.SolarLuminosity, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(LuminosityUnit.Terawatt, LuminosityUnit.Watt, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(LuminosityUnit.Decawatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e1d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Deciwatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e-1d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Femtowatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e-15d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Gigawatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e9d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Kilowatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e3d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Megawatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e6d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Microwatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e-6d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Milliwatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e-3d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Nanowatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e-9d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Petawatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e15d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Picowatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e-12d, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.SolarLuminosity, LuminosityUnit.Watt, quantity => new Luminosity(quantity.Value * 3.846e26, LuminosityUnit.Watt)); + unitConverter.SetConversionFunction(LuminosityUnit.Terawatt, LuminosityUnit.Watt, quantity => new Luminosity((quantity.Value) * 1e12d, LuminosityUnit.Watt)); } /// @@ -840,11 +847,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Luminosity to another Luminosity with the unit representation . /// + /// The unit to convert to. /// A Luminosity with the specified unit. public Luminosity ToUnit(LuminosityUnit unit) { - var convertedValue = GetValueAs(unit); - return new Luminosity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Luminosity to another Luminosity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Luminosity with the specified unit. + public Luminosity ToUnit(LuminosityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Luminosity), Unit, typeof(Luminosity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Luminosity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -853,7 +891,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is LuminosityUnit unitAsLuminosityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminosityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLuminosityUnit); + return ToUnit(unitAsLuminosityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is LuminosityUnit unitAsLuminosityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminosityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsLuminosityUnit, unitConverter); } /// @@ -878,73 +925,15 @@ public Luminosity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(LuminosityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case LuminosityUnit.Decawatt: return (_value) * 1e1d; - case LuminosityUnit.Deciwatt: return (_value) * 1e-1d; - case LuminosityUnit.Femtowatt: return (_value) * 1e-15d; - case LuminosityUnit.Gigawatt: return (_value) * 1e9d; - case LuminosityUnit.Kilowatt: return (_value) * 1e3d; - case LuminosityUnit.Megawatt: return (_value) * 1e6d; - case LuminosityUnit.Microwatt: return (_value) * 1e-6d; - case LuminosityUnit.Milliwatt: return (_value) * 1e-3d; - case LuminosityUnit.Nanowatt: return (_value) * 1e-9d; - case LuminosityUnit.Petawatt: return (_value) * 1e15d; - case LuminosityUnit.Picowatt: return (_value) * 1e-12d; - case LuminosityUnit.SolarLuminosity: return _value * 3.846e26; - case LuminosityUnit.Terawatt: return (_value) * 1e12d; - case LuminosityUnit.Watt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(LuminosityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Luminosity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Luminosity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(LuminosityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case LuminosityUnit.Decawatt: return (baseUnitValue) / 1e1d; - case LuminosityUnit.Deciwatt: return (baseUnitValue) / 1e-1d; - case LuminosityUnit.Femtowatt: return (baseUnitValue) / 1e-15d; - case LuminosityUnit.Gigawatt: return (baseUnitValue) / 1e9d; - case LuminosityUnit.Kilowatt: return (baseUnitValue) / 1e3d; - case LuminosityUnit.Megawatt: return (baseUnitValue) / 1e6d; - case LuminosityUnit.Microwatt: return (baseUnitValue) / 1e-6d; - case LuminosityUnit.Milliwatt: return (baseUnitValue) / 1e-3d; - case LuminosityUnit.Nanowatt: return (baseUnitValue) / 1e-9d; - case LuminosityUnit.Petawatt: return (baseUnitValue) / 1e15d; - case LuminosityUnit.Picowatt: return (baseUnitValue) / 1e-12d; - case LuminosityUnit.SolarLuminosity: return baseUnitValue / 3.846e26; - case LuminosityUnit.Terawatt: return (baseUnitValue) / 1e12d; - case LuminosityUnit.Watt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs index e8e43e5e40..b2e462ad23 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs @@ -68,6 +68,8 @@ static LuminousFlux() new UnitInfo(LuminousFluxUnit.Lumen, "Lumens", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.LuminousFlux); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public LuminousFlux(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this LuminousFlux to another LuminousFlux with the unit representation . /// + /// The unit to convert to. /// A LuminousFlux with the specified unit. public LuminousFlux ToUnit(LuminousFluxUnit unit) { - var convertedValue = GetValueAs(unit); - return new LuminousFlux(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this LuminousFlux to another LuminousFlux using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A LuminousFlux with the specified unit. + public LuminousFlux ToUnit(LuminousFluxUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(LuminousFlux), Unit, typeof(LuminousFlux), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (LuminousFlux)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is LuminousFluxUnit unitAsLuminousFluxUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousFluxUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLuminousFluxUnit); + return ToUnit(unitAsLuminousFluxUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is LuminousFluxUnit unitAsLuminousFluxUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousFluxUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsLuminousFluxUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public LuminousFlux ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(LuminousFluxUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case LuminousFluxUnit.Lumen: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(LuminousFluxUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal LuminousFlux ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new LuminousFlux(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(LuminousFluxUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case LuminousFluxUnit.Lumen: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs index 5ed7ee775a..b4e165c352 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs @@ -68,6 +68,8 @@ static LuminousIntensity() new UnitInfo(LuminousIntensityUnit.Candela, "Candela", new BaseUnits(luminousIntensity: LuminousIntensityUnit.Candela)), }, BaseUnit, Zero, BaseDimensions, QuantityType.LuminousIntensity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public LuminousIntensity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this LuminousIntensity to another LuminousIntensity with the unit representation . /// + /// The unit to convert to. /// A LuminousIntensity with the specified unit. public LuminousIntensity ToUnit(LuminousIntensityUnit unit) { - var convertedValue = GetValueAs(unit); - return new LuminousIntensity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this LuminousIntensity to another LuminousIntensity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A LuminousIntensity with the specified unit. + public LuminousIntensity ToUnit(LuminousIntensityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(LuminousIntensity), Unit, typeof(LuminousIntensity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (LuminousIntensity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is LuminousIntensityUnit unitAsLuminousIntensityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousIntensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLuminousIntensityUnit); + return ToUnit(unitAsLuminousIntensityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is LuminousIntensityUnit unitAsLuminousIntensityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousIntensityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsLuminousIntensityUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public LuminousIntensity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(LuminousIntensityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case LuminousIntensityUnit.Candela: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(LuminousIntensityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal LuminousIntensity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new LuminousIntensity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(LuminousIntensityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case LuminousIntensityUnit.Candela: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs index d488098d69..9248258677 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs @@ -73,6 +73,8 @@ static MagneticField() new UnitInfo(MagneticFieldUnit.Tesla, "Teslas", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.MagneticField); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -111,6 +113,11 @@ public MagneticField(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -228,21 +235,21 @@ public MagneticField(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MagneticFieldUnit - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Gauss, quantity => quantity.ToUnit(MagneticFieldUnit.Gauss)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Microtesla, quantity => quantity.ToUnit(MagneticFieldUnit.Microtesla)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Milligauss, quantity => quantity.ToUnit(MagneticFieldUnit.Milligauss)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Millitesla, quantity => quantity.ToUnit(MagneticFieldUnit.Millitesla)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Nanotesla, quantity => quantity.ToUnit(MagneticFieldUnit.Nanotesla)); + unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Gauss, quantity => new MagneticField(quantity.Value*1e4, MagneticFieldUnit.Gauss)); + unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Microtesla, quantity => new MagneticField((quantity.Value) / 1e-6d, MagneticFieldUnit.Microtesla)); + unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Milligauss, quantity => new MagneticField((quantity.Value*1e4) / 1e-3d, MagneticFieldUnit.Milligauss)); + unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Millitesla, quantity => new MagneticField((quantity.Value) / 1e-3d, MagneticFieldUnit.Millitesla)); + unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Nanotesla, quantity => new MagneticField((quantity.Value) / 1e-9d, MagneticFieldUnit.Nanotesla)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Tesla, quantity => quantity); // Register in unit converter: MagneticFieldUnit -> BaseUnit - unitConverter.SetConversionFunction(MagneticFieldUnit.Gauss, MagneticFieldUnit.Tesla, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MagneticFieldUnit.Microtesla, MagneticFieldUnit.Tesla, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MagneticFieldUnit.Milligauss, MagneticFieldUnit.Tesla, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MagneticFieldUnit.Millitesla, MagneticFieldUnit.Tesla, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MagneticFieldUnit.Nanotesla, MagneticFieldUnit.Tesla, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MagneticFieldUnit.Gauss, MagneticFieldUnit.Tesla, quantity => new MagneticField(quantity.Value/1e4, MagneticFieldUnit.Tesla)); + unitConverter.SetConversionFunction(MagneticFieldUnit.Microtesla, MagneticFieldUnit.Tesla, quantity => new MagneticField((quantity.Value) * 1e-6d, MagneticFieldUnit.Tesla)); + unitConverter.SetConversionFunction(MagneticFieldUnit.Milligauss, MagneticFieldUnit.Tesla, quantity => new MagneticField((quantity.Value/1e4) * 1e-3d, MagneticFieldUnit.Tesla)); + unitConverter.SetConversionFunction(MagneticFieldUnit.Millitesla, MagneticFieldUnit.Tesla, quantity => new MagneticField((quantity.Value) * 1e-3d, MagneticFieldUnit.Tesla)); + unitConverter.SetConversionFunction(MagneticFieldUnit.Nanotesla, MagneticFieldUnit.Tesla, quantity => new MagneticField((quantity.Value) * 1e-9d, MagneticFieldUnit.Tesla)); } /// @@ -704,11 +711,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MagneticField to another MagneticField with the unit representation . /// + /// The unit to convert to. /// A MagneticField with the specified unit. public MagneticField ToUnit(MagneticFieldUnit unit) { - var convertedValue = GetValueAs(unit); - return new MagneticField(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MagneticField to another MagneticField using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MagneticField with the specified unit. + public MagneticField ToUnit(MagneticFieldUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MagneticField), Unit, typeof(MagneticField), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MagneticField)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -717,7 +755,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MagneticFieldUnit unitAsMagneticFieldUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFieldUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMagneticFieldUnit); + return ToUnit(unitAsMagneticFieldUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MagneticFieldUnit unitAsMagneticFieldUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFieldUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMagneticFieldUnit, unitConverter); } /// @@ -742,57 +789,15 @@ public MagneticField ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MagneticFieldUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MagneticFieldUnit.Gauss: return _value/1e4; - case MagneticFieldUnit.Microtesla: return (_value) * 1e-6d; - case MagneticFieldUnit.Milligauss: return (_value/1e4) * 1e-3d; - case MagneticFieldUnit.Millitesla: return (_value) * 1e-3d; - case MagneticFieldUnit.Nanotesla: return (_value) * 1e-9d; - case MagneticFieldUnit.Tesla: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MagneticFieldUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MagneticField ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MagneticField(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MagneticFieldUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MagneticFieldUnit.Gauss: return baseUnitValue*1e4; - case MagneticFieldUnit.Microtesla: return (baseUnitValue) / 1e-6d; - case MagneticFieldUnit.Milligauss: return (baseUnitValue*1e4) / 1e-3d; - case MagneticFieldUnit.Millitesla: return (baseUnitValue) / 1e-3d; - case MagneticFieldUnit.Nanotesla: return (baseUnitValue) / 1e-9d; - case MagneticFieldUnit.Tesla: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs index b614b47881..e13e4ea0e9 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs @@ -68,6 +68,8 @@ static MagneticFlux() new UnitInfo(MagneticFluxUnit.Weber, "Webers", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.MagneticFlux); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public MagneticFlux(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MagneticFlux to another MagneticFlux with the unit representation . /// + /// The unit to convert to. /// A MagneticFlux with the specified unit. public MagneticFlux ToUnit(MagneticFluxUnit unit) { - var convertedValue = GetValueAs(unit); - return new MagneticFlux(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MagneticFlux to another MagneticFlux using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MagneticFlux with the specified unit. + public MagneticFlux ToUnit(MagneticFluxUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MagneticFlux), Unit, typeof(MagneticFlux), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MagneticFlux)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MagneticFluxUnit unitAsMagneticFluxUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFluxUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMagneticFluxUnit); + return ToUnit(unitAsMagneticFluxUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MagneticFluxUnit unitAsMagneticFluxUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFluxUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMagneticFluxUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public MagneticFlux ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MagneticFluxUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MagneticFluxUnit.Weber: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MagneticFluxUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MagneticFlux ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MagneticFlux(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MagneticFluxUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MagneticFluxUnit.Weber: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs index bd074fe594..4c623332cc 100644 --- a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs @@ -68,6 +68,8 @@ static Magnetization() new UnitInfo(MagnetizationUnit.AmperePerMeter, "AmperesPerMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere)), }, BaseUnit, Zero, BaseDimensions, QuantityType.Magnetization); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public Magnetization(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Magnetization to another Magnetization with the unit representation . /// + /// The unit to convert to. /// A Magnetization with the specified unit. public Magnetization ToUnit(MagnetizationUnit unit) { - var convertedValue = GetValueAs(unit); - return new Magnetization(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Magnetization to another Magnetization using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Magnetization with the specified unit. + public Magnetization ToUnit(MagnetizationUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Magnetization), Unit, typeof(Magnetization), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Magnetization)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MagnetizationUnit unitAsMagnetizationUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagnetizationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMagnetizationUnit); + return ToUnit(unitAsMagnetizationUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MagnetizationUnit unitAsMagnetizationUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagnetizationUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMagnetizationUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public Magnetization ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MagnetizationUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MagnetizationUnit.AmperePerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MagnetizationUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Magnetization ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Magnetization(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MagnetizationUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MagnetizationUnit.AmperePerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs index 553c2292f3..a66b43a579 100644 --- a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs @@ -89,6 +89,8 @@ static Mass() new UnitInfo(MassUnit.Tonne, "Tonnes", new BaseUnits(mass: MassUnit.Tonne)), }, BaseUnit, Zero, BaseDimensions, QuantityType.Mass); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -127,6 +129,11 @@ public Mass(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -339,59 +346,59 @@ public Mass(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MassUnit - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Centigram, quantity => quantity.ToUnit(MassUnit.Centigram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Decagram, quantity => quantity.ToUnit(MassUnit.Decagram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Decigram, quantity => quantity.ToUnit(MassUnit.Decigram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.EarthMass, quantity => quantity.ToUnit(MassUnit.EarthMass)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Grain, quantity => quantity.ToUnit(MassUnit.Grain)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Gram, quantity => quantity.ToUnit(MassUnit.Gram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Hectogram, quantity => quantity.ToUnit(MassUnit.Hectogram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Kilopound, quantity => quantity.ToUnit(MassUnit.Kilopound)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Kilotonne, quantity => quantity.ToUnit(MassUnit.Kilotonne)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.LongHundredweight, quantity => quantity.ToUnit(MassUnit.LongHundredweight)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.LongTon, quantity => quantity.ToUnit(MassUnit.LongTon)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Megapound, quantity => quantity.ToUnit(MassUnit.Megapound)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Megatonne, quantity => quantity.ToUnit(MassUnit.Megatonne)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Microgram, quantity => quantity.ToUnit(MassUnit.Microgram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Milligram, quantity => quantity.ToUnit(MassUnit.Milligram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Nanogram, quantity => quantity.ToUnit(MassUnit.Nanogram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Ounce, quantity => quantity.ToUnit(MassUnit.Ounce)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Pound, quantity => quantity.ToUnit(MassUnit.Pound)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.ShortHundredweight, quantity => quantity.ToUnit(MassUnit.ShortHundredweight)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.ShortTon, quantity => quantity.ToUnit(MassUnit.ShortTon)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Slug, quantity => quantity.ToUnit(MassUnit.Slug)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.SolarMass, quantity => quantity.ToUnit(MassUnit.SolarMass)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Stone, quantity => quantity.ToUnit(MassUnit.Stone)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Tonne, quantity => quantity.ToUnit(MassUnit.Tonne)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Centigram, quantity => new Mass((quantity.Value*1e3) / 1e-2d, MassUnit.Centigram)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Decagram, quantity => new Mass((quantity.Value*1e3) / 1e1d, MassUnit.Decagram)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Decigram, quantity => new Mass((quantity.Value*1e3) / 1e-1d, MassUnit.Decigram)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.EarthMass, quantity => new Mass(quantity.Value / 5.9722E+24, MassUnit.EarthMass)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Grain, quantity => new Mass(quantity.Value*15432.358352941431, MassUnit.Grain)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Gram, quantity => new Mass(quantity.Value*1e3, MassUnit.Gram)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Hectogram, quantity => new Mass((quantity.Value*1e3) / 1e2d, MassUnit.Hectogram)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Kilopound, quantity => new Mass((quantity.Value/0.45359237) / 1e3d, MassUnit.Kilopound)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Kilotonne, quantity => new Mass((quantity.Value/1e3) / 1e3d, MassUnit.Kilotonne)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.LongHundredweight, quantity => new Mass(quantity.Value*0.01968413055222121, MassUnit.LongHundredweight)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.LongTon, quantity => new Mass(quantity.Value/1.0160469088e3, MassUnit.LongTon)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Megapound, quantity => new Mass((quantity.Value/0.45359237) / 1e6d, MassUnit.Megapound)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Megatonne, quantity => new Mass((quantity.Value/1e3) / 1e6d, MassUnit.Megatonne)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Microgram, quantity => new Mass((quantity.Value*1e3) / 1e-6d, MassUnit.Microgram)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Milligram, quantity => new Mass((quantity.Value*1e3) / 1e-3d, MassUnit.Milligram)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Nanogram, quantity => new Mass((quantity.Value*1e3) / 1e-9d, MassUnit.Nanogram)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Ounce, quantity => new Mass(quantity.Value*35.2739619, MassUnit.Ounce)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Pound, quantity => new Mass(quantity.Value/0.45359237, MassUnit.Pound)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.ShortHundredweight, quantity => new Mass(quantity.Value*0.022046226218487758, MassUnit.ShortHundredweight)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.ShortTon, quantity => new Mass(quantity.Value/9.0718474e2, MassUnit.ShortTon)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Slug, quantity => new Mass(quantity.Value*6.852176556196105e-2, MassUnit.Slug)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.SolarMass, quantity => new Mass(quantity.Value / 1.98947e30, MassUnit.SolarMass)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Stone, quantity => new Mass(quantity.Value*0.1574731728702698, MassUnit.Stone)); + unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Tonne, quantity => new Mass(quantity.Value/1e3, MassUnit.Tonne)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Kilogram, quantity => quantity); // Register in unit converter: MassUnit -> BaseUnit - unitConverter.SetConversionFunction(MassUnit.Centigram, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Decagram, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Decigram, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.EarthMass, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Grain, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Gram, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Hectogram, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Kilopound, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Kilotonne, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.LongHundredweight, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.LongTon, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Megapound, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Megatonne, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Microgram, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Milligram, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Nanogram, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Ounce, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Pound, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.ShortHundredweight, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.ShortTon, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Slug, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.SolarMass, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Stone, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassUnit.Tonne, MassUnit.Kilogram, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MassUnit.Centigram, MassUnit.Kilogram, quantity => new Mass((quantity.Value/1e3) * 1e-2d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Decagram, MassUnit.Kilogram, quantity => new Mass((quantity.Value/1e3) * 1e1d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Decigram, MassUnit.Kilogram, quantity => new Mass((quantity.Value/1e3) * 1e-1d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.EarthMass, MassUnit.Kilogram, quantity => new Mass(quantity.Value * 5.9722E+24, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Grain, MassUnit.Kilogram, quantity => new Mass(quantity.Value/15432.358352941431, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Gram, MassUnit.Kilogram, quantity => new Mass(quantity.Value/1e3, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Hectogram, MassUnit.Kilogram, quantity => new Mass((quantity.Value/1e3) * 1e2d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Kilopound, MassUnit.Kilogram, quantity => new Mass((quantity.Value*0.45359237) * 1e3d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Kilotonne, MassUnit.Kilogram, quantity => new Mass((quantity.Value*1e3) * 1e3d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.LongHundredweight, MassUnit.Kilogram, quantity => new Mass(quantity.Value/0.01968413055222121, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.LongTon, MassUnit.Kilogram, quantity => new Mass(quantity.Value*1.0160469088e3, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Megapound, MassUnit.Kilogram, quantity => new Mass((quantity.Value*0.45359237) * 1e6d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Megatonne, MassUnit.Kilogram, quantity => new Mass((quantity.Value*1e3) * 1e6d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Microgram, MassUnit.Kilogram, quantity => new Mass((quantity.Value/1e3) * 1e-6d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Milligram, MassUnit.Kilogram, quantity => new Mass((quantity.Value/1e3) * 1e-3d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Nanogram, MassUnit.Kilogram, quantity => new Mass((quantity.Value/1e3) * 1e-9d, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Ounce, MassUnit.Kilogram, quantity => new Mass(quantity.Value/35.2739619, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Pound, MassUnit.Kilogram, quantity => new Mass(quantity.Value*0.45359237, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.ShortHundredweight, MassUnit.Kilogram, quantity => new Mass(quantity.Value/0.022046226218487758, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.ShortTon, MassUnit.Kilogram, quantity => new Mass(quantity.Value*9.0718474e2, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Slug, MassUnit.Kilogram, quantity => new Mass(quantity.Value/6.852176556196105e-2, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.SolarMass, MassUnit.Kilogram, quantity => new Mass(quantity.Value * 1.98947e30, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Stone, MassUnit.Kilogram, quantity => new Mass(quantity.Value/0.1574731728702698, MassUnit.Kilogram)); + unitConverter.SetConversionFunction(MassUnit.Tonne, MassUnit.Kilogram, quantity => new Mass(quantity.Value*1e3, MassUnit.Kilogram)); } /// @@ -1024,11 +1031,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Mass to another Mass with the unit representation . /// + /// The unit to convert to. /// A Mass with the specified unit. public Mass ToUnit(MassUnit unit) { - var convertedValue = GetValueAs(unit); - return new Mass(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Mass to another Mass using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Mass with the specified unit. + public Mass ToUnit(MassUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Mass), Unit, typeof(Mass), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Mass)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1037,7 +1075,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MassUnit unitAsMassUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassUnit); + return ToUnit(unitAsMassUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MassUnit unitAsMassUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMassUnit, unitConverter); } /// @@ -1062,95 +1109,15 @@ public Mass ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MassUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MassUnit.Centigram: return (_value/1e3) * 1e-2d; - case MassUnit.Decagram: return (_value/1e3) * 1e1d; - case MassUnit.Decigram: return (_value/1e3) * 1e-1d; - case MassUnit.EarthMass: return _value * 5.9722E+24; - case MassUnit.Grain: return _value/15432.358352941431; - case MassUnit.Gram: return _value/1e3; - case MassUnit.Hectogram: return (_value/1e3) * 1e2d; - case MassUnit.Kilogram: return (_value/1e3) * 1e3d; - case MassUnit.Kilopound: return (_value*0.45359237) * 1e3d; - case MassUnit.Kilotonne: return (_value*1e3) * 1e3d; - case MassUnit.LongHundredweight: return _value/0.01968413055222121; - case MassUnit.LongTon: return _value*1.0160469088e3; - case MassUnit.Megapound: return (_value*0.45359237) * 1e6d; - case MassUnit.Megatonne: return (_value*1e3) * 1e6d; - case MassUnit.Microgram: return (_value/1e3) * 1e-6d; - case MassUnit.Milligram: return (_value/1e3) * 1e-3d; - case MassUnit.Nanogram: return (_value/1e3) * 1e-9d; - case MassUnit.Ounce: return _value/35.2739619; - case MassUnit.Pound: return _value*0.45359237; - case MassUnit.ShortHundredweight: return _value/0.022046226218487758; - case MassUnit.ShortTon: return _value*9.0718474e2; - case MassUnit.Slug: return _value/6.852176556196105e-2; - case MassUnit.SolarMass: return _value * 1.98947e30; - case MassUnit.Stone: return _value/0.1574731728702698; - case MassUnit.Tonne: return _value*1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MassUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Mass ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Mass(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MassUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MassUnit.Centigram: return (baseUnitValue*1e3) / 1e-2d; - case MassUnit.Decagram: return (baseUnitValue*1e3) / 1e1d; - case MassUnit.Decigram: return (baseUnitValue*1e3) / 1e-1d; - case MassUnit.EarthMass: return baseUnitValue / 5.9722E+24; - case MassUnit.Grain: return baseUnitValue*15432.358352941431; - case MassUnit.Gram: return baseUnitValue*1e3; - case MassUnit.Hectogram: return (baseUnitValue*1e3) / 1e2d; - case MassUnit.Kilogram: return (baseUnitValue*1e3) / 1e3d; - case MassUnit.Kilopound: return (baseUnitValue/0.45359237) / 1e3d; - case MassUnit.Kilotonne: return (baseUnitValue/1e3) / 1e3d; - case MassUnit.LongHundredweight: return baseUnitValue*0.01968413055222121; - case MassUnit.LongTon: return baseUnitValue/1.0160469088e3; - case MassUnit.Megapound: return (baseUnitValue/0.45359237) / 1e6d; - case MassUnit.Megatonne: return (baseUnitValue/1e3) / 1e6d; - case MassUnit.Microgram: return (baseUnitValue*1e3) / 1e-6d; - case MassUnit.Milligram: return (baseUnitValue*1e3) / 1e-3d; - case MassUnit.Nanogram: return (baseUnitValue*1e3) / 1e-9d; - case MassUnit.Ounce: return baseUnitValue*35.2739619; - case MassUnit.Pound: return baseUnitValue/0.45359237; - case MassUnit.ShortHundredweight: return baseUnitValue*0.022046226218487758; - case MassUnit.ShortTon: return baseUnitValue/9.0718474e2; - case MassUnit.Slug: return baseUnitValue*6.852176556196105e-2; - case MassUnit.SolarMass: return baseUnitValue / 1.98947e30; - case MassUnit.Stone: return baseUnitValue*0.1574731728702698; - case MassUnit.Tonne: return baseUnitValue/1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs index 119dc4f914..2ac346ac3d 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs @@ -116,6 +116,8 @@ static MassConcentration() new UnitInfo(MassConcentrationUnit.TonnePerCubicMillimeter, "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne)), }, BaseUnit, Zero, BaseDimensions, QuantityType.MassConcentration); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -154,6 +156,11 @@ public MassConcentration(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -486,107 +493,107 @@ public MassConcentration(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MassConcentrationUnit - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicCentimeter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerCubicCentimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMillimeter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerCubicMillimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicCentimeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicCentimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMillimeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMillimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicFoot, quantity => quantity.ToUnit(MassConcentrationUnit.KilopoundPerCubicFoot)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicInch, quantity => quantity.ToUnit(MassConcentrationUnit.KilopoundPerCubicInch)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerImperialGallon, quantity => quantity.ToUnit(MassConcentrationUnit.OuncePerImperialGallon)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerUSGallon, quantity => quantity.ToUnit(MassConcentrationUnit.OuncePerUSGallon)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicFoot, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerCubicFoot)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicInch, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerCubicInch)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerImperialGallon, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerImperialGallon)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerUSGallon, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerUSGallon)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.SlugPerCubicFoot, quantity => quantity.ToUnit(MassConcentrationUnit.SlugPerCubicFoot)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicCentimeter, quantity => quantity.ToUnit(MassConcentrationUnit.TonnePerCubicCentimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.TonnePerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMillimeter, quantity => quantity.ToUnit(MassConcentrationUnit.TonnePerCubicMillimeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerDeciliter, quantity => new MassConcentration((quantity.Value*1e-1) / 1e-2d, MassConcentrationUnit.CentigramPerDeciliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerLiter, quantity => new MassConcentration((quantity.Value) / 1e-2d, MassConcentrationUnit.CentigramPerLiter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMicroliter, quantity => new MassConcentration((quantity.Value*1e-6) / 1e-2d, MassConcentrationUnit.CentigramPerMicroliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMilliliter, quantity => new MassConcentration((quantity.Value*1e-3) / 1e-2d, MassConcentrationUnit.CentigramPerMilliliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerDeciliter, quantity => new MassConcentration((quantity.Value*1e-1) / 1e-1d, MassConcentrationUnit.DecigramPerDeciliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerLiter, quantity => new MassConcentration((quantity.Value) / 1e-1d, MassConcentrationUnit.DecigramPerLiter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMicroliter, quantity => new MassConcentration((quantity.Value*1e-6) / 1e-1d, MassConcentrationUnit.DecigramPerMicroliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMilliliter, quantity => new MassConcentration((quantity.Value*1e-3) / 1e-1d, MassConcentrationUnit.DecigramPerMilliliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicCentimeter, quantity => new MassConcentration(quantity.Value*1e-3, MassConcentrationUnit.GramPerCubicCentimeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMeter, quantity => new MassConcentration(quantity.Value*1e3, MassConcentrationUnit.GramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMillimeter, quantity => new MassConcentration(quantity.Value*1e-6, MassConcentrationUnit.GramPerCubicMillimeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerDeciliter, quantity => new MassConcentration(quantity.Value*1e-1, MassConcentrationUnit.GramPerDeciliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerLiter, quantity => new MassConcentration(quantity.Value, MassConcentrationUnit.GramPerLiter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMicroliter, quantity => new MassConcentration(quantity.Value*1e-6, MassConcentrationUnit.GramPerMicroliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMilliliter, quantity => new MassConcentration(quantity.Value*1e-3, MassConcentrationUnit.GramPerMilliliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicCentimeter, quantity => new MassConcentration((quantity.Value*1e-3) / 1e3d, MassConcentrationUnit.KilogramPerCubicCentimeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMillimeter, quantity => new MassConcentration((quantity.Value*1e-6) / 1e3d, MassConcentrationUnit.KilogramPerCubicMillimeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerLiter, quantity => new MassConcentration((quantity.Value) / 1e3d, MassConcentrationUnit.KilogramPerLiter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicFoot, quantity => new MassConcentration((quantity.Value*0.062427961) / 1e3d, MassConcentrationUnit.KilopoundPerCubicFoot)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicInch, quantity => new MassConcentration((quantity.Value*3.6127298147753e-5) / 1e3d, MassConcentrationUnit.KilopoundPerCubicInch)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerCubicMeter, quantity => new MassConcentration((quantity.Value*1e3) / 1e-6d, MassConcentrationUnit.MicrogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerDeciliter, quantity => new MassConcentration((quantity.Value*1e-1) / 1e-6d, MassConcentrationUnit.MicrogramPerDeciliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerLiter, quantity => new MassConcentration((quantity.Value) / 1e-6d, MassConcentrationUnit.MicrogramPerLiter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMicroliter, quantity => new MassConcentration((quantity.Value*1e-6) / 1e-6d, MassConcentrationUnit.MicrogramPerMicroliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMilliliter, quantity => new MassConcentration((quantity.Value*1e-3) / 1e-6d, MassConcentrationUnit.MicrogramPerMilliliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerCubicMeter, quantity => new MassConcentration((quantity.Value*1e3) / 1e-3d, MassConcentrationUnit.MilligramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerDeciliter, quantity => new MassConcentration((quantity.Value*1e-1) / 1e-3d, MassConcentrationUnit.MilligramPerDeciliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerLiter, quantity => new MassConcentration((quantity.Value) / 1e-3d, MassConcentrationUnit.MilligramPerLiter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMicroliter, quantity => new MassConcentration((quantity.Value*1e-6) / 1e-3d, MassConcentrationUnit.MilligramPerMicroliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMilliliter, quantity => new MassConcentration((quantity.Value*1e-3) / 1e-3d, MassConcentrationUnit.MilligramPerMilliliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerDeciliter, quantity => new MassConcentration((quantity.Value*1e-1) / 1e-9d, MassConcentrationUnit.NanogramPerDeciliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerLiter, quantity => new MassConcentration((quantity.Value) / 1e-9d, MassConcentrationUnit.NanogramPerLiter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMicroliter, quantity => new MassConcentration((quantity.Value*1e-6) / 1e-9d, MassConcentrationUnit.NanogramPerMicroliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMilliliter, quantity => new MassConcentration((quantity.Value*1e-3) / 1e-9d, MassConcentrationUnit.NanogramPerMilliliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerImperialGallon, quantity => new MassConcentration(quantity.Value*0.1603586720609, MassConcentrationUnit.OuncePerImperialGallon)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerUSGallon, quantity => new MassConcentration(quantity.Value*0.1335264711843, MassConcentrationUnit.OuncePerUSGallon)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerDeciliter, quantity => new MassConcentration((quantity.Value*1e-1) / 1e-12d, MassConcentrationUnit.PicogramPerDeciliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerLiter, quantity => new MassConcentration((quantity.Value) / 1e-12d, MassConcentrationUnit.PicogramPerLiter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMicroliter, quantity => new MassConcentration((quantity.Value*1e-6) / 1e-12d, MassConcentrationUnit.PicogramPerMicroliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMilliliter, quantity => new MassConcentration((quantity.Value*1e-3) / 1e-12d, MassConcentrationUnit.PicogramPerMilliliter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicFoot, quantity => new MassConcentration(quantity.Value*0.062427961, MassConcentrationUnit.PoundPerCubicFoot)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicInch, quantity => new MassConcentration(quantity.Value*3.6127298147753e-5, MassConcentrationUnit.PoundPerCubicInch)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerImperialGallon, quantity => new MassConcentration(quantity.Value/9.9776398e1, MassConcentrationUnit.PoundPerImperialGallon)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerUSGallon, quantity => new MassConcentration(quantity.Value/1.19826427e2, MassConcentrationUnit.PoundPerUSGallon)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.SlugPerCubicFoot, quantity => new MassConcentration(quantity.Value*0.00194032033, MassConcentrationUnit.SlugPerCubicFoot)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicCentimeter, quantity => new MassConcentration(quantity.Value*1e-9, MassConcentrationUnit.TonnePerCubicCentimeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMeter, quantity => new MassConcentration(quantity.Value*0.001, MassConcentrationUnit.TonnePerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMillimeter, quantity => new MassConcentration(quantity.Value*1e-12, MassConcentrationUnit.TonnePerCubicMillimeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity); // Register in unit converter: MassConcentrationUnit -> BaseUnit - unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilopoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilopoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.OuncePerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.OuncePerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.SlugPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.TonnePerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.TonnePerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassConcentrationUnit.TonnePerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-1) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-6) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-3) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-1) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-6) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-3) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/1e-3, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/1e3, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/1e-6, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/1e-1, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/1e-6, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/1e-3, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-3) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-6) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilopoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/0.062427961) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.KilopoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/3.6127298147753e-5) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e3) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-1) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-6) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-3) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e3) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-1) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-6) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-3) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-1) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-6) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-3) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.OuncePerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration( quantity.Value/0.1603586720609, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.OuncePerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration( quantity.Value/0.1335264711843, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-1) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-6) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration((quantity.Value/1e-3) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/0.062427961, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/3.6127298147753e-5, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value*9.9776398e1, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value*1.19826427e2, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.SlugPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value*515.378818, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.TonnePerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/1e-9, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.TonnePerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/0.001, MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction(MassConcentrationUnit.TonnePerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => new MassConcentration(quantity.Value/1e-12, MassConcentrationUnit.KilogramPerCubicMeter)); } /// @@ -1435,11 +1442,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MassConcentration to another MassConcentration with the unit representation . /// + /// The unit to convert to. /// A MassConcentration with the specified unit. public MassConcentration ToUnit(MassConcentrationUnit unit) { - var convertedValue = GetValueAs(unit); - return new MassConcentration(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MassConcentration to another MassConcentration using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MassConcentration with the specified unit. + public MassConcentration ToUnit(MassConcentrationUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MassConcentration), Unit, typeof(MassConcentration), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MassConcentration)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1448,7 +1486,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MassConcentrationUnit unitAsMassConcentrationUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassConcentrationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassConcentrationUnit); + return ToUnit(unitAsMassConcentrationUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MassConcentrationUnit unitAsMassConcentrationUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassConcentrationUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMassConcentrationUnit, unitConverter); } /// @@ -1473,143 +1520,15 @@ public MassConcentration ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MassConcentrationUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MassConcentrationUnit.CentigramPerDeciliter: return (_value/1e-1) * 1e-2d; - case MassConcentrationUnit.CentigramPerLiter: return (_value) * 1e-2d; - case MassConcentrationUnit.CentigramPerMicroliter: return (_value/1e-6) * 1e-2d; - case MassConcentrationUnit.CentigramPerMilliliter: return (_value/1e-3) * 1e-2d; - case MassConcentrationUnit.DecigramPerDeciliter: return (_value/1e-1) * 1e-1d; - case MassConcentrationUnit.DecigramPerLiter: return (_value) * 1e-1d; - case MassConcentrationUnit.DecigramPerMicroliter: return (_value/1e-6) * 1e-1d; - case MassConcentrationUnit.DecigramPerMilliliter: return (_value/1e-3) * 1e-1d; - case MassConcentrationUnit.GramPerCubicCentimeter: return _value/1e-3; - case MassConcentrationUnit.GramPerCubicMeter: return _value/1e3; - case MassConcentrationUnit.GramPerCubicMillimeter: return _value/1e-6; - case MassConcentrationUnit.GramPerDeciliter: return _value/1e-1; - case MassConcentrationUnit.GramPerLiter: return _value; - case MassConcentrationUnit.GramPerMicroliter: return _value/1e-6; - case MassConcentrationUnit.GramPerMilliliter: return _value/1e-3; - case MassConcentrationUnit.KilogramPerCubicCentimeter: return (_value/1e-3) * 1e3d; - case MassConcentrationUnit.KilogramPerCubicMeter: return (_value/1e3) * 1e3d; - case MassConcentrationUnit.KilogramPerCubicMillimeter: return (_value/1e-6) * 1e3d; - case MassConcentrationUnit.KilogramPerLiter: return (_value) * 1e3d; - case MassConcentrationUnit.KilopoundPerCubicFoot: return (_value/0.062427961) * 1e3d; - case MassConcentrationUnit.KilopoundPerCubicInch: return (_value/3.6127298147753e-5) * 1e3d; - case MassConcentrationUnit.MicrogramPerCubicMeter: return (_value/1e3) * 1e-6d; - case MassConcentrationUnit.MicrogramPerDeciliter: return (_value/1e-1) * 1e-6d; - case MassConcentrationUnit.MicrogramPerLiter: return (_value) * 1e-6d; - case MassConcentrationUnit.MicrogramPerMicroliter: return (_value/1e-6) * 1e-6d; - case MassConcentrationUnit.MicrogramPerMilliliter: return (_value/1e-3) * 1e-6d; - case MassConcentrationUnit.MilligramPerCubicMeter: return (_value/1e3) * 1e-3d; - case MassConcentrationUnit.MilligramPerDeciliter: return (_value/1e-1) * 1e-3d; - case MassConcentrationUnit.MilligramPerLiter: return (_value) * 1e-3d; - case MassConcentrationUnit.MilligramPerMicroliter: return (_value/1e-6) * 1e-3d; - case MassConcentrationUnit.MilligramPerMilliliter: return (_value/1e-3) * 1e-3d; - case MassConcentrationUnit.NanogramPerDeciliter: return (_value/1e-1) * 1e-9d; - case MassConcentrationUnit.NanogramPerLiter: return (_value) * 1e-9d; - case MassConcentrationUnit.NanogramPerMicroliter: return (_value/1e-6) * 1e-9d; - case MassConcentrationUnit.NanogramPerMilliliter: return (_value/1e-3) * 1e-9d; - case MassConcentrationUnit.OuncePerImperialGallon: return _value/0.1603586720609; - case MassConcentrationUnit.OuncePerUSGallon: return _value/0.1335264711843; - case MassConcentrationUnit.PicogramPerDeciliter: return (_value/1e-1) * 1e-12d; - case MassConcentrationUnit.PicogramPerLiter: return (_value) * 1e-12d; - case MassConcentrationUnit.PicogramPerMicroliter: return (_value/1e-6) * 1e-12d; - case MassConcentrationUnit.PicogramPerMilliliter: return (_value/1e-3) * 1e-12d; - case MassConcentrationUnit.PoundPerCubicFoot: return _value/0.062427961; - case MassConcentrationUnit.PoundPerCubicInch: return _value/3.6127298147753e-5; - case MassConcentrationUnit.PoundPerImperialGallon: return _value*9.9776398e1; - case MassConcentrationUnit.PoundPerUSGallon: return _value*1.19826427e2; - case MassConcentrationUnit.SlugPerCubicFoot: return _value*515.378818; - case MassConcentrationUnit.TonnePerCubicCentimeter: return _value/1e-9; - case MassConcentrationUnit.TonnePerCubicMeter: return _value/0.001; - case MassConcentrationUnit.TonnePerCubicMillimeter: return _value/1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MassConcentrationUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MassConcentration ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MassConcentration(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MassConcentrationUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MassConcentrationUnit.CentigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-2d; - case MassConcentrationUnit.CentigramPerLiter: return (baseUnitValue) / 1e-2d; - case MassConcentrationUnit.CentigramPerMicroliter: return (baseUnitValue*1e-6) / 1e-2d; - case MassConcentrationUnit.CentigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-2d; - case MassConcentrationUnit.DecigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-1d; - case MassConcentrationUnit.DecigramPerLiter: return (baseUnitValue) / 1e-1d; - case MassConcentrationUnit.DecigramPerMicroliter: return (baseUnitValue*1e-6) / 1e-1d; - case MassConcentrationUnit.DecigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-1d; - case MassConcentrationUnit.GramPerCubicCentimeter: return baseUnitValue*1e-3; - case MassConcentrationUnit.GramPerCubicMeter: return baseUnitValue*1e3; - case MassConcentrationUnit.GramPerCubicMillimeter: return baseUnitValue*1e-6; - case MassConcentrationUnit.GramPerDeciliter: return baseUnitValue*1e-1; - case MassConcentrationUnit.GramPerLiter: return baseUnitValue; - case MassConcentrationUnit.GramPerMicroliter: return baseUnitValue*1e-6; - case MassConcentrationUnit.GramPerMilliliter: return baseUnitValue*1e-3; - case MassConcentrationUnit.KilogramPerCubicCentimeter: return (baseUnitValue*1e-3) / 1e3d; - case MassConcentrationUnit.KilogramPerCubicMeter: return (baseUnitValue*1e3) / 1e3d; - case MassConcentrationUnit.KilogramPerCubicMillimeter: return (baseUnitValue*1e-6) / 1e3d; - case MassConcentrationUnit.KilogramPerLiter: return (baseUnitValue) / 1e3d; - case MassConcentrationUnit.KilopoundPerCubicFoot: return (baseUnitValue*0.062427961) / 1e3d; - case MassConcentrationUnit.KilopoundPerCubicInch: return (baseUnitValue*3.6127298147753e-5) / 1e3d; - case MassConcentrationUnit.MicrogramPerCubicMeter: return (baseUnitValue*1e3) / 1e-6d; - case MassConcentrationUnit.MicrogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-6d; - case MassConcentrationUnit.MicrogramPerLiter: return (baseUnitValue) / 1e-6d; - case MassConcentrationUnit.MicrogramPerMicroliter: return (baseUnitValue*1e-6) / 1e-6d; - case MassConcentrationUnit.MicrogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-6d; - case MassConcentrationUnit.MilligramPerCubicMeter: return (baseUnitValue*1e3) / 1e-3d; - case MassConcentrationUnit.MilligramPerDeciliter: return (baseUnitValue*1e-1) / 1e-3d; - case MassConcentrationUnit.MilligramPerLiter: return (baseUnitValue) / 1e-3d; - case MassConcentrationUnit.MilligramPerMicroliter: return (baseUnitValue*1e-6) / 1e-3d; - case MassConcentrationUnit.MilligramPerMilliliter: return (baseUnitValue*1e-3) / 1e-3d; - case MassConcentrationUnit.NanogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-9d; - case MassConcentrationUnit.NanogramPerLiter: return (baseUnitValue) / 1e-9d; - case MassConcentrationUnit.NanogramPerMicroliter: return (baseUnitValue*1e-6) / 1e-9d; - case MassConcentrationUnit.NanogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-9d; - case MassConcentrationUnit.OuncePerImperialGallon: return baseUnitValue*0.1603586720609; - case MassConcentrationUnit.OuncePerUSGallon: return baseUnitValue*0.1335264711843; - case MassConcentrationUnit.PicogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-12d; - case MassConcentrationUnit.PicogramPerLiter: return (baseUnitValue) / 1e-12d; - case MassConcentrationUnit.PicogramPerMicroliter: return (baseUnitValue*1e-6) / 1e-12d; - case MassConcentrationUnit.PicogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-12d; - case MassConcentrationUnit.PoundPerCubicFoot: return baseUnitValue*0.062427961; - case MassConcentrationUnit.PoundPerCubicInch: return baseUnitValue*3.6127298147753e-5; - case MassConcentrationUnit.PoundPerImperialGallon: return baseUnitValue/9.9776398e1; - case MassConcentrationUnit.PoundPerUSGallon: return baseUnitValue/1.19826427e2; - case MassConcentrationUnit.SlugPerCubicFoot: return baseUnitValue*0.00194032033; - case MassConcentrationUnit.TonnePerCubicCentimeter: return baseUnitValue*1e-9; - case MassConcentrationUnit.TonnePerCubicMeter: return baseUnitValue*0.001; - case MassConcentrationUnit.TonnePerCubicMillimeter: return baseUnitValue*1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs index 169fc5ac7d..539980472b 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs @@ -97,6 +97,8 @@ static MassFlow() new UnitInfo(MassFlowUnit.TonnePerHour, "TonnesPerHour", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.MassFlow); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -135,6 +137,11 @@ public MassFlow(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -387,75 +394,75 @@ public MassFlow(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MassFlowUnit - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerDay, quantity => quantity.ToUnit(MassFlowUnit.CentigramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.CentigramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerDay, quantity => quantity.ToUnit(MassFlowUnit.DecagramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.DecagramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerDay, quantity => quantity.ToUnit(MassFlowUnit.DecigramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.DecigramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerDay, quantity => quantity.ToUnit(MassFlowUnit.GramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerHour, quantity => quantity.ToUnit(MassFlowUnit.GramPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.HectogramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.HectogramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerHour, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerMinute, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerMinute)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegagramPerDay, quantity => quantity.ToUnit(MassFlowUnit.MegagramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerDay, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerHour, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerMinute, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerMinute)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerSecond, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.MicrogramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.MicrogramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerDay, quantity => quantity.ToUnit(MassFlowUnit.MilligramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.MilligramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.NanogramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.NanogramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerDay, quantity => quantity.ToUnit(MassFlowUnit.PoundPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerHour, quantity => quantity.ToUnit(MassFlowUnit.PoundPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerMinute, quantity => quantity.ToUnit(MassFlowUnit.PoundPerMinute)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerSecond, quantity => quantity.ToUnit(MassFlowUnit.PoundPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.ShortTonPerHour, quantity => quantity.ToUnit(MassFlowUnit.ShortTonPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerDay, quantity => quantity.ToUnit(MassFlowUnit.TonnePerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerHour, quantity => quantity.ToUnit(MassFlowUnit.TonnePerHour)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerDay, quantity => new MassFlow((quantity.Value*86400) / 1e-2d, MassFlowUnit.CentigramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerSecond, quantity => new MassFlow((quantity.Value) / 1e-2d, MassFlowUnit.CentigramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerDay, quantity => new MassFlow((quantity.Value*86400) / 1e1d, MassFlowUnit.DecagramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerSecond, quantity => new MassFlow((quantity.Value) / 1e1d, MassFlowUnit.DecagramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerDay, quantity => new MassFlow((quantity.Value*86400) / 1e-1d, MassFlowUnit.DecigramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerSecond, quantity => new MassFlow((quantity.Value) / 1e-1d, MassFlowUnit.DecigramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerDay, quantity => new MassFlow(quantity.Value*86400, MassFlowUnit.GramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerHour, quantity => new MassFlow(quantity.Value*3600, MassFlowUnit.GramPerHour)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerDay, quantity => new MassFlow((quantity.Value*86400) / 1e2d, MassFlowUnit.HectogramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerSecond, quantity => new MassFlow((quantity.Value) / 1e2d, MassFlowUnit.HectogramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerDay, quantity => new MassFlow((quantity.Value*86400) / 1e3d, MassFlowUnit.KilogramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerHour, quantity => new MassFlow(quantity.Value*3.6, MassFlowUnit.KilogramPerHour)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerMinute, quantity => new MassFlow(quantity.Value*0.06, MassFlowUnit.KilogramPerMinute)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerSecond, quantity => new MassFlow((quantity.Value) / 1e3d, MassFlowUnit.KilogramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegagramPerDay, quantity => new MassFlow((quantity.Value*86400) / 1e6d, MassFlowUnit.MegagramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerDay, quantity => new MassFlow((quantity.Value*190.47936) / 1e6d, MassFlowUnit.MegapoundPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerHour, quantity => new MassFlow((quantity.Value*7.93664) / 1e6d, MassFlowUnit.MegapoundPerHour)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerMinute, quantity => new MassFlow((quantity.Value*0.132277) / 1e6d, MassFlowUnit.MegapoundPerMinute)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerSecond, quantity => new MassFlow((quantity.Value / 453.59237) / 1e6d, MassFlowUnit.MegapoundPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerDay, quantity => new MassFlow((quantity.Value*86400) / 1e-6d, MassFlowUnit.MicrogramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerSecond, quantity => new MassFlow((quantity.Value) / 1e-6d, MassFlowUnit.MicrogramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerDay, quantity => new MassFlow((quantity.Value*86400) / 1e-3d, MassFlowUnit.MilligramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerSecond, quantity => new MassFlow((quantity.Value) / 1e-3d, MassFlowUnit.MilligramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerDay, quantity => new MassFlow((quantity.Value*86400) / 1e-9d, MassFlowUnit.NanogramPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerSecond, quantity => new MassFlow((quantity.Value) / 1e-9d, MassFlowUnit.NanogramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerDay, quantity => new MassFlow(quantity.Value*190.47936, MassFlowUnit.PoundPerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerHour, quantity => new MassFlow(quantity.Value*7.93664, MassFlowUnit.PoundPerHour)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerMinute, quantity => new MassFlow(quantity.Value*0.132277, MassFlowUnit.PoundPerMinute)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerSecond, quantity => new MassFlow(quantity.Value / 453.59237, MassFlowUnit.PoundPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.ShortTonPerHour, quantity => new MassFlow(quantity.Value/251.9957611, MassFlowUnit.ShortTonPerHour)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerDay, quantity => new MassFlow(quantity.Value*0.0864000, MassFlowUnit.TonnePerDay)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerHour, quantity => new MassFlow(quantity.Value*3.6/1000, MassFlowUnit.TonnePerHour)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity); // Register in unit converter: MassFlowUnit -> BaseUnit - unitConverter.SetConversionFunction(MassFlowUnit.CentigramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.CentigramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.DecagramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.DecagramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.DecigramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.DecigramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.HectogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.HectogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerMinute, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.MegagramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerMinute, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.MicrogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.MicrogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.MilligramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.MilligramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.NanogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.NanogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.PoundPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.PoundPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.PoundPerMinute, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.PoundPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.ShortTonPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.TonnePerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFlowUnit.TonnePerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MassFlowUnit.CentigramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/86400) * 1e-2d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.CentigramPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value) * 1e-2d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.DecagramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/86400) * 1e1d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.DecagramPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value) * 1e1d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.DecigramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/86400) * 1e-1d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.DecigramPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value) * 1e-1d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value/86400, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.GramPerHour, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value/3600, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.HectogramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/86400) * 1e2d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.HectogramPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value) * 1e2d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/86400) * 1e3d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerHour, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value/3.6, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerMinute, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value/0.06, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value) * 1e3d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.MegagramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/86400) * 1e6d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/190.47936) * 1e6d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerHour, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/7.93664) * 1e6d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerMinute, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/0.132277) * 1e6d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value * 453.59237) * 1e6d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.MicrogramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/86400) * 1e-6d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.MicrogramPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value) * 1e-6d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.MilligramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/86400) * 1e-3d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.MilligramPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value) * 1e-3d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.NanogramPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value/86400) * 1e-9d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.NanogramPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow((quantity.Value) * 1e-9d, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.PoundPerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value/190.47936, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.PoundPerHour, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value/7.93664, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.PoundPerMinute, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value/0.132277, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.PoundPerSecond, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value * 453.59237, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.ShortTonPerHour, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value*251.9957611, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.TonnePerDay, MassFlowUnit.GramPerSecond, quantity => new MassFlow(quantity.Value/0.0864000, MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction(MassFlowUnit.TonnePerHour, MassFlowUnit.GramPerSecond, quantity => new MassFlow(1000*quantity.Value/3.6, MassFlowUnit.GramPerSecond)); } /// @@ -1160,11 +1167,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MassFlow to another MassFlow with the unit representation . /// + /// The unit to convert to. /// A MassFlow with the specified unit. public MassFlow ToUnit(MassFlowUnit unit) { - var convertedValue = GetValueAs(unit); - return new MassFlow(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MassFlow to another MassFlow using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MassFlow with the specified unit. + public MassFlow ToUnit(MassFlowUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MassFlow), Unit, typeof(MassFlow), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MassFlow)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1173,7 +1211,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MassFlowUnit unitAsMassFlowUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFlowUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassFlowUnit); + return ToUnit(unitAsMassFlowUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MassFlowUnit unitAsMassFlowUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFlowUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMassFlowUnit, unitConverter); } /// @@ -1198,111 +1245,15 @@ public MassFlow ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MassFlowUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MassFlowUnit.CentigramPerDay: return (_value/86400) * 1e-2d; - case MassFlowUnit.CentigramPerSecond: return (_value) * 1e-2d; - case MassFlowUnit.DecagramPerDay: return (_value/86400) * 1e1d; - case MassFlowUnit.DecagramPerSecond: return (_value) * 1e1d; - case MassFlowUnit.DecigramPerDay: return (_value/86400) * 1e-1d; - case MassFlowUnit.DecigramPerSecond: return (_value) * 1e-1d; - case MassFlowUnit.GramPerDay: return _value/86400; - case MassFlowUnit.GramPerHour: return _value/3600; - case MassFlowUnit.GramPerSecond: return _value; - case MassFlowUnit.HectogramPerDay: return (_value/86400) * 1e2d; - case MassFlowUnit.HectogramPerSecond: return (_value) * 1e2d; - case MassFlowUnit.KilogramPerDay: return (_value/86400) * 1e3d; - case MassFlowUnit.KilogramPerHour: return _value/3.6; - case MassFlowUnit.KilogramPerMinute: return _value/0.06; - case MassFlowUnit.KilogramPerSecond: return (_value) * 1e3d; - case MassFlowUnit.MegagramPerDay: return (_value/86400) * 1e6d; - case MassFlowUnit.MegapoundPerDay: return (_value/190.47936) * 1e6d; - case MassFlowUnit.MegapoundPerHour: return (_value/7.93664) * 1e6d; - case MassFlowUnit.MegapoundPerMinute: return (_value/0.132277) * 1e6d; - case MassFlowUnit.MegapoundPerSecond: return (_value * 453.59237) * 1e6d; - case MassFlowUnit.MicrogramPerDay: return (_value/86400) * 1e-6d; - case MassFlowUnit.MicrogramPerSecond: return (_value) * 1e-6d; - case MassFlowUnit.MilligramPerDay: return (_value/86400) * 1e-3d; - case MassFlowUnit.MilligramPerSecond: return (_value) * 1e-3d; - case MassFlowUnit.NanogramPerDay: return (_value/86400) * 1e-9d; - case MassFlowUnit.NanogramPerSecond: return (_value) * 1e-9d; - case MassFlowUnit.PoundPerDay: return _value/190.47936; - case MassFlowUnit.PoundPerHour: return _value/7.93664; - case MassFlowUnit.PoundPerMinute: return _value/0.132277; - case MassFlowUnit.PoundPerSecond: return _value * 453.59237; - case MassFlowUnit.ShortTonPerHour: return _value*251.9957611; - case MassFlowUnit.TonnePerDay: return _value/0.0864000; - case MassFlowUnit.TonnePerHour: return 1000*_value/3.6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MassFlowUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MassFlow ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MassFlow(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MassFlowUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MassFlowUnit.CentigramPerDay: return (baseUnitValue*86400) / 1e-2d; - case MassFlowUnit.CentigramPerSecond: return (baseUnitValue) / 1e-2d; - case MassFlowUnit.DecagramPerDay: return (baseUnitValue*86400) / 1e1d; - case MassFlowUnit.DecagramPerSecond: return (baseUnitValue) / 1e1d; - case MassFlowUnit.DecigramPerDay: return (baseUnitValue*86400) / 1e-1d; - case MassFlowUnit.DecigramPerSecond: return (baseUnitValue) / 1e-1d; - case MassFlowUnit.GramPerDay: return baseUnitValue*86400; - case MassFlowUnit.GramPerHour: return baseUnitValue*3600; - case MassFlowUnit.GramPerSecond: return baseUnitValue; - case MassFlowUnit.HectogramPerDay: return (baseUnitValue*86400) / 1e2d; - case MassFlowUnit.HectogramPerSecond: return (baseUnitValue) / 1e2d; - case MassFlowUnit.KilogramPerDay: return (baseUnitValue*86400) / 1e3d; - case MassFlowUnit.KilogramPerHour: return baseUnitValue*3.6; - case MassFlowUnit.KilogramPerMinute: return baseUnitValue*0.06; - case MassFlowUnit.KilogramPerSecond: return (baseUnitValue) / 1e3d; - case MassFlowUnit.MegagramPerDay: return (baseUnitValue*86400) / 1e6d; - case MassFlowUnit.MegapoundPerDay: return (baseUnitValue*190.47936) / 1e6d; - case MassFlowUnit.MegapoundPerHour: return (baseUnitValue*7.93664) / 1e6d; - case MassFlowUnit.MegapoundPerMinute: return (baseUnitValue*0.132277) / 1e6d; - case MassFlowUnit.MegapoundPerSecond: return (baseUnitValue / 453.59237) / 1e6d; - case MassFlowUnit.MicrogramPerDay: return (baseUnitValue*86400) / 1e-6d; - case MassFlowUnit.MicrogramPerSecond: return (baseUnitValue) / 1e-6d; - case MassFlowUnit.MilligramPerDay: return (baseUnitValue*86400) / 1e-3d; - case MassFlowUnit.MilligramPerSecond: return (baseUnitValue) / 1e-3d; - case MassFlowUnit.NanogramPerDay: return (baseUnitValue*86400) / 1e-9d; - case MassFlowUnit.NanogramPerSecond: return (baseUnitValue) / 1e-9d; - case MassFlowUnit.PoundPerDay: return baseUnitValue*190.47936; - case MassFlowUnit.PoundPerHour: return baseUnitValue*7.93664; - case MassFlowUnit.PoundPerMinute: return baseUnitValue*0.132277; - case MassFlowUnit.PoundPerSecond: return baseUnitValue / 453.59237; - case MassFlowUnit.ShortTonPerHour: return baseUnitValue/251.9957611; - case MassFlowUnit.TonnePerDay: return baseUnitValue*0.0864000; - case MassFlowUnit.TonnePerHour: return baseUnitValue*3.6/1000; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs index 44aa8d41fc..5ed0048169 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs @@ -76,6 +76,8 @@ static MassFlux() new UnitInfo(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, "KilogramsPerSecondPerSquareMillimeter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.MassFlux); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -114,6 +116,11 @@ public MassFlux(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -261,33 +268,33 @@ public MassFlux(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MassFluxUnit - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerHourPerSquareCentimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerHourPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerHourPerSquareMillimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerSecondPerSquareCentimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerSecondPerSquareMillimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerHourPerSquareCentimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerHourPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerHourPerSquareMillimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareCentimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMillimeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareCentimeter, quantity => new MassFlux(quantity.Value*3.6e2, MassFluxUnit.GramPerHourPerSquareCentimeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMeter, quantity => new MassFlux(quantity.Value*3.6e6, MassFluxUnit.GramPerHourPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMillimeter, quantity => new MassFlux(quantity.Value*3.6e0, MassFluxUnit.GramPerHourPerSquareMillimeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareCentimeter, quantity => new MassFlux(quantity.Value*1e-1, MassFluxUnit.GramPerSecondPerSquareCentimeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMeter, quantity => new MassFlux(quantity.Value*1e3, MassFluxUnit.GramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMillimeter, quantity => new MassFlux(quantity.Value*1e-3, MassFluxUnit.GramPerSecondPerSquareMillimeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareCentimeter, quantity => new MassFlux((quantity.Value*3.6e2) / 1e3d, MassFluxUnit.KilogramPerHourPerSquareCentimeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMeter, quantity => new MassFlux((quantity.Value*3.6e6) / 1e3d, MassFluxUnit.KilogramPerHourPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMillimeter, quantity => new MassFlux((quantity.Value*3.6e0) / 1e3d, MassFluxUnit.KilogramPerHourPerSquareMillimeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareCentimeter, quantity => new MassFlux((quantity.Value*1e-1) / 1e3d, MassFluxUnit.KilogramPerSecondPerSquareCentimeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMillimeter, quantity => new MassFlux((quantity.Value*1e-3) / 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMillimeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity); // Register in unit converter: MassFluxUnit -> BaseUnit - unitConverter.SetConversionFunction(MassFluxUnit.GramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MassFluxUnit.GramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux(quantity.Value/3.6e2, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.GramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux(quantity.Value/3.6e6, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.GramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux(quantity.Value/3.6e0, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.GramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux(quantity.Value/1e-1, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.GramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux(quantity.Value/1e3, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.GramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux(quantity.Value/1e-3, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux((quantity.Value/3.6e2) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux((quantity.Value/3.6e6) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux((quantity.Value/3.6e0) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux((quantity.Value/1e-1) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => new MassFlux((quantity.Value/1e-3) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter)); } /// @@ -803,11 +810,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MassFlux to another MassFlux with the unit representation . /// + /// The unit to convert to. /// A MassFlux with the specified unit. public MassFlux ToUnit(MassFluxUnit unit) { - var convertedValue = GetValueAs(unit); - return new MassFlux(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MassFlux to another MassFlux using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MassFlux with the specified unit. + public MassFlux ToUnit(MassFluxUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MassFlux), Unit, typeof(MassFlux), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MassFlux)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -816,7 +854,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MassFluxUnit unitAsMassFluxUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFluxUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassFluxUnit); + return ToUnit(unitAsMassFluxUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MassFluxUnit unitAsMassFluxUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFluxUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMassFluxUnit, unitConverter); } /// @@ -841,69 +888,15 @@ public MassFlux ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MassFluxUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MassFluxUnit.GramPerHourPerSquareCentimeter: return _value/3.6e2; - case MassFluxUnit.GramPerHourPerSquareMeter: return _value/3.6e6; - case MassFluxUnit.GramPerHourPerSquareMillimeter: return _value/3.6e0; - case MassFluxUnit.GramPerSecondPerSquareCentimeter: return _value/1e-1; - case MassFluxUnit.GramPerSecondPerSquareMeter: return _value/1e3; - case MassFluxUnit.GramPerSecondPerSquareMillimeter: return _value/1e-3; - case MassFluxUnit.KilogramPerHourPerSquareCentimeter: return (_value/3.6e2) * 1e3d; - case MassFluxUnit.KilogramPerHourPerSquareMeter: return (_value/3.6e6) * 1e3d; - case MassFluxUnit.KilogramPerHourPerSquareMillimeter: return (_value/3.6e0) * 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareCentimeter: return (_value/1e-1) * 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (_value/1e3) * 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareMillimeter: return (_value/1e-3) * 1e3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MassFluxUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MassFlux ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MassFlux(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MassFluxUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MassFluxUnit.GramPerHourPerSquareCentimeter: return baseUnitValue*3.6e2; - case MassFluxUnit.GramPerHourPerSquareMeter: return baseUnitValue*3.6e6; - case MassFluxUnit.GramPerHourPerSquareMillimeter: return baseUnitValue*3.6e0; - case MassFluxUnit.GramPerSecondPerSquareCentimeter: return baseUnitValue*1e-1; - case MassFluxUnit.GramPerSecondPerSquareMeter: return baseUnitValue*1e3; - case MassFluxUnit.GramPerSecondPerSquareMillimeter: return baseUnitValue*1e-3; - case MassFluxUnit.KilogramPerHourPerSquareCentimeter: return (baseUnitValue*3.6e2) / 1e3d; - case MassFluxUnit.KilogramPerHourPerSquareMeter: return (baseUnitValue*3.6e6) / 1e3d; - case MassFluxUnit.KilogramPerHourPerSquareMillimeter: return (baseUnitValue*3.6e0) / 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareCentimeter: return (baseUnitValue*1e-1) / 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (baseUnitValue*1e3) / 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareMillimeter: return (baseUnitValue*1e-3) / 1e3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs index b03de7d933..67380089bb 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs @@ -91,6 +91,8 @@ static MassFraction() new UnitInfo(MassFractionUnit.Percent, "Percent", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.MassFraction); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -129,6 +131,11 @@ public MassFraction(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -336,57 +343,57 @@ public MassFraction(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MassFractionUnit - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerGram, quantity => quantity.ToUnit(MassFractionUnit.CentigramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.CentigramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerGram, quantity => quantity.ToUnit(MassFractionUnit.DecagramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.DecagramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerGram, quantity => quantity.ToUnit(MassFractionUnit.DecigramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.DecigramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerGram, quantity => quantity.ToUnit(MassFractionUnit.GramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.GramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.HectogramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.HectogramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.KilogramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.KilogramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.MicrogramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.MicrogramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerGram, quantity => quantity.ToUnit(MassFractionUnit.MilligramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.MilligramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.NanogramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.NanogramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerBillion, quantity => quantity.ToUnit(MassFractionUnit.PartPerBillion)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerMillion, quantity => quantity.ToUnit(MassFractionUnit.PartPerMillion)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerThousand, quantity => quantity.ToUnit(MassFractionUnit.PartPerThousand)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerTrillion, quantity => quantity.ToUnit(MassFractionUnit.PartPerTrillion)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.Percent, quantity => quantity.ToUnit(MassFractionUnit.Percent)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerGram, quantity => new MassFraction((quantity.Value) / 1e-2d, MassFractionUnit.CentigramPerGram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerKilogram, quantity => new MassFraction((quantity.Value*1e3) / 1e-2d, MassFractionUnit.CentigramPerKilogram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerGram, quantity => new MassFraction((quantity.Value) / 1e1d, MassFractionUnit.DecagramPerGram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerKilogram, quantity => new MassFraction((quantity.Value*1e3) / 1e1d, MassFractionUnit.DecagramPerKilogram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerGram, quantity => new MassFraction((quantity.Value) / 1e-1d, MassFractionUnit.DecigramPerGram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerKilogram, quantity => new MassFraction((quantity.Value*1e3) / 1e-1d, MassFractionUnit.DecigramPerKilogram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerGram, quantity => new MassFraction(quantity.Value, MassFractionUnit.GramPerGram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerKilogram, quantity => new MassFraction(quantity.Value*1e3, MassFractionUnit.GramPerKilogram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerGram, quantity => new MassFraction((quantity.Value) / 1e2d, MassFractionUnit.HectogramPerGram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerKilogram, quantity => new MassFraction((quantity.Value*1e3) / 1e2d, MassFractionUnit.HectogramPerKilogram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerGram, quantity => new MassFraction((quantity.Value) / 1e3d, MassFractionUnit.KilogramPerGram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerKilogram, quantity => new MassFraction((quantity.Value*1e3) / 1e3d, MassFractionUnit.KilogramPerKilogram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerGram, quantity => new MassFraction((quantity.Value) / 1e-6d, MassFractionUnit.MicrogramPerGram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerKilogram, quantity => new MassFraction((quantity.Value*1e3) / 1e-6d, MassFractionUnit.MicrogramPerKilogram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerGram, quantity => new MassFraction((quantity.Value) / 1e-3d, MassFractionUnit.MilligramPerGram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerKilogram, quantity => new MassFraction((quantity.Value*1e3) / 1e-3d, MassFractionUnit.MilligramPerKilogram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerGram, quantity => new MassFraction((quantity.Value) / 1e-9d, MassFractionUnit.NanogramPerGram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerKilogram, quantity => new MassFraction((quantity.Value*1e3) / 1e-9d, MassFractionUnit.NanogramPerKilogram)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerBillion, quantity => new MassFraction(quantity.Value*1e9, MassFractionUnit.PartPerBillion)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerMillion, quantity => new MassFraction(quantity.Value*1e6, MassFractionUnit.PartPerMillion)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerThousand, quantity => new MassFraction(quantity.Value*1e3, MassFractionUnit.PartPerThousand)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerTrillion, quantity => new MassFraction(quantity.Value*1e12, MassFractionUnit.PartPerTrillion)); + unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.Percent, quantity => new MassFraction(quantity.Value*1e2, MassFractionUnit.Percent)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecimalFraction, quantity => quantity); // Register in unit converter: MassFractionUnit -> BaseUnit - unitConverter.SetConversionFunction(MassFractionUnit.CentigramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.CentigramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.DecagramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.DecagramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.DecigramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.DecigramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.GramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.GramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.HectogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.HectogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.KilogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.KilogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.MicrogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.MicrogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.MilligramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.MilligramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.NanogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.NanogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.PartPerBillion, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.PartPerMillion, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.PartPerThousand, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.PartPerTrillion, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassFractionUnit.Percent, MassFractionUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MassFractionUnit.CentigramPerGram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value) * 1e-2d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.CentigramPerKilogram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value/1e3) * 1e-2d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.DecagramPerGram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value) * 1e1d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.DecagramPerKilogram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value/1e3) * 1e1d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.DecigramPerGram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value) * 1e-1d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.DecigramPerKilogram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value/1e3) * 1e-1d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.GramPerGram, MassFractionUnit.DecimalFraction, quantity => new MassFraction(quantity.Value, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.GramPerKilogram, MassFractionUnit.DecimalFraction, quantity => new MassFraction(quantity.Value/1e3, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.HectogramPerGram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value) * 1e2d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.HectogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value/1e3) * 1e2d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.KilogramPerGram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value) * 1e3d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.KilogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value/1e3) * 1e3d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.MicrogramPerGram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value) * 1e-6d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.MicrogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value/1e3) * 1e-6d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.MilligramPerGram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value) * 1e-3d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.MilligramPerKilogram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value/1e3) * 1e-3d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.NanogramPerGram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value) * 1e-9d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.NanogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => new MassFraction((quantity.Value/1e3) * 1e-9d, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.PartPerBillion, MassFractionUnit.DecimalFraction, quantity => new MassFraction(quantity.Value/1e9, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.PartPerMillion, MassFractionUnit.DecimalFraction, quantity => new MassFraction(quantity.Value/1e6, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.PartPerThousand, MassFractionUnit.DecimalFraction, quantity => new MassFraction(quantity.Value/1e3, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.PartPerTrillion, MassFractionUnit.DecimalFraction, quantity => new MassFraction(quantity.Value/1e12, MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction(MassFractionUnit.Percent, MassFractionUnit.DecimalFraction, quantity => new MassFraction(quantity.Value/1e2, MassFractionUnit.DecimalFraction)); } /// @@ -1010,11 +1017,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MassFraction to another MassFraction with the unit representation . /// + /// The unit to convert to. /// A MassFraction with the specified unit. public MassFraction ToUnit(MassFractionUnit unit) { - var convertedValue = GetValueAs(unit); - return new MassFraction(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MassFraction to another MassFraction using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MassFraction with the specified unit. + public MassFraction ToUnit(MassFractionUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MassFraction), Unit, typeof(MassFraction), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MassFraction)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1023,7 +1061,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MassFractionUnit unitAsMassFractionUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFractionUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassFractionUnit); + return ToUnit(unitAsMassFractionUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MassFractionUnit unitAsMassFractionUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFractionUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMassFractionUnit, unitConverter); } /// @@ -1048,93 +1095,15 @@ public MassFraction ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MassFractionUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MassFractionUnit.CentigramPerGram: return (_value) * 1e-2d; - case MassFractionUnit.CentigramPerKilogram: return (_value/1e3) * 1e-2d; - case MassFractionUnit.DecagramPerGram: return (_value) * 1e1d; - case MassFractionUnit.DecagramPerKilogram: return (_value/1e3) * 1e1d; - case MassFractionUnit.DecigramPerGram: return (_value) * 1e-1d; - case MassFractionUnit.DecigramPerKilogram: return (_value/1e3) * 1e-1d; - case MassFractionUnit.DecimalFraction: return _value; - case MassFractionUnit.GramPerGram: return _value; - case MassFractionUnit.GramPerKilogram: return _value/1e3; - case MassFractionUnit.HectogramPerGram: return (_value) * 1e2d; - case MassFractionUnit.HectogramPerKilogram: return (_value/1e3) * 1e2d; - case MassFractionUnit.KilogramPerGram: return (_value) * 1e3d; - case MassFractionUnit.KilogramPerKilogram: return (_value/1e3) * 1e3d; - case MassFractionUnit.MicrogramPerGram: return (_value) * 1e-6d; - case MassFractionUnit.MicrogramPerKilogram: return (_value/1e3) * 1e-6d; - case MassFractionUnit.MilligramPerGram: return (_value) * 1e-3d; - case MassFractionUnit.MilligramPerKilogram: return (_value/1e3) * 1e-3d; - case MassFractionUnit.NanogramPerGram: return (_value) * 1e-9d; - case MassFractionUnit.NanogramPerKilogram: return (_value/1e3) * 1e-9d; - case MassFractionUnit.PartPerBillion: return _value/1e9; - case MassFractionUnit.PartPerMillion: return _value/1e6; - case MassFractionUnit.PartPerThousand: return _value/1e3; - case MassFractionUnit.PartPerTrillion: return _value/1e12; - case MassFractionUnit.Percent: return _value/1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MassFractionUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MassFraction ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MassFraction(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MassFractionUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MassFractionUnit.CentigramPerGram: return (baseUnitValue) / 1e-2d; - case MassFractionUnit.CentigramPerKilogram: return (baseUnitValue*1e3) / 1e-2d; - case MassFractionUnit.DecagramPerGram: return (baseUnitValue) / 1e1d; - case MassFractionUnit.DecagramPerKilogram: return (baseUnitValue*1e3) / 1e1d; - case MassFractionUnit.DecigramPerGram: return (baseUnitValue) / 1e-1d; - case MassFractionUnit.DecigramPerKilogram: return (baseUnitValue*1e3) / 1e-1d; - case MassFractionUnit.DecimalFraction: return baseUnitValue; - case MassFractionUnit.GramPerGram: return baseUnitValue; - case MassFractionUnit.GramPerKilogram: return baseUnitValue*1e3; - case MassFractionUnit.HectogramPerGram: return (baseUnitValue) / 1e2d; - case MassFractionUnit.HectogramPerKilogram: return (baseUnitValue*1e3) / 1e2d; - case MassFractionUnit.KilogramPerGram: return (baseUnitValue) / 1e3d; - case MassFractionUnit.KilogramPerKilogram: return (baseUnitValue*1e3) / 1e3d; - case MassFractionUnit.MicrogramPerGram: return (baseUnitValue) / 1e-6d; - case MassFractionUnit.MicrogramPerKilogram: return (baseUnitValue*1e3) / 1e-6d; - case MassFractionUnit.MilligramPerGram: return (baseUnitValue) / 1e-3d; - case MassFractionUnit.MilligramPerKilogram: return (baseUnitValue*1e3) / 1e-3d; - case MassFractionUnit.NanogramPerGram: return (baseUnitValue) / 1e-9d; - case MassFractionUnit.NanogramPerKilogram: return (baseUnitValue*1e3) / 1e-9d; - case MassFractionUnit.PartPerBillion: return baseUnitValue*1e9; - case MassFractionUnit.PartPerMillion: return baseUnitValue*1e6; - case MassFractionUnit.PartPerThousand: return baseUnitValue*1e3; - case MassFractionUnit.PartPerTrillion: return baseUnitValue*1e12; - case MassFractionUnit.Percent: return baseUnitValue*1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs index fa6ff14499..7f8adc4f76 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs @@ -92,6 +92,8 @@ static MassMomentOfInertia() new UnitInfo(MassMomentOfInertiaUnit.TonneSquareMilimeter, "TonneSquareMilimeters", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.MassMomentOfInertia); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -130,6 +132,11 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -357,65 +364,65 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MassMomentOfInertiaUnit - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareMillimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMillimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMilimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMilimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMilimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMilimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMillimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareFoot, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.PoundSquareFoot)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareInch, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.PoundSquareInch)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareFoot, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.SlugSquareFoot)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareInch, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.SlugSquareInch)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMilimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareMilimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareCentimeter, quantity => new MassMomentOfInertia(quantity.Value*1e7, MassMomentOfInertiaUnit.GramSquareCentimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareDecimeter, quantity => new MassMomentOfInertia(quantity.Value*1e5, MassMomentOfInertiaUnit.GramSquareDecimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value*1e3, MassMomentOfInertiaUnit.GramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMillimeter, quantity => new MassMomentOfInertia(quantity.Value*1e9, MassMomentOfInertiaUnit.GramSquareMillimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareCentimeter, quantity => new MassMomentOfInertia((quantity.Value*1e7) / 1e3d, MassMomentOfInertiaUnit.KilogramSquareCentimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareDecimeter, quantity => new MassMomentOfInertia((quantity.Value*1e5) / 1e3d, MassMomentOfInertiaUnit.KilogramSquareDecimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMillimeter, quantity => new MassMomentOfInertia((quantity.Value*1e9) / 1e3d, MassMomentOfInertiaUnit.KilogramSquareMillimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareCentimeter, quantity => new MassMomentOfInertia((quantity.Value*1e1) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareCentimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareDecimeter, quantity => new MassMomentOfInertia((quantity.Value*1e-1) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareDecimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMeter, quantity => new MassMomentOfInertia((quantity.Value*1e-3) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMilimeter, quantity => new MassMomentOfInertia((quantity.Value*1e3) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareMilimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareCentimeter, quantity => new MassMomentOfInertia((quantity.Value*1e1) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareCentimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareDecimeter, quantity => new MassMomentOfInertia((quantity.Value*1e-1) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareDecimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMeter, quantity => new MassMomentOfInertia((quantity.Value*1e-3) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMilimeter, quantity => new MassMomentOfInertia((quantity.Value*1e3) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareMilimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareCentimeter, quantity => new MassMomentOfInertia((quantity.Value*1e7) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareCentimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareDecimeter, quantity => new MassMomentOfInertia((quantity.Value*1e5) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareDecimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value*1e3) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMillimeter, quantity => new MassMomentOfInertia((quantity.Value*1e9) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareMillimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareFoot, quantity => new MassMomentOfInertia(quantity.Value/4.21401101e-2, MassMomentOfInertiaUnit.PoundSquareFoot)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareInch, quantity => new MassMomentOfInertia(quantity.Value/2.9263965e-4, MassMomentOfInertiaUnit.PoundSquareInch)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareFoot, quantity => new MassMomentOfInertia(quantity.Value/1.3558179619, MassMomentOfInertiaUnit.SlugSquareFoot)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareInch, quantity => new MassMomentOfInertia(quantity.Value/9.41540242e-3, MassMomentOfInertiaUnit.SlugSquareInch)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareCentimeter, quantity => new MassMomentOfInertia(quantity.Value*1e1, MassMomentOfInertiaUnit.TonneSquareCentimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareDecimeter, quantity => new MassMomentOfInertia(quantity.Value*1e-1, MassMomentOfInertiaUnit.TonneSquareDecimeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMeter, quantity => new MassMomentOfInertia(quantity.Value*1e-3, MassMomentOfInertiaUnit.TonneSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMilimeter, quantity => new MassMomentOfInertia(quantity.Value*1e3, MassMomentOfInertiaUnit.TonneSquareMilimeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity); // Register in unit converter: MassMomentOfInertiaUnit -> BaseUnit - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.PoundSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.PoundSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.SlugSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.SlugSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value/1e7, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value/1e5, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value/1e3, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value/1e9, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e7) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e5) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e9) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e1) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e-1) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e-3) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e3) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e1) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e-1) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e-3) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e3) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e7) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e5) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e3) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia((quantity.Value/1e9) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.PoundSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value*4.21401101e-2, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.PoundSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value*2.9263965e-4, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.SlugSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value*1.3558179619, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.SlugSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value*9.41540242e-3, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value/1e1, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value/1e-1, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value/1e-3, MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => new MassMomentOfInertia(quantity.Value/1e3, MassMomentOfInertiaUnit.KilogramSquareMeter)); } /// @@ -1075,11 +1082,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MassMomentOfInertia to another MassMomentOfInertia with the unit representation . /// + /// The unit to convert to. /// A MassMomentOfInertia with the specified unit. public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) { - var convertedValue = GetValueAs(unit); - return new MassMomentOfInertia(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MassMomentOfInertia to another MassMomentOfInertia using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MassMomentOfInertia with the specified unit. + public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MassMomentOfInertia), Unit, typeof(MassMomentOfInertia), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MassMomentOfInertia)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1088,7 +1126,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MassMomentOfInertiaUnit unitAsMassMomentOfInertiaUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassMomentOfInertiaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassMomentOfInertiaUnit); + return ToUnit(unitAsMassMomentOfInertiaUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MassMomentOfInertiaUnit unitAsMassMomentOfInertiaUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassMomentOfInertiaUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMassMomentOfInertiaUnit, unitConverter); } /// @@ -1113,101 +1160,15 @@ public MassMomentOfInertia ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MassMomentOfInertiaUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: return _value/1e7; - case MassMomentOfInertiaUnit.GramSquareDecimeter: return _value/1e5; - case MassMomentOfInertiaUnit.GramSquareMeter: return _value/1e3; - case MassMomentOfInertiaUnit.GramSquareMillimeter: return _value/1e9; - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (_value/1e7) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (_value/1e5) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMeter: return (_value/1e3) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (_value/1e9) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (_value/1e1) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (_value/1e-1) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (_value/1e-3) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (_value/1e3) * 1e3d; - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (_value/1e1) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (_value/1e-1) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (_value/1e-3) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (_value/1e3) * 1e6d; - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (_value/1e7) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (_value/1e5) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMeter: return (_value/1e3) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (_value/1e9) * 1e-3d; - case MassMomentOfInertiaUnit.PoundSquareFoot: return _value*4.21401101e-2; - case MassMomentOfInertiaUnit.PoundSquareInch: return _value*2.9263965e-4; - case MassMomentOfInertiaUnit.SlugSquareFoot: return _value*1.3558179619; - case MassMomentOfInertiaUnit.SlugSquareInch: return _value*9.41540242e-3; - case MassMomentOfInertiaUnit.TonneSquareCentimeter: return _value/1e1; - case MassMomentOfInertiaUnit.TonneSquareDecimeter: return _value/1e-1; - case MassMomentOfInertiaUnit.TonneSquareMeter: return _value/1e-3; - case MassMomentOfInertiaUnit.TonneSquareMilimeter: return _value/1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MassMomentOfInertiaUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MassMomentOfInertia ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MassMomentOfInertia(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MassMomentOfInertiaUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: return baseUnitValue*1e7; - case MassMomentOfInertiaUnit.GramSquareDecimeter: return baseUnitValue*1e5; - case MassMomentOfInertiaUnit.GramSquareMeter: return baseUnitValue*1e3; - case MassMomentOfInertiaUnit.GramSquareMillimeter: return baseUnitValue*1e9; - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (baseUnitValue*1e7) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (baseUnitValue*1e5) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMeter: return (baseUnitValue*1e3) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (baseUnitValue*1e9) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (baseUnitValue*1e1) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (baseUnitValue*1e-1) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (baseUnitValue*1e-3) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (baseUnitValue*1e3) / 1e3d; - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (baseUnitValue*1e1) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (baseUnitValue*1e-1) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (baseUnitValue*1e-3) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (baseUnitValue*1e3) / 1e6d; - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (baseUnitValue*1e7) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (baseUnitValue*1e5) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMeter: return (baseUnitValue*1e3) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (baseUnitValue*1e9) / 1e-3d; - case MassMomentOfInertiaUnit.PoundSquareFoot: return baseUnitValue/4.21401101e-2; - case MassMomentOfInertiaUnit.PoundSquareInch: return baseUnitValue/2.9263965e-4; - case MassMomentOfInertiaUnit.SlugSquareFoot: return baseUnitValue/1.3558179619; - case MassMomentOfInertiaUnit.SlugSquareInch: return baseUnitValue/9.41540242e-3; - case MassMomentOfInertiaUnit.TonneSquareCentimeter: return baseUnitValue*1e1; - case MassMomentOfInertiaUnit.TonneSquareDecimeter: return baseUnitValue*1e-1; - case MassMomentOfInertiaUnit.TonneSquareMeter: return baseUnitValue*1e-3; - case MassMomentOfInertiaUnit.TonneSquareMilimeter: return baseUnitValue*1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs index ebc1f044cf..e5df95fc5e 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs @@ -67,6 +67,8 @@ static MolarEnergy() new UnitInfo(MolarEnergyUnit.MegajoulePerMole, "MegajoulesPerMole", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.MolarEnergy); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -105,6 +107,11 @@ public MolarEnergy(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -207,15 +214,15 @@ public MolarEnergy(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MolarEnergyUnit - unitConverter.SetConversionFunction(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.KilojoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.KilojoulePerMole)); - unitConverter.SetConversionFunction(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.MegajoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.MegajoulePerMole)); + unitConverter.SetConversionFunction(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.KilojoulePerMole, quantity => new MolarEnergy((quantity.Value) / 1e3d, MolarEnergyUnit.KilojoulePerMole)); + unitConverter.SetConversionFunction(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.MegajoulePerMole, quantity => new MolarEnergy((quantity.Value) / 1e6d, MolarEnergyUnit.MegajoulePerMole)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => quantity); // Register in unit converter: MolarEnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(MolarEnergyUnit.KilojoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarEnergyUnit.MegajoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MolarEnergyUnit.KilojoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => new MolarEnergy((quantity.Value) * 1e3d, MolarEnergyUnit.JoulePerMole)); + unitConverter.SetConversionFunction(MolarEnergyUnit.MegajoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => new MolarEnergy((quantity.Value) * 1e6d, MolarEnergyUnit.JoulePerMole)); } /// @@ -650,11 +657,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MolarEnergy to another MolarEnergy with the unit representation . /// + /// The unit to convert to. /// A MolarEnergy with the specified unit. public MolarEnergy ToUnit(MolarEnergyUnit unit) { - var convertedValue = GetValueAs(unit); - return new MolarEnergy(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MolarEnergy to another MolarEnergy using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MolarEnergy with the specified unit. + public MolarEnergy ToUnit(MolarEnergyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MolarEnergy), Unit, typeof(MolarEnergy), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MolarEnergy)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -663,7 +701,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MolarEnergyUnit unitAsMolarEnergyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMolarEnergyUnit); + return ToUnit(unitAsMolarEnergyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MolarEnergyUnit unitAsMolarEnergyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMolarEnergyUnit, unitConverter); } /// @@ -688,51 +735,15 @@ public MolarEnergy ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MolarEnergyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MolarEnergyUnit.JoulePerMole: return _value; - case MolarEnergyUnit.KilojoulePerMole: return (_value) * 1e3d; - case MolarEnergyUnit.MegajoulePerMole: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MolarEnergyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MolarEnergy ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MolarEnergy(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MolarEnergyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MolarEnergyUnit.JoulePerMole: return baseUnitValue; - case MolarEnergyUnit.KilojoulePerMole: return (baseUnitValue) / 1e3d; - case MolarEnergyUnit.MegajoulePerMole: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs index 2fd739a88a..00da84ca93 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs @@ -67,6 +67,8 @@ static MolarEntropy() new UnitInfo(MolarEntropyUnit.MegajoulePerMoleKelvin, "MegajoulesPerMoleKelvin", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.MolarEntropy); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -105,6 +107,11 @@ public MolarEntropy(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -207,15 +214,15 @@ public MolarEntropy(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MolarEntropyUnit - unitConverter.SetConversionFunction(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.KilojoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.KilojoulePerMoleKelvin)); - unitConverter.SetConversionFunction(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.MegajoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.MegajoulePerMoleKelvin)); + unitConverter.SetConversionFunction(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.KilojoulePerMoleKelvin, quantity => new MolarEntropy((quantity.Value) / 1e3d, MolarEntropyUnit.KilojoulePerMoleKelvin)); + unitConverter.SetConversionFunction(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.MegajoulePerMoleKelvin, quantity => new MolarEntropy((quantity.Value) / 1e6d, MolarEntropyUnit.MegajoulePerMoleKelvin)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => quantity); // Register in unit converter: MolarEntropyUnit -> BaseUnit - unitConverter.SetConversionFunction(MolarEntropyUnit.KilojoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarEntropyUnit.MegajoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MolarEntropyUnit.KilojoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => new MolarEntropy((quantity.Value) * 1e3d, MolarEntropyUnit.JoulePerMoleKelvin)); + unitConverter.SetConversionFunction(MolarEntropyUnit.MegajoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => new MolarEntropy((quantity.Value) * 1e6d, MolarEntropyUnit.JoulePerMoleKelvin)); } /// @@ -650,11 +657,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MolarEntropy to another MolarEntropy with the unit representation . /// + /// The unit to convert to. /// A MolarEntropy with the specified unit. public MolarEntropy ToUnit(MolarEntropyUnit unit) { - var convertedValue = GetValueAs(unit); - return new MolarEntropy(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MolarEntropy to another MolarEntropy using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MolarEntropy with the specified unit. + public MolarEntropy ToUnit(MolarEntropyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MolarEntropy), Unit, typeof(MolarEntropy), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MolarEntropy)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -663,7 +701,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MolarEntropyUnit unitAsMolarEntropyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEntropyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMolarEntropyUnit); + return ToUnit(unitAsMolarEntropyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MolarEntropyUnit unitAsMolarEntropyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEntropyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMolarEntropyUnit, unitConverter); } /// @@ -688,51 +735,15 @@ public MolarEntropy ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MolarEntropyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: return _value; - case MolarEntropyUnit.KilojoulePerMoleKelvin: return (_value) * 1e3d; - case MolarEntropyUnit.MegajoulePerMoleKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MolarEntropyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MolarEntropy ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MolarEntropy(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MolarEntropyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: return baseUnitValue; - case MolarEntropyUnit.KilojoulePerMoleKelvin: return (baseUnitValue) / 1e3d; - case MolarEntropyUnit.MegajoulePerMoleKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs index f9895f5f3d..810adc25f9 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs @@ -76,6 +76,8 @@ static MolarMass() new UnitInfo(MolarMassUnit.PoundPerMole, "PoundsPerMole", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.MolarMass); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -114,6 +116,11 @@ public MolarMass(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -261,33 +268,33 @@ public MolarMass(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MolarMassUnit - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.CentigramPerMole, quantity => quantity.ToUnit(MolarMassUnit.CentigramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.DecagramPerMole, quantity => quantity.ToUnit(MolarMassUnit.DecagramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.DecigramPerMole, quantity => quantity.ToUnit(MolarMassUnit.DecigramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.GramPerMole, quantity => quantity.ToUnit(MolarMassUnit.GramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.HectogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.HectogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.KilopoundPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilopoundPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.MegapoundPerMole, quantity => quantity.ToUnit(MolarMassUnit.MegapoundPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.MicrogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.MicrogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.MilligramPerMole, quantity => quantity.ToUnit(MolarMassUnit.MilligramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.NanogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.NanogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.PoundPerMole, quantity => quantity.ToUnit(MolarMassUnit.PoundPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.CentigramPerMole, quantity => new MolarMass((quantity.Value*1e3) / 1e-2d, MolarMassUnit.CentigramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.DecagramPerMole, quantity => new MolarMass((quantity.Value*1e3) / 1e1d, MolarMassUnit.DecagramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.DecigramPerMole, quantity => new MolarMass((quantity.Value*1e3) / 1e-1d, MolarMassUnit.DecigramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.GramPerMole, quantity => new MolarMass(quantity.Value*1e3, MolarMassUnit.GramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.HectogramPerMole, quantity => new MolarMass((quantity.Value*1e3) / 1e2d, MolarMassUnit.HectogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.KilopoundPerMole, quantity => new MolarMass((quantity.Value/0.45359237) / 1e3d, MolarMassUnit.KilopoundPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.MegapoundPerMole, quantity => new MolarMass((quantity.Value/0.45359237) / 1e6d, MolarMassUnit.MegapoundPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.MicrogramPerMole, quantity => new MolarMass((quantity.Value*1e3) / 1e-6d, MolarMassUnit.MicrogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.MilligramPerMole, quantity => new MolarMass((quantity.Value*1e3) / 1e-3d, MolarMassUnit.MilligramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.NanogramPerMole, quantity => new MolarMass((quantity.Value*1e3) / 1e-9d, MolarMassUnit.NanogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.PoundPerMole, quantity => new MolarMass(quantity.Value/0.45359237, MolarMassUnit.PoundPerMole)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity); // Register in unit converter: MolarMassUnit -> BaseUnit - unitConverter.SetConversionFunction(MolarMassUnit.CentigramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.DecagramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.DecigramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.GramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.HectogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.KilopoundPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.MegapoundPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.MicrogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.MilligramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.NanogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarMassUnit.PoundPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MolarMassUnit.CentigramPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass((quantity.Value/1e3) * 1e-2d, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.DecagramPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass((quantity.Value/1e3) * 1e1d, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.DecigramPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass((quantity.Value/1e3) * 1e-1d, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.GramPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass(quantity.Value/1e3, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.HectogramPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass((quantity.Value/1e3) * 1e2d, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.KilopoundPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass((quantity.Value*0.45359237) * 1e3d, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.MegapoundPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass((quantity.Value*0.45359237) * 1e6d, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.MicrogramPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass((quantity.Value/1e3) * 1e-6d, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.MilligramPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass((quantity.Value/1e3) * 1e-3d, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.NanogramPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass((quantity.Value/1e3) * 1e-9d, MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction(MolarMassUnit.PoundPerMole, MolarMassUnit.KilogramPerMole, quantity => new MolarMass(quantity.Value*0.45359237, MolarMassUnit.KilogramPerMole)); } /// @@ -803,11 +810,42 @@ double IQuantity.As(Enum unit) /// /// Converts this MolarMass to another MolarMass with the unit representation . /// + /// The unit to convert to. /// A MolarMass with the specified unit. public MolarMass ToUnit(MolarMassUnit unit) { - var convertedValue = GetValueAs(unit); - return new MolarMass(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this MolarMass to another MolarMass using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A MolarMass with the specified unit. + public MolarMass ToUnit(MolarMassUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(MolarMass), Unit, typeof(MolarMass), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (MolarMass)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -816,7 +854,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MolarMassUnit unitAsMolarMassUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarMassUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMolarMassUnit); + return ToUnit(unitAsMolarMassUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MolarMassUnit unitAsMolarMassUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarMassUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMolarMassUnit, unitConverter); } /// @@ -841,69 +888,15 @@ public MolarMass ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MolarMassUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MolarMassUnit.CentigramPerMole: return (_value/1e3) * 1e-2d; - case MolarMassUnit.DecagramPerMole: return (_value/1e3) * 1e1d; - case MolarMassUnit.DecigramPerMole: return (_value/1e3) * 1e-1d; - case MolarMassUnit.GramPerMole: return _value/1e3; - case MolarMassUnit.HectogramPerMole: return (_value/1e3) * 1e2d; - case MolarMassUnit.KilogramPerMole: return (_value/1e3) * 1e3d; - case MolarMassUnit.KilopoundPerMole: return (_value*0.45359237) * 1e3d; - case MolarMassUnit.MegapoundPerMole: return (_value*0.45359237) * 1e6d; - case MolarMassUnit.MicrogramPerMole: return (_value/1e3) * 1e-6d; - case MolarMassUnit.MilligramPerMole: return (_value/1e3) * 1e-3d; - case MolarMassUnit.NanogramPerMole: return (_value/1e3) * 1e-9d; - case MolarMassUnit.PoundPerMole: return _value*0.45359237; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MolarMassUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal MolarMass ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new MolarMass(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MolarMassUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MolarMassUnit.CentigramPerMole: return (baseUnitValue*1e3) / 1e-2d; - case MolarMassUnit.DecagramPerMole: return (baseUnitValue*1e3) / 1e1d; - case MolarMassUnit.DecigramPerMole: return (baseUnitValue*1e3) / 1e-1d; - case MolarMassUnit.GramPerMole: return baseUnitValue*1e3; - case MolarMassUnit.HectogramPerMole: return (baseUnitValue*1e3) / 1e2d; - case MolarMassUnit.KilogramPerMole: return (baseUnitValue*1e3) / 1e3d; - case MolarMassUnit.KilopoundPerMole: return (baseUnitValue/0.45359237) / 1e3d; - case MolarMassUnit.MegapoundPerMole: return (baseUnitValue/0.45359237) / 1e6d; - case MolarMassUnit.MicrogramPerMole: return (baseUnitValue*1e3) / 1e-6d; - case MolarMassUnit.MilligramPerMole: return (baseUnitValue*1e3) / 1e-3d; - case MolarMassUnit.NanogramPerMole: return (baseUnitValue*1e3) / 1e-9d; - case MolarMassUnit.PoundPerMole: return baseUnitValue/0.45359237; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs index 15abdc87f8..3768ed7fd4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs @@ -75,6 +75,8 @@ static Molarity() new UnitInfo(MolarityUnit.PicomolesPerLiter, "PicomolesPerLiter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Molarity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -113,6 +115,11 @@ public Molarity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -240,25 +247,25 @@ public Molarity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> MolarityUnit - unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.CentimolesPerLiter, quantity => quantity.ToUnit(MolarityUnit.CentimolesPerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.DecimolesPerLiter, quantity => quantity.ToUnit(MolarityUnit.DecimolesPerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.MicromolesPerLiter, quantity => quantity.ToUnit(MolarityUnit.MicromolesPerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.MillimolesPerLiter, quantity => quantity.ToUnit(MolarityUnit.MillimolesPerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.MolesPerLiter, quantity => quantity.ToUnit(MolarityUnit.MolesPerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.NanomolesPerLiter, quantity => quantity.ToUnit(MolarityUnit.NanomolesPerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.PicomolesPerLiter, quantity => quantity.ToUnit(MolarityUnit.PicomolesPerLiter)); + unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.CentimolesPerLiter, quantity => new Molarity((quantity.Value*1e-3) / 1e-2d, MolarityUnit.CentimolesPerLiter)); + unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.DecimolesPerLiter, quantity => new Molarity((quantity.Value*1e-3) / 1e-1d, MolarityUnit.DecimolesPerLiter)); + unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.MicromolesPerLiter, quantity => new Molarity((quantity.Value*1e-3) / 1e-6d, MolarityUnit.MicromolesPerLiter)); + unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.MillimolesPerLiter, quantity => new Molarity((quantity.Value*1e-3) / 1e-3d, MolarityUnit.MillimolesPerLiter)); + unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.MolesPerLiter, quantity => new Molarity(quantity.Value*1e-3, MolarityUnit.MolesPerLiter)); + unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.NanomolesPerLiter, quantity => new Molarity((quantity.Value*1e-3) / 1e-9d, MolarityUnit.NanomolesPerLiter)); + unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.PicomolesPerLiter, quantity => new Molarity((quantity.Value*1e-3) / 1e-12d, MolarityUnit.PicomolesPerLiter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(MolarityUnit.MolesPerCubicMeter, MolarityUnit.MolesPerCubicMeter, quantity => quantity); // Register in unit converter: MolarityUnit -> BaseUnit - unitConverter.SetConversionFunction(MolarityUnit.CentimolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarityUnit.DecimolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarityUnit.MicromolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarityUnit.MillimolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarityUnit.MolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarityUnit.NanomolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(MolarityUnit.PicomolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(MolarityUnit.CentimolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => new Molarity((quantity.Value/1e-3) * 1e-2d, MolarityUnit.MolesPerCubicMeter)); + unitConverter.SetConversionFunction(MolarityUnit.DecimolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => new Molarity((quantity.Value/1e-3) * 1e-1d, MolarityUnit.MolesPerCubicMeter)); + unitConverter.SetConversionFunction(MolarityUnit.MicromolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => new Molarity((quantity.Value/1e-3) * 1e-6d, MolarityUnit.MolesPerCubicMeter)); + unitConverter.SetConversionFunction(MolarityUnit.MillimolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => new Molarity((quantity.Value/1e-3) * 1e-3d, MolarityUnit.MolesPerCubicMeter)); + unitConverter.SetConversionFunction(MolarityUnit.MolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => new Molarity(quantity.Value/1e-3, MolarityUnit.MolesPerCubicMeter)); + unitConverter.SetConversionFunction(MolarityUnit.NanomolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => new Molarity((quantity.Value/1e-3) * 1e-9d, MolarityUnit.MolesPerCubicMeter)); + unitConverter.SetConversionFunction(MolarityUnit.PicomolesPerLiter, MolarityUnit.MolesPerCubicMeter, quantity => new Molarity((quantity.Value/1e-3) * 1e-12d, MolarityUnit.MolesPerCubicMeter)); } /// @@ -738,11 +745,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Molarity to another Molarity with the unit representation . /// + /// The unit to convert to. /// A Molarity with the specified unit. public Molarity ToUnit(MolarityUnit unit) { - var convertedValue = GetValueAs(unit); - return new Molarity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Molarity to another Molarity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Molarity with the specified unit. + public Molarity ToUnit(MolarityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Molarity), Unit, typeof(Molarity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Molarity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -751,7 +789,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is MolarityUnit unitAsMolarityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMolarityUnit); + return ToUnit(unitAsMolarityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is MolarityUnit unitAsMolarityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsMolarityUnit, unitConverter); } /// @@ -776,61 +823,15 @@ public Molarity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(MolarityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case MolarityUnit.CentimolesPerLiter: return (_value/1e-3) * 1e-2d; - case MolarityUnit.DecimolesPerLiter: return (_value/1e-3) * 1e-1d; - case MolarityUnit.MicromolesPerLiter: return (_value/1e-3) * 1e-6d; - case MolarityUnit.MillimolesPerLiter: return (_value/1e-3) * 1e-3d; - case MolarityUnit.MolesPerCubicMeter: return _value; - case MolarityUnit.MolesPerLiter: return _value/1e-3; - case MolarityUnit.NanomolesPerLiter: return (_value/1e-3) * 1e-9d; - case MolarityUnit.PicomolesPerLiter: return (_value/1e-3) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(MolarityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Molarity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Molarity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(MolarityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case MolarityUnit.CentimolesPerLiter: return (baseUnitValue*1e-3) / 1e-2d; - case MolarityUnit.DecimolesPerLiter: return (baseUnitValue*1e-3) / 1e-1d; - case MolarityUnit.MicromolesPerLiter: return (baseUnitValue*1e-3) / 1e-6d; - case MolarityUnit.MillimolesPerLiter: return (baseUnitValue*1e-3) / 1e-3d; - case MolarityUnit.MolesPerCubicMeter: return baseUnitValue; - case MolarityUnit.MolesPerLiter: return baseUnitValue*1e-3; - case MolarityUnit.NanomolesPerLiter: return (baseUnitValue*1e-3) / 1e-9d; - case MolarityUnit.PicomolesPerLiter: return (baseUnitValue*1e-3) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs index 8a8098826b..9a747267fe 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs @@ -68,6 +68,8 @@ static Permeability() new UnitInfo(PermeabilityUnit.HenryPerMeter, "HenriesPerMeter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Permeability); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public Permeability(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Permeability to another Permeability with the unit representation . /// + /// The unit to convert to. /// A Permeability with the specified unit. public Permeability ToUnit(PermeabilityUnit unit) { - var convertedValue = GetValueAs(unit); - return new Permeability(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Permeability to another Permeability using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Permeability with the specified unit. + public Permeability ToUnit(PermeabilityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Permeability), Unit, typeof(Permeability), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Permeability)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is PermeabilityUnit unitAsPermeabilityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPermeabilityUnit); + return ToUnit(unitAsPermeabilityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is PermeabilityUnit unitAsPermeabilityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsPermeabilityUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public Permeability ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(PermeabilityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case PermeabilityUnit.HenryPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(PermeabilityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Permeability ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Permeability(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(PermeabilityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case PermeabilityUnit.HenryPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs index 0aecde7398..fbb77f2c71 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs @@ -68,6 +68,8 @@ static Permittivity() new UnitInfo(PermittivityUnit.FaradPerMeter, "FaradsPerMeter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Permittivity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public Permittivity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Permittivity to another Permittivity with the unit representation . /// + /// The unit to convert to. /// A Permittivity with the specified unit. public Permittivity ToUnit(PermittivityUnit unit) { - var convertedValue = GetValueAs(unit); - return new Permittivity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Permittivity to another Permittivity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Permittivity with the specified unit. + public Permittivity ToUnit(PermittivityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Permittivity), Unit, typeof(Permittivity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Permittivity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is PermittivityUnit unitAsPermittivityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermittivityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPermittivityUnit); + return ToUnit(unitAsPermittivityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is PermittivityUnit unitAsPermittivityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermittivityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsPermittivityUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public Permittivity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(PermittivityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case PermittivityUnit.FaradPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(PermittivityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Permittivity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Permittivity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(PermittivityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case PermittivityUnit.FaradPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Power.g.cs b/UnitsNet/GeneratedCode/Quantities/Power.g.cs index 778201aaa1..1cd5ca7258 100644 --- a/UnitsNet/GeneratedCode/Quantities/Power.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Power.g.cs @@ -89,6 +89,8 @@ static Power() new UnitInfo(PowerUnit.Watt, "Watts", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Power); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -127,6 +129,11 @@ public Power(decimal value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -344,59 +351,59 @@ public Power(decimal value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> PowerUnit - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.BoilerHorsepower, quantity => quantity.ToUnit(PowerUnit.BoilerHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.BritishThermalUnitPerHour, quantity => quantity.ToUnit(PowerUnit.BritishThermalUnitPerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Decawatt, quantity => quantity.ToUnit(PowerUnit.Decawatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Deciwatt, quantity => quantity.ToUnit(PowerUnit.Deciwatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.ElectricalHorsepower, quantity => quantity.ToUnit(PowerUnit.ElectricalHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Femtowatt, quantity => quantity.ToUnit(PowerUnit.Femtowatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.GigajoulePerHour, quantity => quantity.ToUnit(PowerUnit.GigajoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Gigawatt, quantity => quantity.ToUnit(PowerUnit.Gigawatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.HydraulicHorsepower, quantity => quantity.ToUnit(PowerUnit.HydraulicHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.JoulePerHour, quantity => quantity.ToUnit(PowerUnit.JoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.KilobritishThermalUnitPerHour, quantity => quantity.ToUnit(PowerUnit.KilobritishThermalUnitPerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.KilojoulePerHour, quantity => quantity.ToUnit(PowerUnit.KilojoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Kilowatt, quantity => quantity.ToUnit(PowerUnit.Kilowatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MechanicalHorsepower, quantity => quantity.ToUnit(PowerUnit.MechanicalHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MegajoulePerHour, quantity => quantity.ToUnit(PowerUnit.MegajoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Megawatt, quantity => quantity.ToUnit(PowerUnit.Megawatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MetricHorsepower, quantity => quantity.ToUnit(PowerUnit.MetricHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Microwatt, quantity => quantity.ToUnit(PowerUnit.Microwatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MillijoulePerHour, quantity => quantity.ToUnit(PowerUnit.MillijoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Milliwatt, quantity => quantity.ToUnit(PowerUnit.Milliwatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Nanowatt, quantity => quantity.ToUnit(PowerUnit.Nanowatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Petawatt, quantity => quantity.ToUnit(PowerUnit.Petawatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Picowatt, quantity => quantity.ToUnit(PowerUnit.Picowatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Terawatt, quantity => quantity.ToUnit(PowerUnit.Terawatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.BoilerHorsepower, quantity => new Power(quantity.Value/9812.5m, PowerUnit.BoilerHorsepower)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.BritishThermalUnitPerHour, quantity => new Power(quantity.Value/0.293071m, PowerUnit.BritishThermalUnitPerHour)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Decawatt, quantity => new Power((quantity.Value) / 1e1m, PowerUnit.Decawatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Deciwatt, quantity => new Power((quantity.Value) / 1e-1m, PowerUnit.Deciwatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.ElectricalHorsepower, quantity => new Power(quantity.Value/746m, PowerUnit.ElectricalHorsepower)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Femtowatt, quantity => new Power((quantity.Value) / 1e-15m, PowerUnit.Femtowatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.GigajoulePerHour, quantity => new Power((quantity.Value*3600m) / 1e9m, PowerUnit.GigajoulePerHour)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Gigawatt, quantity => new Power((quantity.Value) / 1e9m, PowerUnit.Gigawatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.HydraulicHorsepower, quantity => new Power(quantity.Value/745.69988145m, PowerUnit.HydraulicHorsepower)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.JoulePerHour, quantity => new Power(quantity.Value*3600m, PowerUnit.JoulePerHour)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.KilobritishThermalUnitPerHour, quantity => new Power((quantity.Value/0.293071m) / 1e3m, PowerUnit.KilobritishThermalUnitPerHour)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.KilojoulePerHour, quantity => new Power((quantity.Value*3600m) / 1e3m, PowerUnit.KilojoulePerHour)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Kilowatt, quantity => new Power((quantity.Value) / 1e3m, PowerUnit.Kilowatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MechanicalHorsepower, quantity => new Power(quantity.Value/745.69m, PowerUnit.MechanicalHorsepower)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MegajoulePerHour, quantity => new Power((quantity.Value*3600m) / 1e6m, PowerUnit.MegajoulePerHour)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Megawatt, quantity => new Power((quantity.Value) / 1e6m, PowerUnit.Megawatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MetricHorsepower, quantity => new Power(quantity.Value/735.49875m, PowerUnit.MetricHorsepower)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Microwatt, quantity => new Power((quantity.Value) / 1e-6m, PowerUnit.Microwatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MillijoulePerHour, quantity => new Power((quantity.Value*3600m) / 1e-3m, PowerUnit.MillijoulePerHour)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Milliwatt, quantity => new Power((quantity.Value) / 1e-3m, PowerUnit.Milliwatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Nanowatt, quantity => new Power((quantity.Value) / 1e-9m, PowerUnit.Nanowatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Petawatt, quantity => new Power((quantity.Value) / 1e15m, PowerUnit.Petawatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Picowatt, quantity => new Power((quantity.Value) / 1e-12m, PowerUnit.Picowatt)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Terawatt, quantity => new Power((quantity.Value) / 1e12m, PowerUnit.Terawatt)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Watt, quantity => quantity); // Register in unit converter: PowerUnit -> BaseUnit - unitConverter.SetConversionFunction(PowerUnit.BoilerHorsepower, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.BritishThermalUnitPerHour, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Decawatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Deciwatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.ElectricalHorsepower, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Femtowatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.GigajoulePerHour, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Gigawatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.HydraulicHorsepower, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.JoulePerHour, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.KilobritishThermalUnitPerHour, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.KilojoulePerHour, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Kilowatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.MechanicalHorsepower, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.MegajoulePerHour, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Megawatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.MetricHorsepower, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Microwatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.MillijoulePerHour, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Milliwatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Nanowatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Petawatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Picowatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerUnit.Terawatt, PowerUnit.Watt, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(PowerUnit.BoilerHorsepower, PowerUnit.Watt, quantity => new Power(quantity.Value*9812.5m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.BritishThermalUnitPerHour, PowerUnit.Watt, quantity => new Power(quantity.Value*0.293071m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Decawatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e1m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Deciwatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e-1m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.ElectricalHorsepower, PowerUnit.Watt, quantity => new Power(quantity.Value*746m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Femtowatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e-15m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.GigajoulePerHour, PowerUnit.Watt, quantity => new Power((quantity.Value/3600m) * 1e9m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Gigawatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e9m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.HydraulicHorsepower, PowerUnit.Watt, quantity => new Power(quantity.Value*745.69988145m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.JoulePerHour, PowerUnit.Watt, quantity => new Power(quantity.Value/3600m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.KilobritishThermalUnitPerHour, PowerUnit.Watt, quantity => new Power((quantity.Value*0.293071m) * 1e3m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.KilojoulePerHour, PowerUnit.Watt, quantity => new Power((quantity.Value/3600m) * 1e3m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Kilowatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e3m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.MechanicalHorsepower, PowerUnit.Watt, quantity => new Power(quantity.Value*745.69m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.MegajoulePerHour, PowerUnit.Watt, quantity => new Power((quantity.Value/3600m) * 1e6m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Megawatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e6m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.MetricHorsepower, PowerUnit.Watt, quantity => new Power(quantity.Value*735.49875m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Microwatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e-6m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.MillijoulePerHour, PowerUnit.Watt, quantity => new Power((quantity.Value/3600m) * 1e-3m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Milliwatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e-3m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Nanowatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e-9m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Petawatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e15m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Picowatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e-12m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.Terawatt, PowerUnit.Watt, quantity => new Power((quantity.Value) * 1e12m, PowerUnit.Watt)); } /// @@ -1029,11 +1036,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Power to another Power with the unit representation . /// + /// The unit to convert to. /// A Power with the specified unit. public Power ToUnit(PowerUnit unit) { - var convertedValue = GetValueAs(unit); - return new Power(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Power to another Power using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Power with the specified unit. + public Power ToUnit(PowerUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Power), Unit, typeof(Power), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Power)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1042,7 +1080,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is PowerUnit unitAsPowerUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPowerUnit); + return ToUnit(unitAsPowerUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is PowerUnit unitAsPowerUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsPowerUnit, unitConverter); } /// @@ -1067,95 +1114,15 @@ public Power ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(PowerUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private decimal GetValueInBaseUnit() - { - switch(Unit) - { - case PowerUnit.BoilerHorsepower: return _value*9812.5m; - case PowerUnit.BritishThermalUnitPerHour: return _value*0.293071m; - case PowerUnit.Decawatt: return (_value) * 1e1m; - case PowerUnit.Deciwatt: return (_value) * 1e-1m; - case PowerUnit.ElectricalHorsepower: return _value*746m; - case PowerUnit.Femtowatt: return (_value) * 1e-15m; - case PowerUnit.GigajoulePerHour: return (_value/3600m) * 1e9m; - case PowerUnit.Gigawatt: return (_value) * 1e9m; - case PowerUnit.HydraulicHorsepower: return _value*745.69988145m; - case PowerUnit.JoulePerHour: return _value/3600m; - case PowerUnit.KilobritishThermalUnitPerHour: return (_value*0.293071m) * 1e3m; - case PowerUnit.KilojoulePerHour: return (_value/3600m) * 1e3m; - case PowerUnit.Kilowatt: return (_value) * 1e3m; - case PowerUnit.MechanicalHorsepower: return _value*745.69m; - case PowerUnit.MegajoulePerHour: return (_value/3600m) * 1e6m; - case PowerUnit.Megawatt: return (_value) * 1e6m; - case PowerUnit.MetricHorsepower: return _value*735.49875m; - case PowerUnit.Microwatt: return (_value) * 1e-6m; - case PowerUnit.MillijoulePerHour: return (_value/3600m) * 1e-3m; - case PowerUnit.Milliwatt: return (_value) * 1e-3m; - case PowerUnit.Nanowatt: return (_value) * 1e-9m; - case PowerUnit.Petawatt: return (_value) * 1e15m; - case PowerUnit.Picowatt: return (_value) * 1e-12m; - case PowerUnit.Terawatt: return (_value) * 1e12m; - case PowerUnit.Watt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(PowerUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Power ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Power(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private decimal GetValueAs(PowerUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case PowerUnit.BoilerHorsepower: return baseUnitValue/9812.5m; - case PowerUnit.BritishThermalUnitPerHour: return baseUnitValue/0.293071m; - case PowerUnit.Decawatt: return (baseUnitValue) / 1e1m; - case PowerUnit.Deciwatt: return (baseUnitValue) / 1e-1m; - case PowerUnit.ElectricalHorsepower: return baseUnitValue/746m; - case PowerUnit.Femtowatt: return (baseUnitValue) / 1e-15m; - case PowerUnit.GigajoulePerHour: return (baseUnitValue*3600m) / 1e9m; - case PowerUnit.Gigawatt: return (baseUnitValue) / 1e9m; - case PowerUnit.HydraulicHorsepower: return baseUnitValue/745.69988145m; - case PowerUnit.JoulePerHour: return baseUnitValue*3600m; - case PowerUnit.KilobritishThermalUnitPerHour: return (baseUnitValue/0.293071m) / 1e3m; - case PowerUnit.KilojoulePerHour: return (baseUnitValue*3600m) / 1e3m; - case PowerUnit.Kilowatt: return (baseUnitValue) / 1e3m; - case PowerUnit.MechanicalHorsepower: return baseUnitValue/745.69m; - case PowerUnit.MegajoulePerHour: return (baseUnitValue*3600m) / 1e6m; - case PowerUnit.Megawatt: return (baseUnitValue) / 1e6m; - case PowerUnit.MetricHorsepower: return baseUnitValue/735.49875m; - case PowerUnit.Microwatt: return (baseUnitValue) / 1e-6m; - case PowerUnit.MillijoulePerHour: return (baseUnitValue*3600m) / 1e-3m; - case PowerUnit.Milliwatt: return (baseUnitValue) / 1e-3m; - case PowerUnit.Nanowatt: return (baseUnitValue) / 1e-9m; - case PowerUnit.Petawatt: return (baseUnitValue) / 1e15m; - case PowerUnit.Picowatt: return (baseUnitValue) / 1e-12m; - case PowerUnit.Terawatt: return (baseUnitValue) / 1e12m; - case PowerUnit.Watt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (decimal)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs index 349efe35a7..f461a7aab0 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs @@ -108,6 +108,8 @@ static PowerDensity() new UnitInfo(PowerDensityUnit.WattPerLiter, "WattsPerLiter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.PowerDensity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -146,6 +148,11 @@ public PowerDensity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -453,97 +460,97 @@ public PowerDensity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> PowerDensityUnit - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e1d, PowerDensityUnit.DecawattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e1d, PowerDensityUnit.DecawattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e1d, PowerDensityUnit.DecawattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e1d, PowerDensityUnit.DecawattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e-1d, PowerDensityUnit.DeciwattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e-1d, PowerDensityUnit.DeciwattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e-1d, PowerDensityUnit.DeciwattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e-1d, PowerDensityUnit.DeciwattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e9d, PowerDensityUnit.GigawattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e9d, PowerDensityUnit.GigawattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e9d, PowerDensityUnit.GigawattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e9d, PowerDensityUnit.GigawattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e3d, PowerDensityUnit.KilowattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e3d, PowerDensityUnit.KilowattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e3d, PowerDensityUnit.KilowattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e3d, PowerDensityUnit.KilowattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e6d, PowerDensityUnit.MegawattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e6d, PowerDensityUnit.MegawattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e6d, PowerDensityUnit.MegawattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e6d, PowerDensityUnit.MegawattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e-6d, PowerDensityUnit.MicrowattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e-6d, PowerDensityUnit.MicrowattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e-6d, PowerDensityUnit.MicrowattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e-6d, PowerDensityUnit.MicrowattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e-3d, PowerDensityUnit.MilliwattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e-3d, PowerDensityUnit.MilliwattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e-3d, PowerDensityUnit.MilliwattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e-3d, PowerDensityUnit.MilliwattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e-9d, PowerDensityUnit.NanowattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e-9d, PowerDensityUnit.NanowattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e-9d, PowerDensityUnit.NanowattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e-9d, PowerDensityUnit.NanowattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e-12d, PowerDensityUnit.PicowattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e-12d, PowerDensityUnit.PicowattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e-12d, PowerDensityUnit.PicowattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e-12d, PowerDensityUnit.PicowattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicFoot, quantity => new PowerDensity((quantity.Value/3.531466672148859e1) / 1e12d, PowerDensityUnit.TerawattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicInch, quantity => new PowerDensity((quantity.Value/6.102374409473228e4) / 1e12d, PowerDensityUnit.TerawattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicMeter, quantity => new PowerDensity((quantity.Value) / 1e12d, PowerDensityUnit.TerawattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerLiter, quantity => new PowerDensity((quantity.Value/1.0e3) / 1e12d, PowerDensityUnit.TerawattPerLiter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicFoot, quantity => new PowerDensity(quantity.Value/3.531466672148859e1, PowerDensityUnit.WattPerCubicFoot)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicInch, quantity => new PowerDensity(quantity.Value/6.102374409473228e4, PowerDensityUnit.WattPerCubicInch)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerLiter, quantity => new PowerDensity(quantity.Value/1.0e3, PowerDensityUnit.WattPerLiter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity); // Register in unit converter: PowerDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e1d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e1d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e1d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e1d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e-1d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e-1d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e-1d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e-1d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e9d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e9d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e9d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e9d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e3d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e3d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e3d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e3d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e6d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e6d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e6d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e6d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e-6d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e-6d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e-6d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e-6d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e-3d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e-3d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e-3d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e-3d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e-9d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e-9d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e-9d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e-9d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e-12d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e-12d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e-12d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e-12d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*3.531466672148859e1) * 1e12d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*6.102374409473228e4) * 1e12d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value) * 1e12d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity((quantity.Value*1.0e3) * 1e12d, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity(quantity.Value*3.531466672148859e1, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity(quantity.Value*6.102374409473228e4, PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction(PowerDensityUnit.WattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => new PowerDensity(quantity.Value*1.0e3, PowerDensityUnit.WattPerCubicMeter)); } /// @@ -1347,11 +1354,42 @@ double IQuantity.As(Enum unit) /// /// Converts this PowerDensity to another PowerDensity with the unit representation . /// + /// The unit to convert to. /// A PowerDensity with the specified unit. public PowerDensity ToUnit(PowerDensityUnit unit) { - var convertedValue = GetValueAs(unit); - return new PowerDensity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this PowerDensity to another PowerDensity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A PowerDensity with the specified unit. + public PowerDensity ToUnit(PowerDensityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(PowerDensity), Unit, typeof(PowerDensity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (PowerDensity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1360,7 +1398,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is PowerDensityUnit unitAsPowerDensityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPowerDensityUnit); + return ToUnit(unitAsPowerDensityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is PowerDensityUnit unitAsPowerDensityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsPowerDensityUnit, unitConverter); } /// @@ -1385,133 +1432,15 @@ public PowerDensity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(PowerDensityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case PowerDensityUnit.DecawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e1d; - case PowerDensityUnit.DecawattPerCubicInch: return (_value*6.102374409473228e4) * 1e1d; - case PowerDensityUnit.DecawattPerCubicMeter: return (_value) * 1e1d; - case PowerDensityUnit.DecawattPerLiter: return (_value*1.0e3) * 1e1d; - case PowerDensityUnit.DeciwattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-1d; - case PowerDensityUnit.DeciwattPerCubicInch: return (_value*6.102374409473228e4) * 1e-1d; - case PowerDensityUnit.DeciwattPerCubicMeter: return (_value) * 1e-1d; - case PowerDensityUnit.DeciwattPerLiter: return (_value*1.0e3) * 1e-1d; - case PowerDensityUnit.GigawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e9d; - case PowerDensityUnit.GigawattPerCubicInch: return (_value*6.102374409473228e4) * 1e9d; - case PowerDensityUnit.GigawattPerCubicMeter: return (_value) * 1e9d; - case PowerDensityUnit.GigawattPerLiter: return (_value*1.0e3) * 1e9d; - case PowerDensityUnit.KilowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e3d; - case PowerDensityUnit.KilowattPerCubicInch: return (_value*6.102374409473228e4) * 1e3d; - case PowerDensityUnit.KilowattPerCubicMeter: return (_value) * 1e3d; - case PowerDensityUnit.KilowattPerLiter: return (_value*1.0e3) * 1e3d; - case PowerDensityUnit.MegawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e6d; - case PowerDensityUnit.MegawattPerCubicInch: return (_value*6.102374409473228e4) * 1e6d; - case PowerDensityUnit.MegawattPerCubicMeter: return (_value) * 1e6d; - case PowerDensityUnit.MegawattPerLiter: return (_value*1.0e3) * 1e6d; - case PowerDensityUnit.MicrowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-6d; - case PowerDensityUnit.MicrowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-6d; - case PowerDensityUnit.MicrowattPerCubicMeter: return (_value) * 1e-6d; - case PowerDensityUnit.MicrowattPerLiter: return (_value*1.0e3) * 1e-6d; - case PowerDensityUnit.MilliwattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-3d; - case PowerDensityUnit.MilliwattPerCubicInch: return (_value*6.102374409473228e4) * 1e-3d; - case PowerDensityUnit.MilliwattPerCubicMeter: return (_value) * 1e-3d; - case PowerDensityUnit.MilliwattPerLiter: return (_value*1.0e3) * 1e-3d; - case PowerDensityUnit.NanowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-9d; - case PowerDensityUnit.NanowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-9d; - case PowerDensityUnit.NanowattPerCubicMeter: return (_value) * 1e-9d; - case PowerDensityUnit.NanowattPerLiter: return (_value*1.0e3) * 1e-9d; - case PowerDensityUnit.PicowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-12d; - case PowerDensityUnit.PicowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-12d; - case PowerDensityUnit.PicowattPerCubicMeter: return (_value) * 1e-12d; - case PowerDensityUnit.PicowattPerLiter: return (_value*1.0e3) * 1e-12d; - case PowerDensityUnit.TerawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e12d; - case PowerDensityUnit.TerawattPerCubicInch: return (_value*6.102374409473228e4) * 1e12d; - case PowerDensityUnit.TerawattPerCubicMeter: return (_value) * 1e12d; - case PowerDensityUnit.TerawattPerLiter: return (_value*1.0e3) * 1e12d; - case PowerDensityUnit.WattPerCubicFoot: return _value*3.531466672148859e1; - case PowerDensityUnit.WattPerCubicInch: return _value*6.102374409473228e4; - case PowerDensityUnit.WattPerCubicMeter: return _value; - case PowerDensityUnit.WattPerLiter: return _value*1.0e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(PowerDensityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal PowerDensity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new PowerDensity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(PowerDensityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case PowerDensityUnit.DecawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e1d; - case PowerDensityUnit.DecawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e1d; - case PowerDensityUnit.DecawattPerCubicMeter: return (baseUnitValue) / 1e1d; - case PowerDensityUnit.DecawattPerLiter: return (baseUnitValue/1.0e3) / 1e1d; - case PowerDensityUnit.DeciwattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-1d; - case PowerDensityUnit.DeciwattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-1d; - case PowerDensityUnit.DeciwattPerCubicMeter: return (baseUnitValue) / 1e-1d; - case PowerDensityUnit.DeciwattPerLiter: return (baseUnitValue/1.0e3) / 1e-1d; - case PowerDensityUnit.GigawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e9d; - case PowerDensityUnit.GigawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e9d; - case PowerDensityUnit.GigawattPerCubicMeter: return (baseUnitValue) / 1e9d; - case PowerDensityUnit.GigawattPerLiter: return (baseUnitValue/1.0e3) / 1e9d; - case PowerDensityUnit.KilowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e3d; - case PowerDensityUnit.KilowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e3d; - case PowerDensityUnit.KilowattPerCubicMeter: return (baseUnitValue) / 1e3d; - case PowerDensityUnit.KilowattPerLiter: return (baseUnitValue/1.0e3) / 1e3d; - case PowerDensityUnit.MegawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e6d; - case PowerDensityUnit.MegawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e6d; - case PowerDensityUnit.MegawattPerCubicMeter: return (baseUnitValue) / 1e6d; - case PowerDensityUnit.MegawattPerLiter: return (baseUnitValue/1.0e3) / 1e6d; - case PowerDensityUnit.MicrowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-6d; - case PowerDensityUnit.MicrowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-6d; - case PowerDensityUnit.MicrowattPerCubicMeter: return (baseUnitValue) / 1e-6d; - case PowerDensityUnit.MicrowattPerLiter: return (baseUnitValue/1.0e3) / 1e-6d; - case PowerDensityUnit.MilliwattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-3d; - case PowerDensityUnit.MilliwattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-3d; - case PowerDensityUnit.MilliwattPerCubicMeter: return (baseUnitValue) / 1e-3d; - case PowerDensityUnit.MilliwattPerLiter: return (baseUnitValue/1.0e3) / 1e-3d; - case PowerDensityUnit.NanowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-9d; - case PowerDensityUnit.NanowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-9d; - case PowerDensityUnit.NanowattPerCubicMeter: return (baseUnitValue) / 1e-9d; - case PowerDensityUnit.NanowattPerLiter: return (baseUnitValue/1.0e3) / 1e-9d; - case PowerDensityUnit.PicowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-12d; - case PowerDensityUnit.PicowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-12d; - case PowerDensityUnit.PicowattPerCubicMeter: return (baseUnitValue) / 1e-12d; - case PowerDensityUnit.PicowattPerLiter: return (baseUnitValue/1.0e3) / 1e-12d; - case PowerDensityUnit.TerawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e12d; - case PowerDensityUnit.TerawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e12d; - case PowerDensityUnit.TerawattPerCubicMeter: return (baseUnitValue) / 1e12d; - case PowerDensityUnit.TerawattPerLiter: return (baseUnitValue/1.0e3) / 1e12d; - case PowerDensityUnit.WattPerCubicFoot: return baseUnitValue/3.531466672148859e1; - case PowerDensityUnit.WattPerCubicInch: return baseUnitValue/6.102374409473228e4; - case PowerDensityUnit.WattPerCubicMeter: return baseUnitValue; - case PowerDensityUnit.WattPerLiter: return baseUnitValue/1.0e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs index bfb428a7ba..94317bac25 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs @@ -66,6 +66,8 @@ static PowerRatio() new UnitInfo(PowerRatioUnit.DecibelWatt, "DecibelWatts", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.PowerRatio); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -104,6 +106,11 @@ public PowerRatio(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -201,13 +208,13 @@ public PowerRatio(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> PowerRatioUnit - unitConverter.SetConversionFunction(PowerRatioUnit.DecibelWatt, PowerRatioUnit.DecibelMilliwatt, quantity => quantity.ToUnit(PowerRatioUnit.DecibelMilliwatt)); + unitConverter.SetConversionFunction(PowerRatioUnit.DecibelWatt, PowerRatioUnit.DecibelMilliwatt, quantity => new PowerRatio(quantity.Value + 30, PowerRatioUnit.DecibelMilliwatt)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(PowerRatioUnit.DecibelWatt, PowerRatioUnit.DecibelWatt, quantity => quantity); // Register in unit converter: PowerRatioUnit -> BaseUnit - unitConverter.SetConversionFunction(PowerRatioUnit.DecibelMilliwatt, PowerRatioUnit.DecibelWatt, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(PowerRatioUnit.DecibelMilliwatt, PowerRatioUnit.DecibelWatt, quantity => new PowerRatio(quantity.Value - 30, PowerRatioUnit.DecibelWatt)); } /// @@ -641,11 +648,42 @@ double IQuantity.As(Enum unit) /// /// Converts this PowerRatio to another PowerRatio with the unit representation . /// + /// The unit to convert to. /// A PowerRatio with the specified unit. public PowerRatio ToUnit(PowerRatioUnit unit) { - var convertedValue = GetValueAs(unit); - return new PowerRatio(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this PowerRatio to another PowerRatio using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A PowerRatio with the specified unit. + public PowerRatio ToUnit(PowerRatioUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(PowerRatio), Unit, typeof(PowerRatio), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (PowerRatio)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -654,7 +692,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is PowerRatioUnit unitAsPowerRatioUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerRatioUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPowerRatioUnit); + return ToUnit(unitAsPowerRatioUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is PowerRatioUnit unitAsPowerRatioUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerRatioUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsPowerRatioUnit, unitConverter); } /// @@ -679,49 +726,15 @@ public PowerRatio ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(PowerRatioUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case PowerRatioUnit.DecibelMilliwatt: return _value - 30; - case PowerRatioUnit.DecibelWatt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(PowerRatioUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal PowerRatio ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new PowerRatio(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(PowerRatioUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case PowerRatioUnit.DecibelMilliwatt: return baseUnitValue + 30; - case PowerRatioUnit.DecibelWatt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index 747f792962..2939d0d85e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -109,6 +109,8 @@ static Pressure() new UnitInfo(PressureUnit.Torr, "Torrs", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Pressure); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -147,6 +149,11 @@ public Pressure(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -459,99 +466,99 @@ public Pressure(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> PressureUnit - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Atmosphere, quantity => quantity.ToUnit(PressureUnit.Atmosphere)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Bar, quantity => quantity.ToUnit(PressureUnit.Bar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Centibar, quantity => quantity.ToUnit(PressureUnit.Centibar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Decapascal, quantity => quantity.ToUnit(PressureUnit.Decapascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Decibar, quantity => quantity.ToUnit(PressureUnit.Decibar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.DynePerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.DynePerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.FootOfElevation, quantity => quantity.ToUnit(PressureUnit.FootOfElevation)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.FootOfHead, quantity => quantity.ToUnit(PressureUnit.FootOfHead)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Gigapascal, quantity => quantity.ToUnit(PressureUnit.Gigapascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Hectopascal, quantity => quantity.ToUnit(PressureUnit.Hectopascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.InchOfMercury, quantity => quantity.ToUnit(PressureUnit.InchOfMercury)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.InchOfWaterColumn, quantity => quantity.ToUnit(PressureUnit.InchOfWaterColumn)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Kilobar, quantity => quantity.ToUnit(PressureUnit.Kilobar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.KilogramForcePerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMeter, quantity => quantity.ToUnit(PressureUnit.KilogramForcePerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.KilogramForcePerSquareMillimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.KilonewtonPerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMeter, quantity => quantity.ToUnit(PressureUnit.KilonewtonPerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.KilonewtonPerSquareMillimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Kilopascal, quantity => quantity.ToUnit(PressureUnit.Kilopascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareFoot, quantity => quantity.ToUnit(PressureUnit.KilopoundForcePerSquareFoot)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareInch, quantity => quantity.ToUnit(PressureUnit.KilopoundForcePerSquareInch)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Megabar, quantity => quantity.ToUnit(PressureUnit.Megabar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MeganewtonPerSquareMeter, quantity => quantity.ToUnit(PressureUnit.MeganewtonPerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Megapascal, quantity => quantity.ToUnit(PressureUnit.Megapascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MeterOfElevation, quantity => quantity.ToUnit(PressureUnit.MeterOfElevation)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MeterOfHead, quantity => quantity.ToUnit(PressureUnit.MeterOfHead)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Microbar, quantity => quantity.ToUnit(PressureUnit.Microbar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Micropascal, quantity => quantity.ToUnit(PressureUnit.Micropascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Millibar, quantity => quantity.ToUnit(PressureUnit.Millibar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MillimeterOfMercury, quantity => quantity.ToUnit(PressureUnit.MillimeterOfMercury)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MillimeterOfWaterColumn, quantity => quantity.ToUnit(PressureUnit.MillimeterOfWaterColumn)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Millipascal, quantity => quantity.ToUnit(PressureUnit.Millipascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.NewtonPerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.NewtonPerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.NewtonPerSquareMeter, quantity => quantity.ToUnit(PressureUnit.NewtonPerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.NewtonPerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.NewtonPerSquareMillimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareFoot, quantity => quantity.ToUnit(PressureUnit.PoundForcePerSquareFoot)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareInch, quantity => quantity.ToUnit(PressureUnit.PoundForcePerSquareInch)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundPerInchSecondSquared, quantity => quantity.ToUnit(PressureUnit.PoundPerInchSecondSquared)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TechnicalAtmosphere, quantity => quantity.ToUnit(PressureUnit.TechnicalAtmosphere)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.TonneForcePerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMeter, quantity => quantity.ToUnit(PressureUnit.TonneForcePerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.TonneForcePerSquareMillimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Torr, quantity => quantity.ToUnit(PressureUnit.Torr)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Atmosphere, quantity => new Pressure(quantity.Value/(1.01325*1e5), PressureUnit.Atmosphere)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Bar, quantity => new Pressure(quantity.Value/1e5, PressureUnit.Bar)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Centibar, quantity => new Pressure((quantity.Value/1e5) / 1e-2d, PressureUnit.Centibar)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Decapascal, quantity => new Pressure((quantity.Value) / 1e1d, PressureUnit.Decapascal)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Decibar, quantity => new Pressure((quantity.Value/1e5) / 1e-1d, PressureUnit.Decibar)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.DynePerSquareCentimeter, quantity => new Pressure(quantity.Value/1.0e-1, PressureUnit.DynePerSquareCentimeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.FootOfElevation, quantity => new Pressure((1.0 - Math.Pow(quantity.Value / 101325.0, 0.190284)) * 145366.45, PressureUnit.FootOfElevation)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.FootOfHead, quantity => new Pressure(quantity.Value*0.000334552565551, PressureUnit.FootOfHead)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Gigapascal, quantity => new Pressure((quantity.Value) / 1e9d, PressureUnit.Gigapascal)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Hectopascal, quantity => new Pressure((quantity.Value) / 1e2d, PressureUnit.Hectopascal)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.InchOfMercury, quantity => new Pressure(quantity.Value*2.95299830714159e-4, PressureUnit.InchOfMercury)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.InchOfWaterColumn, quantity => new Pressure(quantity.Value/249.08890833333, PressureUnit.InchOfWaterColumn)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Kilobar, quantity => new Pressure((quantity.Value/1e5) / 1e3d, PressureUnit.Kilobar)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareCentimeter, quantity => new Pressure(quantity.Value/9.80665e4, PressureUnit.KilogramForcePerSquareCentimeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMeter, quantity => new Pressure(quantity.Value*0.101971619222242, PressureUnit.KilogramForcePerSquareMeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMillimeter, quantity => new Pressure(quantity.Value/9.80665e6, PressureUnit.KilogramForcePerSquareMillimeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareCentimeter, quantity => new Pressure((quantity.Value/1e4) / 1e3d, PressureUnit.KilonewtonPerSquareCentimeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMeter, quantity => new Pressure((quantity.Value) / 1e3d, PressureUnit.KilonewtonPerSquareMeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMillimeter, quantity => new Pressure((quantity.Value/1e6) / 1e3d, PressureUnit.KilonewtonPerSquareMillimeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Kilopascal, quantity => new Pressure((quantity.Value) / 1e3d, PressureUnit.Kilopascal)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareFoot, quantity => new Pressure((quantity.Value/4.788025898033584e1) / 1e3d, PressureUnit.KilopoundForcePerSquareFoot)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareInch, quantity => new Pressure((quantity.Value/6.894757293168361e3) / 1e3d, PressureUnit.KilopoundForcePerSquareInch)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Megabar, quantity => new Pressure((quantity.Value/1e5) / 1e6d, PressureUnit.Megabar)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MeganewtonPerSquareMeter, quantity => new Pressure((quantity.Value) / 1e6d, PressureUnit.MeganewtonPerSquareMeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Megapascal, quantity => new Pressure((quantity.Value) / 1e6d, PressureUnit.Megapascal)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MeterOfElevation, quantity => new Pressure((1.0 - Math.Pow(quantity.Value / 101325.0, 0.190284)) * 44307.69396, PressureUnit.MeterOfElevation)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MeterOfHead, quantity => new Pressure(quantity.Value*0.0001019977334, PressureUnit.MeterOfHead)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Microbar, quantity => new Pressure((quantity.Value/1e5) / 1e-6d, PressureUnit.Microbar)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Micropascal, quantity => new Pressure((quantity.Value) / 1e-6d, PressureUnit.Micropascal)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Millibar, quantity => new Pressure((quantity.Value/1e5) / 1e-3d, PressureUnit.Millibar)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MillimeterOfMercury, quantity => new Pressure(quantity.Value*7.50061561302643e-3, PressureUnit.MillimeterOfMercury)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MillimeterOfWaterColumn, quantity => new Pressure(quantity.Value/9.806650000000272e0, PressureUnit.MillimeterOfWaterColumn)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Millipascal, quantity => new Pressure((quantity.Value) / 1e-3d, PressureUnit.Millipascal)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.NewtonPerSquareCentimeter, quantity => new Pressure(quantity.Value/1e4, PressureUnit.NewtonPerSquareCentimeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.NewtonPerSquareMeter, quantity => new Pressure(quantity.Value, PressureUnit.NewtonPerSquareMeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.NewtonPerSquareMillimeter, quantity => new Pressure(quantity.Value/1e6, PressureUnit.NewtonPerSquareMillimeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareFoot, quantity => new Pressure(quantity.Value/4.788025898033584e1, PressureUnit.PoundForcePerSquareFoot)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareInch, quantity => new Pressure(quantity.Value/6.894757293168361e3, PressureUnit.PoundForcePerSquareInch)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundPerInchSecondSquared, quantity => new Pressure(quantity.Value/1.785796732283465e1, PressureUnit.PoundPerInchSecondSquared)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TechnicalAtmosphere, quantity => new Pressure(quantity.Value/(9.80680592331*1e4), PressureUnit.TechnicalAtmosphere)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareCentimeter, quantity => new Pressure(quantity.Value/9.80665e7, PressureUnit.TonneForcePerSquareCentimeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMeter, quantity => new Pressure(quantity.Value/9.80665e3, PressureUnit.TonneForcePerSquareMeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMillimeter, quantity => new Pressure(quantity.Value/9.80665e9, PressureUnit.TonneForcePerSquareMillimeter)); + unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Torr, quantity => new Pressure(quantity.Value/(1.3332266752*1e2), PressureUnit.Torr)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Pascal, quantity => quantity); // Register in unit converter: PressureUnit -> BaseUnit - unitConverter.SetConversionFunction(PressureUnit.Atmosphere, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Bar, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Centibar, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Decapascal, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Decibar, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.DynePerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.FootOfElevation, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.FootOfHead, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Gigapascal, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Hectopascal, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.InchOfMercury, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.InchOfWaterColumn, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Kilobar, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.KilogramForcePerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.KilogramForcePerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.KilogramForcePerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.KilonewtonPerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.KilonewtonPerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.KilonewtonPerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Kilopascal, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.KilopoundForcePerSquareFoot, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.KilopoundForcePerSquareInch, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Megabar, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.MeganewtonPerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Megapascal, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.MeterOfElevation, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.MeterOfHead, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Microbar, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Micropascal, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Millibar, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.MillimeterOfMercury, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.MillimeterOfWaterColumn, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Millipascal, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.NewtonPerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.NewtonPerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.NewtonPerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.PoundForcePerSquareFoot, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.PoundForcePerSquareInch, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.PoundPerInchSecondSquared, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.TechnicalAtmosphere, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.TonneForcePerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.TonneForcePerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.TonneForcePerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureUnit.Torr, PressureUnit.Pascal, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(PressureUnit.Atmosphere, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*1.01325*1e5, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Bar, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*1e5, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Centibar, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*1e5) * 1e-2d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Decapascal, PressureUnit.Pascal, quantity => new Pressure((quantity.Value) * 1e1d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Decibar, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*1e5) * 1e-1d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.DynePerSquareCentimeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*1.0e-1, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.FootOfElevation, PressureUnit.Pascal, quantity => new Pressure(Math.Pow(1.0 - (quantity.Value / 145366.45), 5.2553026003237266401799415610351) * 101325.0, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.FootOfHead, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*2989.0669, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Gigapascal, PressureUnit.Pascal, quantity => new Pressure((quantity.Value) * 1e9d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Hectopascal, PressureUnit.Pascal, quantity => new Pressure((quantity.Value) * 1e2d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.InchOfMercury, PressureUnit.Pascal, quantity => new Pressure(quantity.Value/2.95299830714159e-4, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.InchOfWaterColumn, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*249.08890833333, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Kilobar, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*1e5) * 1e3d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.KilogramForcePerSquareCentimeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*9.80665e4, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.KilogramForcePerSquareMeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*9.80665019960652, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.KilogramForcePerSquareMillimeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*9.80665e6, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.KilonewtonPerSquareCentimeter, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*1e4) * 1e3d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.KilonewtonPerSquareMeter, PressureUnit.Pascal, quantity => new Pressure((quantity.Value) * 1e3d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.KilonewtonPerSquareMillimeter, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*1e6) * 1e3d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Kilopascal, PressureUnit.Pascal, quantity => new Pressure((quantity.Value) * 1e3d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.KilopoundForcePerSquareFoot, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*4.788025898033584e1) * 1e3d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.KilopoundForcePerSquareInch, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*6.894757293168361e3) * 1e3d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Megabar, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*1e5) * 1e6d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.MeganewtonPerSquareMeter, PressureUnit.Pascal, quantity => new Pressure((quantity.Value) * 1e6d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Megapascal, PressureUnit.Pascal, quantity => new Pressure((quantity.Value) * 1e6d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.MeterOfElevation, PressureUnit.Pascal, quantity => new Pressure(Math.Pow(1.0 - (quantity.Value / 44307.69396), 5.2553026003237266401799415610351) * 101325.0, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.MeterOfHead, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*9804.139432, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Microbar, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*1e5) * 1e-6d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Micropascal, PressureUnit.Pascal, quantity => new Pressure((quantity.Value) * 1e-6d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Millibar, PressureUnit.Pascal, quantity => new Pressure((quantity.Value*1e5) * 1e-3d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.MillimeterOfMercury, PressureUnit.Pascal, quantity => new Pressure(quantity.Value/7.50061561302643e-3, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.MillimeterOfWaterColumn, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*9.806650000000272e0, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Millipascal, PressureUnit.Pascal, quantity => new Pressure((quantity.Value) * 1e-3d, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.NewtonPerSquareCentimeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*1e4, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.NewtonPerSquareMeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.NewtonPerSquareMillimeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*1e6, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.PoundForcePerSquareFoot, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*4.788025898033584e1, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.PoundForcePerSquareInch, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*6.894757293168361e3, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.PoundPerInchSecondSquared, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*1.785796732283465e1, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.TechnicalAtmosphere, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*9.80680592331*1e4, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.TonneForcePerSquareCentimeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*9.80665e7, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.TonneForcePerSquareMeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*9.80665e3, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.TonneForcePerSquareMillimeter, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*9.80665e9, PressureUnit.Pascal)); + unitConverter.SetConversionFunction(PressureUnit.Torr, PressureUnit.Pascal, quantity => new Pressure(quantity.Value*1.3332266752*1e2, PressureUnit.Pascal)); } /// @@ -1364,11 +1371,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Pressure to another Pressure with the unit representation . /// + /// The unit to convert to. /// A Pressure with the specified unit. public Pressure ToUnit(PressureUnit unit) { - var convertedValue = GetValueAs(unit); - return new Pressure(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Pressure to another Pressure using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Pressure with the specified unit. + public Pressure ToUnit(PressureUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Pressure), Unit, typeof(Pressure), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Pressure)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1377,7 +1415,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is PressureUnit unitAsPressureUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPressureUnit); + return ToUnit(unitAsPressureUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is PressureUnit unitAsPressureUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsPressureUnit, unitConverter); } /// @@ -1402,135 +1449,15 @@ public Pressure ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(PressureUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case PressureUnit.Atmosphere: return _value*1.01325*1e5; - case PressureUnit.Bar: return _value*1e5; - case PressureUnit.Centibar: return (_value*1e5) * 1e-2d; - case PressureUnit.Decapascal: return (_value) * 1e1d; - case PressureUnit.Decibar: return (_value*1e5) * 1e-1d; - case PressureUnit.DynePerSquareCentimeter: return _value*1.0e-1; - case PressureUnit.FootOfElevation: return Math.Pow(1.0 - (_value / 145366.45), 5.2553026003237266401799415610351) * 101325.0; - case PressureUnit.FootOfHead: return _value*2989.0669; - case PressureUnit.Gigapascal: return (_value) * 1e9d; - case PressureUnit.Hectopascal: return (_value) * 1e2d; - case PressureUnit.InchOfMercury: return _value/2.95299830714159e-4; - case PressureUnit.InchOfWaterColumn: return _value*249.08890833333; - case PressureUnit.Kilobar: return (_value*1e5) * 1e3d; - case PressureUnit.KilogramForcePerSquareCentimeter: return _value*9.80665e4; - case PressureUnit.KilogramForcePerSquareMeter: return _value*9.80665019960652; - case PressureUnit.KilogramForcePerSquareMillimeter: return _value*9.80665e6; - case PressureUnit.KilonewtonPerSquareCentimeter: return (_value*1e4) * 1e3d; - case PressureUnit.KilonewtonPerSquareMeter: return (_value) * 1e3d; - case PressureUnit.KilonewtonPerSquareMillimeter: return (_value*1e6) * 1e3d; - case PressureUnit.Kilopascal: return (_value) * 1e3d; - case PressureUnit.KilopoundForcePerSquareFoot: return (_value*4.788025898033584e1) * 1e3d; - case PressureUnit.KilopoundForcePerSquareInch: return (_value*6.894757293168361e3) * 1e3d; - case PressureUnit.Megabar: return (_value*1e5) * 1e6d; - case PressureUnit.MeganewtonPerSquareMeter: return (_value) * 1e6d; - case PressureUnit.Megapascal: return (_value) * 1e6d; - case PressureUnit.MeterOfElevation: return Math.Pow(1.0 - (_value / 44307.69396), 5.2553026003237266401799415610351) * 101325.0; - case PressureUnit.MeterOfHead: return _value*9804.139432; - case PressureUnit.Microbar: return (_value*1e5) * 1e-6d; - case PressureUnit.Micropascal: return (_value) * 1e-6d; - case PressureUnit.Millibar: return (_value*1e5) * 1e-3d; - case PressureUnit.MillimeterOfMercury: return _value/7.50061561302643e-3; - case PressureUnit.MillimeterOfWaterColumn: return _value*9.806650000000272e0; - case PressureUnit.Millipascal: return (_value) * 1e-3d; - case PressureUnit.NewtonPerSquareCentimeter: return _value*1e4; - case PressureUnit.NewtonPerSquareMeter: return _value; - case PressureUnit.NewtonPerSquareMillimeter: return _value*1e6; - case PressureUnit.Pascal: return _value; - case PressureUnit.PoundForcePerSquareFoot: return _value*4.788025898033584e1; - case PressureUnit.PoundForcePerSquareInch: return _value*6.894757293168361e3; - case PressureUnit.PoundPerInchSecondSquared: return _value*1.785796732283465e1; - case PressureUnit.TechnicalAtmosphere: return _value*9.80680592331*1e4; - case PressureUnit.TonneForcePerSquareCentimeter: return _value*9.80665e7; - case PressureUnit.TonneForcePerSquareMeter: return _value*9.80665e3; - case PressureUnit.TonneForcePerSquareMillimeter: return _value*9.80665e9; - case PressureUnit.Torr: return _value*1.3332266752*1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(PressureUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Pressure ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Pressure(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(PressureUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case PressureUnit.Atmosphere: return baseUnitValue/(1.01325*1e5); - case PressureUnit.Bar: return baseUnitValue/1e5; - case PressureUnit.Centibar: return (baseUnitValue/1e5) / 1e-2d; - case PressureUnit.Decapascal: return (baseUnitValue) / 1e1d; - case PressureUnit.Decibar: return (baseUnitValue/1e5) / 1e-1d; - case PressureUnit.DynePerSquareCentimeter: return baseUnitValue/1.0e-1; - case PressureUnit.FootOfElevation: return (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 145366.45; - case PressureUnit.FootOfHead: return baseUnitValue*0.000334552565551; - case PressureUnit.Gigapascal: return (baseUnitValue) / 1e9d; - case PressureUnit.Hectopascal: return (baseUnitValue) / 1e2d; - case PressureUnit.InchOfMercury: return baseUnitValue*2.95299830714159e-4; - case PressureUnit.InchOfWaterColumn: return baseUnitValue/249.08890833333; - case PressureUnit.Kilobar: return (baseUnitValue/1e5) / 1e3d; - case PressureUnit.KilogramForcePerSquareCentimeter: return baseUnitValue/9.80665e4; - case PressureUnit.KilogramForcePerSquareMeter: return baseUnitValue*0.101971619222242; - case PressureUnit.KilogramForcePerSquareMillimeter: return baseUnitValue/9.80665e6; - case PressureUnit.KilonewtonPerSquareCentimeter: return (baseUnitValue/1e4) / 1e3d; - case PressureUnit.KilonewtonPerSquareMeter: return (baseUnitValue) / 1e3d; - case PressureUnit.KilonewtonPerSquareMillimeter: return (baseUnitValue/1e6) / 1e3d; - case PressureUnit.Kilopascal: return (baseUnitValue) / 1e3d; - case PressureUnit.KilopoundForcePerSquareFoot: return (baseUnitValue/4.788025898033584e1) / 1e3d; - case PressureUnit.KilopoundForcePerSquareInch: return (baseUnitValue/6.894757293168361e3) / 1e3d; - case PressureUnit.Megabar: return (baseUnitValue/1e5) / 1e6d; - case PressureUnit.MeganewtonPerSquareMeter: return (baseUnitValue) / 1e6d; - case PressureUnit.Megapascal: return (baseUnitValue) / 1e6d; - case PressureUnit.MeterOfElevation: return (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 44307.69396; - case PressureUnit.MeterOfHead: return baseUnitValue*0.0001019977334; - case PressureUnit.Microbar: return (baseUnitValue/1e5) / 1e-6d; - case PressureUnit.Micropascal: return (baseUnitValue) / 1e-6d; - case PressureUnit.Millibar: return (baseUnitValue/1e5) / 1e-3d; - case PressureUnit.MillimeterOfMercury: return baseUnitValue*7.50061561302643e-3; - case PressureUnit.MillimeterOfWaterColumn: return baseUnitValue/9.806650000000272e0; - case PressureUnit.Millipascal: return (baseUnitValue) / 1e-3d; - case PressureUnit.NewtonPerSquareCentimeter: return baseUnitValue/1e4; - case PressureUnit.NewtonPerSquareMeter: return baseUnitValue; - case PressureUnit.NewtonPerSquareMillimeter: return baseUnitValue/1e6; - case PressureUnit.Pascal: return baseUnitValue; - case PressureUnit.PoundForcePerSquareFoot: return baseUnitValue/4.788025898033584e1; - case PressureUnit.PoundForcePerSquareInch: return baseUnitValue/6.894757293168361e3; - case PressureUnit.PoundPerInchSecondSquared: return baseUnitValue/1.785796732283465e1; - case PressureUnit.TechnicalAtmosphere: return baseUnitValue/(9.80680592331*1e4); - case PressureUnit.TonneForcePerSquareCentimeter: return baseUnitValue/9.80665e7; - case PressureUnit.TonneForcePerSquareMeter: return baseUnitValue/9.80665e3; - case PressureUnit.TonneForcePerSquareMillimeter: return baseUnitValue/9.80665e9; - case PressureUnit.Torr: return baseUnitValue/(1.3332266752*1e2); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs index 1ed139133e..8349035ece 100644 --- a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs @@ -78,6 +78,8 @@ static PressureChangeRate() new UnitInfo(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, "PoundsForcePerSquareInchPerSecond", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.PressureChangeRate); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -116,6 +118,11 @@ public PressureChangeRate(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -273,37 +280,37 @@ public PressureChangeRate(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> PressureChangeRateUnit - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.AtmospherePerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.AtmospherePerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopascalPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapascalPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillimeterOfMercuryPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MillimeterOfMercuryPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PascalPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.AtmospherePerSecond, quantity => new PressureChangeRate(quantity.Value / (1.01325*1e5), PressureChangeRateUnit.AtmospherePerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerMinute, quantity => new PressureChangeRate((quantity.Value*60) / 1e3d, PressureChangeRateUnit.KilopascalPerMinute)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerSecond, quantity => new PressureChangeRate((quantity.Value) / 1e3d, PressureChangeRateUnit.KilopascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, quantity => new PressureChangeRate((quantity.Value/6.894757293168361e3*60) / 1e3d, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, quantity => new PressureChangeRate((quantity.Value/6.894757293168361e3) / 1e3d, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerMinute, quantity => new PressureChangeRate((quantity.Value*60) / 1e6d, PressureChangeRateUnit.MegapascalPerMinute)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerSecond, quantity => new PressureChangeRate((quantity.Value) / 1e6d, PressureChangeRateUnit.MegapascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, quantity => new PressureChangeRate((quantity.Value/6.894757293168361e3*60) / 1e6d, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, quantity => new PressureChangeRate((quantity.Value/6.894757293168361e3) / 1e6d, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillimeterOfMercuryPerSecond, quantity => new PressureChangeRate(quantity.Value/133.322, PressureChangeRateUnit.MillimeterOfMercuryPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PascalPerMinute, quantity => new PressureChangeRate(quantity.Value*60, PressureChangeRateUnit.PascalPerMinute)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, quantity => new PressureChangeRate(quantity.Value/6.894757293168361e3*60, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, quantity => new PressureChangeRate(quantity.Value/6.894757293168361e3, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity); // Register in unit converter: PressureChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(PressureChangeRateUnit.AtmospherePerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(PressureChangeRateUnit.AtmospherePerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate(quantity.Value * 1.01325*1e5, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate((quantity.Value/60) * 1e3d, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate((quantity.Value) * 1e3d, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate((quantity.Value*6.894757293168361e3/60) * 1e3d, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate((quantity.Value*6.894757293168361e3) * 1e3d, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate((quantity.Value/60) * 1e6d, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate((quantity.Value) * 1e6d, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate((quantity.Value*6.894757293168361e3/60) * 1e6d, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate((quantity.Value*6.894757293168361e3) * 1e6d, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate(quantity.Value*133.322, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate(quantity.Value/60, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate(quantity.Value*6.894757293168361e3/60, PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => new PressureChangeRate(quantity.Value*6.894757293168361e3, PressureChangeRateUnit.PascalPerSecond)); } /// @@ -837,11 +844,42 @@ double IQuantity.As(Enum unit) /// /// Converts this PressureChangeRate to another PressureChangeRate with the unit representation . /// + /// The unit to convert to. /// A PressureChangeRate with the specified unit. public PressureChangeRate ToUnit(PressureChangeRateUnit unit) { - var convertedValue = GetValueAs(unit); - return new PressureChangeRate(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this PressureChangeRate to another PressureChangeRate using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A PressureChangeRate with the specified unit. + public PressureChangeRate ToUnit(PressureChangeRateUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(PressureChangeRate), Unit, typeof(PressureChangeRate), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (PressureChangeRate)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -850,7 +888,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is PressureChangeRateUnit unitAsPressureChangeRateUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPressureChangeRateUnit); + return ToUnit(unitAsPressureChangeRateUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is PressureChangeRateUnit unitAsPressureChangeRateUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsPressureChangeRateUnit, unitConverter); } /// @@ -875,73 +922,15 @@ public PressureChangeRate ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(PressureChangeRateUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case PressureChangeRateUnit.AtmospherePerSecond: return _value * 1.01325*1e5; - case PressureChangeRateUnit.KilopascalPerMinute: return (_value/60) * 1e3d; - case PressureChangeRateUnit.KilopascalPerSecond: return (_value) * 1e3d; - case PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute: return (_value*6.894757293168361e3/60) * 1e3d; - case PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond: return (_value*6.894757293168361e3) * 1e3d; - case PressureChangeRateUnit.MegapascalPerMinute: return (_value/60) * 1e6d; - case PressureChangeRateUnit.MegapascalPerSecond: return (_value) * 1e6d; - case PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute: return (_value*6.894757293168361e3/60) * 1e6d; - case PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond: return (_value*6.894757293168361e3) * 1e6d; - case PressureChangeRateUnit.MillimeterOfMercuryPerSecond: return _value*133.322; - case PressureChangeRateUnit.PascalPerMinute: return _value/60; - case PressureChangeRateUnit.PascalPerSecond: return _value; - case PressureChangeRateUnit.PoundForcePerSquareInchPerMinute: return _value*6.894757293168361e3/60; - case PressureChangeRateUnit.PoundForcePerSquareInchPerSecond: return _value*6.894757293168361e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(PressureChangeRateUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal PressureChangeRate ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new PressureChangeRate(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(PressureChangeRateUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case PressureChangeRateUnit.AtmospherePerSecond: return baseUnitValue / (1.01325*1e5); - case PressureChangeRateUnit.KilopascalPerMinute: return (baseUnitValue*60) / 1e3d; - case PressureChangeRateUnit.KilopascalPerSecond: return (baseUnitValue) / 1e3d; - case PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute: return (baseUnitValue/6.894757293168361e3*60) / 1e3d; - case PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond: return (baseUnitValue/6.894757293168361e3) / 1e3d; - case PressureChangeRateUnit.MegapascalPerMinute: return (baseUnitValue*60) / 1e6d; - case PressureChangeRateUnit.MegapascalPerSecond: return (baseUnitValue) / 1e6d; - case PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute: return (baseUnitValue/6.894757293168361e3*60) / 1e6d; - case PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond: return (baseUnitValue/6.894757293168361e3) / 1e6d; - case PressureChangeRateUnit.MillimeterOfMercuryPerSecond: return baseUnitValue/133.322; - case PressureChangeRateUnit.PascalPerMinute: return baseUnitValue*60; - case PressureChangeRateUnit.PascalPerSecond: return baseUnitValue; - case PressureChangeRateUnit.PoundForcePerSquareInchPerMinute: return baseUnitValue/6.894757293168361e3*60; - case PressureChangeRateUnit.PoundForcePerSquareInchPerSecond: return baseUnitValue/6.894757293168361e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs index fa52880d9a..160a6aea25 100644 --- a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs @@ -70,6 +70,8 @@ static Ratio() new UnitInfo(RatioUnit.Percent, "Percent", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Ratio); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -108,6 +110,11 @@ public Ratio(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -225,21 +232,21 @@ public Ratio(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> RatioUnit - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerBillion, quantity => quantity.ToUnit(RatioUnit.PartPerBillion)); - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerMillion, quantity => quantity.ToUnit(RatioUnit.PartPerMillion)); - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerThousand, quantity => quantity.ToUnit(RatioUnit.PartPerThousand)); - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerTrillion, quantity => quantity.ToUnit(RatioUnit.PartPerTrillion)); - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.Percent, quantity => quantity.ToUnit(RatioUnit.Percent)); + unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerBillion, quantity => new Ratio(quantity.Value*1e9, RatioUnit.PartPerBillion)); + unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerMillion, quantity => new Ratio(quantity.Value*1e6, RatioUnit.PartPerMillion)); + unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerThousand, quantity => new Ratio(quantity.Value*1e3, RatioUnit.PartPerThousand)); + unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerTrillion, quantity => new Ratio(quantity.Value*1e12, RatioUnit.PartPerTrillion)); + unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.Percent, quantity => new Ratio(quantity.Value*1e2, RatioUnit.Percent)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.DecimalFraction, quantity => quantity); // Register in unit converter: RatioUnit -> BaseUnit - unitConverter.SetConversionFunction(RatioUnit.PartPerBillion, RatioUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RatioUnit.PartPerMillion, RatioUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RatioUnit.PartPerThousand, RatioUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RatioUnit.PartPerTrillion, RatioUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RatioUnit.Percent, RatioUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(RatioUnit.PartPerBillion, RatioUnit.DecimalFraction, quantity => new Ratio(quantity.Value/1e9, RatioUnit.DecimalFraction)); + unitConverter.SetConversionFunction(RatioUnit.PartPerMillion, RatioUnit.DecimalFraction, quantity => new Ratio(quantity.Value/1e6, RatioUnit.DecimalFraction)); + unitConverter.SetConversionFunction(RatioUnit.PartPerThousand, RatioUnit.DecimalFraction, quantity => new Ratio(quantity.Value/1e3, RatioUnit.DecimalFraction)); + unitConverter.SetConversionFunction(RatioUnit.PartPerTrillion, RatioUnit.DecimalFraction, quantity => new Ratio(quantity.Value/1e12, RatioUnit.DecimalFraction)); + unitConverter.SetConversionFunction(RatioUnit.Percent, RatioUnit.DecimalFraction, quantity => new Ratio(quantity.Value/1e2, RatioUnit.DecimalFraction)); } /// @@ -701,11 +708,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Ratio to another Ratio with the unit representation . /// + /// The unit to convert to. /// A Ratio with the specified unit. public Ratio ToUnit(RatioUnit unit) { - var convertedValue = GetValueAs(unit); - return new Ratio(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Ratio to another Ratio using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Ratio with the specified unit. + public Ratio ToUnit(RatioUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Ratio), Unit, typeof(Ratio), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Ratio)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -714,7 +752,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is RatioUnit unitAsRatioUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRatioUnit); + return ToUnit(unitAsRatioUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is RatioUnit unitAsRatioUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsRatioUnit, unitConverter); } /// @@ -739,57 +786,15 @@ public Ratio ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(RatioUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case RatioUnit.DecimalFraction: return _value; - case RatioUnit.PartPerBillion: return _value/1e9; - case RatioUnit.PartPerMillion: return _value/1e6; - case RatioUnit.PartPerThousand: return _value/1e3; - case RatioUnit.PartPerTrillion: return _value/1e12; - case RatioUnit.Percent: return _value/1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(RatioUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Ratio ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Ratio(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(RatioUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case RatioUnit.DecimalFraction: return baseUnitValue; - case RatioUnit.PartPerBillion: return baseUnitValue*1e9; - case RatioUnit.PartPerMillion: return baseUnitValue*1e6; - case RatioUnit.PartPerThousand: return baseUnitValue*1e3; - case RatioUnit.PartPerTrillion: return baseUnitValue*1e12; - case RatioUnit.Percent: return baseUnitValue*1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs index 1d677760b9..4fa52a2934 100644 --- a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs @@ -66,6 +66,8 @@ static RatioChangeRate() new UnitInfo(RatioChangeRateUnit.PercentPerSecond, "PercentsPerSecond", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.RatioChangeRate); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -104,6 +106,11 @@ public RatioChangeRate(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -201,13 +208,13 @@ public RatioChangeRate(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> RatioChangeRateUnit - unitConverter.SetConversionFunction(RatioChangeRateUnit.DecimalFractionPerSecond, RatioChangeRateUnit.PercentPerSecond, quantity => quantity.ToUnit(RatioChangeRateUnit.PercentPerSecond)); + unitConverter.SetConversionFunction(RatioChangeRateUnit.DecimalFractionPerSecond, RatioChangeRateUnit.PercentPerSecond, quantity => new RatioChangeRate(quantity.Value*1e2, RatioChangeRateUnit.PercentPerSecond)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(RatioChangeRateUnit.DecimalFractionPerSecond, RatioChangeRateUnit.DecimalFractionPerSecond, quantity => quantity); // Register in unit converter: RatioChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(RatioChangeRateUnit.PercentPerSecond, RatioChangeRateUnit.DecimalFractionPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(RatioChangeRateUnit.PercentPerSecond, RatioChangeRateUnit.DecimalFractionPerSecond, quantity => new RatioChangeRate(quantity.Value/1e2, RatioChangeRateUnit.DecimalFractionPerSecond)); } /// @@ -633,11 +640,42 @@ double IQuantity.As(Enum unit) /// /// Converts this RatioChangeRate to another RatioChangeRate with the unit representation . /// + /// The unit to convert to. /// A RatioChangeRate with the specified unit. public RatioChangeRate ToUnit(RatioChangeRateUnit unit) { - var convertedValue = GetValueAs(unit); - return new RatioChangeRate(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this RatioChangeRate to another RatioChangeRate using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A RatioChangeRate with the specified unit. + public RatioChangeRate ToUnit(RatioChangeRateUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(RatioChangeRate), Unit, typeof(RatioChangeRate), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (RatioChangeRate)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -646,7 +684,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is RatioChangeRateUnit unitAsRatioChangeRateUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRatioChangeRateUnit); + return ToUnit(unitAsRatioChangeRateUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is RatioChangeRateUnit unitAsRatioChangeRateUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsRatioChangeRateUnit, unitConverter); } /// @@ -671,49 +718,15 @@ public RatioChangeRate ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(RatioChangeRateUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case RatioChangeRateUnit.DecimalFractionPerSecond: return _value; - case RatioChangeRateUnit.PercentPerSecond: return _value/1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(RatioChangeRateUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal RatioChangeRate ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new RatioChangeRate(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(RatioChangeRateUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case RatioChangeRateUnit.DecimalFractionPerSecond: return baseUnitValue; - case RatioChangeRateUnit.PercentPerSecond: return baseUnitValue*1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs index b5c24c49ff..3d199f5c00 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs @@ -67,6 +67,8 @@ static ReactiveEnergy() new UnitInfo(ReactiveEnergyUnit.VoltampereReactiveHour, "VoltampereReactiveHours", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ReactiveEnergy); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -105,6 +107,11 @@ public ReactiveEnergy(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -207,15 +214,15 @@ public ReactiveEnergy(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ReactiveEnergyUnit - unitConverter.SetConversionFunction(ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.KilovoltampereReactiveHour, quantity => quantity.ToUnit(ReactiveEnergyUnit.KilovoltampereReactiveHour)); - unitConverter.SetConversionFunction(ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.MegavoltampereReactiveHour, quantity => quantity.ToUnit(ReactiveEnergyUnit.MegavoltampereReactiveHour)); + unitConverter.SetConversionFunction(ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.KilovoltampereReactiveHour, quantity => new ReactiveEnergy((quantity.Value) / 1e3d, ReactiveEnergyUnit.KilovoltampereReactiveHour)); + unitConverter.SetConversionFunction(ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.MegavoltampereReactiveHour, quantity => new ReactiveEnergy((quantity.Value) / 1e6d, ReactiveEnergyUnit.MegavoltampereReactiveHour)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour, quantity => quantity); // Register in unit converter: ReactiveEnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(ReactiveEnergyUnit.KilovoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReactiveEnergyUnit.MegavoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ReactiveEnergyUnit.KilovoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour, quantity => new ReactiveEnergy((quantity.Value) * 1e3d, ReactiveEnergyUnit.VoltampereReactiveHour)); + unitConverter.SetConversionFunction(ReactiveEnergyUnit.MegavoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour, quantity => new ReactiveEnergy((quantity.Value) * 1e6d, ReactiveEnergyUnit.VoltampereReactiveHour)); } /// @@ -650,11 +657,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ReactiveEnergy to another ReactiveEnergy with the unit representation . /// + /// The unit to convert to. /// A ReactiveEnergy with the specified unit. public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) { - var convertedValue = GetValueAs(unit); - return new ReactiveEnergy(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ReactiveEnergy to another ReactiveEnergy using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ReactiveEnergy with the specified unit. + public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ReactiveEnergy), Unit, typeof(ReactiveEnergy), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ReactiveEnergy)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -663,7 +701,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ReactiveEnergyUnit unitAsReactiveEnergyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactiveEnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsReactiveEnergyUnit); + return ToUnit(unitAsReactiveEnergyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ReactiveEnergyUnit unitAsReactiveEnergyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactiveEnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsReactiveEnergyUnit, unitConverter); } /// @@ -688,51 +735,15 @@ public ReactiveEnergy ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ReactiveEnergyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (_value) * 1e3d; - case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (_value) * 1e6d; - case ReactiveEnergyUnit.VoltampereReactiveHour: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ReactiveEnergyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ReactiveEnergy ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ReactiveEnergy(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ReactiveEnergyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (baseUnitValue) / 1e3d; - case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (baseUnitValue) / 1e6d; - case ReactiveEnergyUnit.VoltampereReactiveHour: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs index b9b52b6ea6..2bcb0c60a8 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs @@ -68,6 +68,8 @@ static ReactivePower() new UnitInfo(ReactivePowerUnit.VoltampereReactive, "VoltamperesReactive", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ReactivePower); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public ReactivePower(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -213,17 +220,17 @@ public ReactivePower(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ReactivePowerUnit - unitConverter.SetConversionFunction(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.GigavoltampereReactive, quantity => quantity.ToUnit(ReactivePowerUnit.GigavoltampereReactive)); - unitConverter.SetConversionFunction(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.KilovoltampereReactive, quantity => quantity.ToUnit(ReactivePowerUnit.KilovoltampereReactive)); - unitConverter.SetConversionFunction(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.MegavoltampereReactive, quantity => quantity.ToUnit(ReactivePowerUnit.MegavoltampereReactive)); + unitConverter.SetConversionFunction(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.GigavoltampereReactive, quantity => new ReactivePower((quantity.Value) / 1e9d, ReactivePowerUnit.GigavoltampereReactive)); + unitConverter.SetConversionFunction(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.KilovoltampereReactive, quantity => new ReactivePower((quantity.Value) / 1e3d, ReactivePowerUnit.KilovoltampereReactive)); + unitConverter.SetConversionFunction(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.MegavoltampereReactive, quantity => new ReactivePower((quantity.Value) / 1e6d, ReactivePowerUnit.MegavoltampereReactive)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => quantity); // Register in unit converter: ReactivePowerUnit -> BaseUnit - unitConverter.SetConversionFunction(ReactivePowerUnit.GigavoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReactivePowerUnit.KilovoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReactivePowerUnit.MegavoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ReactivePowerUnit.GigavoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => new ReactivePower((quantity.Value) * 1e9d, ReactivePowerUnit.VoltampereReactive)); + unitConverter.SetConversionFunction(ReactivePowerUnit.KilovoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => new ReactivePower((quantity.Value) * 1e3d, ReactivePowerUnit.VoltampereReactive)); + unitConverter.SetConversionFunction(ReactivePowerUnit.MegavoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => new ReactivePower((quantity.Value) * 1e6d, ReactivePowerUnit.VoltampereReactive)); } /// @@ -667,11 +674,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ReactivePower to another ReactivePower with the unit representation . /// + /// The unit to convert to. /// A ReactivePower with the specified unit. public ReactivePower ToUnit(ReactivePowerUnit unit) { - var convertedValue = GetValueAs(unit); - return new ReactivePower(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ReactivePower to another ReactivePower using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ReactivePower with the specified unit. + public ReactivePower ToUnit(ReactivePowerUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ReactivePower), Unit, typeof(ReactivePower), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ReactivePower)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -680,7 +718,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ReactivePowerUnit unitAsReactivePowerUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactivePowerUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsReactivePowerUnit); + return ToUnit(unitAsReactivePowerUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ReactivePowerUnit unitAsReactivePowerUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactivePowerUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsReactivePowerUnit, unitConverter); } /// @@ -705,53 +752,15 @@ public ReactivePower ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ReactivePowerUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ReactivePowerUnit.GigavoltampereReactive: return (_value) * 1e9d; - case ReactivePowerUnit.KilovoltampereReactive: return (_value) * 1e3d; - case ReactivePowerUnit.MegavoltampereReactive: return (_value) * 1e6d; - case ReactivePowerUnit.VoltampereReactive: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ReactivePowerUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ReactivePower ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ReactivePower(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ReactivePowerUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ReactivePowerUnit.GigavoltampereReactive: return (baseUnitValue) / 1e9d; - case ReactivePowerUnit.KilovoltampereReactive: return (baseUnitValue) / 1e3d; - case ReactivePowerUnit.MegavoltampereReactive: return (baseUnitValue) / 1e6d; - case ReactivePowerUnit.VoltampereReactive: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs index ee5dbc1591..09cb2b475d 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs @@ -78,6 +78,8 @@ static ReciprocalArea() new UnitInfo(ReciprocalAreaUnit.InverseUsSurveySquareFoot, "InverseUsSurveySquareFeet", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ReciprocalArea); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -116,6 +118,11 @@ public ReciprocalArea(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -258,31 +265,31 @@ public ReciprocalArea(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ReciprocalAreaUnit - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareCentimeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareCentimeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareDecimeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareDecimeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareFoot, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareFoot)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareInch, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareInch)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareKilometer, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareKilometer)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMicrometer, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMicrometer)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMile, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMile)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMillimeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMillimeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareYard, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareYard)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseUsSurveySquareFoot, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseUsSurveySquareFoot)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareCentimeter, quantity => new ReciprocalArea(quantity.Value*1e-4, ReciprocalAreaUnit.InverseSquareCentimeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareDecimeter, quantity => new ReciprocalArea(quantity.Value*1e-2, ReciprocalAreaUnit.InverseSquareDecimeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareFoot, quantity => new ReciprocalArea(quantity.Value*0.092903, ReciprocalAreaUnit.InverseSquareFoot)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareInch, quantity => new ReciprocalArea(quantity.Value*0.00064516, ReciprocalAreaUnit.InverseSquareInch)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareKilometer, quantity => new ReciprocalArea(quantity.Value*1e6, ReciprocalAreaUnit.InverseSquareKilometer)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMicrometer, quantity => new ReciprocalArea(quantity.Value*1e-12, ReciprocalAreaUnit.InverseSquareMicrometer)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMile, quantity => new ReciprocalArea(quantity.Value*2.59e6, ReciprocalAreaUnit.InverseSquareMile)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMillimeter, quantity => new ReciprocalArea(quantity.Value*1e-6, ReciprocalAreaUnit.InverseSquareMillimeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareYard, quantity => new ReciprocalArea(quantity.Value*0.836127, ReciprocalAreaUnit.InverseSquareYard)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseUsSurveySquareFoot, quantity => new ReciprocalArea(quantity.Value*0.09290341161, ReciprocalAreaUnit.InverseUsSurveySquareFoot)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity); // Register in unit converter: ReciprocalAreaUnit -> BaseUnit - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareCentimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareDecimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareFoot, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareInch, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareKilometer, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMicrometer, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMile, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMillimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareYard, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseUsSurveySquareFoot, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareCentimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/1e-4, ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareDecimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/1e-2, ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareFoot, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/0.092903, ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareInch, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/0.00064516, ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareKilometer, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/1e6, ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMicrometer, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/1e-12, ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMile, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/2.59e6, ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMillimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/1e-6, ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareYard, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/0.836127, ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseUsSurveySquareFoot, ReciprocalAreaUnit.InverseSquareMeter, quantity => new ReciprocalArea(quantity.Value/0.09290341161, ReciprocalAreaUnit.InverseSquareMeter)); } /// @@ -789,11 +796,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ReciprocalArea to another ReciprocalArea with the unit representation . /// + /// The unit to convert to. /// A ReciprocalArea with the specified unit. public ReciprocalArea ToUnit(ReciprocalAreaUnit unit) { - var convertedValue = GetValueAs(unit); - return new ReciprocalArea(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ReciprocalArea to another ReciprocalArea using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ReciprocalArea with the specified unit. + public ReciprocalArea ToUnit(ReciprocalAreaUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ReciprocalArea), Unit, typeof(ReciprocalArea), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ReciprocalArea)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -802,7 +840,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ReciprocalAreaUnit unitAsReciprocalAreaUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalAreaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsReciprocalAreaUnit); + return ToUnit(unitAsReciprocalAreaUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ReciprocalAreaUnit unitAsReciprocalAreaUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalAreaUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsReciprocalAreaUnit, unitConverter); } /// @@ -827,67 +874,15 @@ public ReciprocalArea ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ReciprocalAreaUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ReciprocalAreaUnit.InverseSquareCentimeter: return _value/1e-4; - case ReciprocalAreaUnit.InverseSquareDecimeter: return _value/1e-2; - case ReciprocalAreaUnit.InverseSquareFoot: return _value/0.092903; - case ReciprocalAreaUnit.InverseSquareInch: return _value/0.00064516; - case ReciprocalAreaUnit.InverseSquareKilometer: return _value/1e6; - case ReciprocalAreaUnit.InverseSquareMeter: return _value; - case ReciprocalAreaUnit.InverseSquareMicrometer: return _value/1e-12; - case ReciprocalAreaUnit.InverseSquareMile: return _value/2.59e6; - case ReciprocalAreaUnit.InverseSquareMillimeter: return _value/1e-6; - case ReciprocalAreaUnit.InverseSquareYard: return _value/0.836127; - case ReciprocalAreaUnit.InverseUsSurveySquareFoot: return _value/0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ReciprocalAreaUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ReciprocalArea ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ReciprocalArea(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ReciprocalAreaUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ReciprocalAreaUnit.InverseSquareCentimeter: return baseUnitValue*1e-4; - case ReciprocalAreaUnit.InverseSquareDecimeter: return baseUnitValue*1e-2; - case ReciprocalAreaUnit.InverseSquareFoot: return baseUnitValue*0.092903; - case ReciprocalAreaUnit.InverseSquareInch: return baseUnitValue*0.00064516; - case ReciprocalAreaUnit.InverseSquareKilometer: return baseUnitValue*1e6; - case ReciprocalAreaUnit.InverseSquareMeter: return baseUnitValue; - case ReciprocalAreaUnit.InverseSquareMicrometer: return baseUnitValue*1e-12; - case ReciprocalAreaUnit.InverseSquareMile: return baseUnitValue*2.59e6; - case ReciprocalAreaUnit.InverseSquareMillimeter: return baseUnitValue*1e-6; - case ReciprocalAreaUnit.InverseSquareYard: return baseUnitValue*0.836127; - case ReciprocalAreaUnit.InverseUsSurveySquareFoot: return baseUnitValue*0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs index 2eecd855e4..2d5290337b 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs @@ -77,6 +77,8 @@ static ReciprocalLength() new UnitInfo(ReciprocalLengthUnit.InverseYard, "InverseYards", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ReciprocalLength); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -115,6 +117,11 @@ public ReciprocalLength(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -252,29 +259,29 @@ public ReciprocalLength(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ReciprocalLengthUnit - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseCentimeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseCentimeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseFoot, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseFoot)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseInch, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseInch)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMicroinch, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMicroinch)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMil, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMil)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMile, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMile)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMillimeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMillimeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseUsSurveyFoot, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseUsSurveyFoot)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseYard, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseYard)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseCentimeter, quantity => new ReciprocalLength(quantity.Value/1e2, ReciprocalLengthUnit.InverseCentimeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseFoot, quantity => new ReciprocalLength(quantity.Value*0.3048, ReciprocalLengthUnit.InverseFoot)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseInch, quantity => new ReciprocalLength(quantity.Value*2.54e-2, ReciprocalLengthUnit.InverseInch)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMicroinch, quantity => new ReciprocalLength(quantity.Value*2.54e-8, ReciprocalLengthUnit.InverseMicroinch)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMil, quantity => new ReciprocalLength(quantity.Value*2.54e-5, ReciprocalLengthUnit.InverseMil)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMile, quantity => new ReciprocalLength(quantity.Value*1609.34, ReciprocalLengthUnit.InverseMile)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMillimeter, quantity => new ReciprocalLength(quantity.Value/1e3, ReciprocalLengthUnit.InverseMillimeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseUsSurveyFoot, quantity => new ReciprocalLength(quantity.Value*1200/3937, ReciprocalLengthUnit.InverseUsSurveyFoot)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseYard, quantity => new ReciprocalLength(quantity.Value*0.9144, ReciprocalLengthUnit.InverseYard)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMeter, quantity => quantity); // Register in unit converter: ReciprocalLengthUnit -> BaseUnit - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseCentimeter, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseFoot, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseInch, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMicroinch, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMil, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMile, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMillimeter, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseUsSurveyFoot, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseYard, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseCentimeter, ReciprocalLengthUnit.InverseMeter, quantity => new ReciprocalLength(quantity.Value*1e2, ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseFoot, ReciprocalLengthUnit.InverseMeter, quantity => new ReciprocalLength(quantity.Value/0.3048, ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseInch, ReciprocalLengthUnit.InverseMeter, quantity => new ReciprocalLength(quantity.Value/2.54e-2, ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMicroinch, ReciprocalLengthUnit.InverseMeter, quantity => new ReciprocalLength(quantity.Value/2.54e-8, ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMil, ReciprocalLengthUnit.InverseMeter, quantity => new ReciprocalLength(quantity.Value/2.54e-5, ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMile, ReciprocalLengthUnit.InverseMeter, quantity => new ReciprocalLength(quantity.Value/1609.34, ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMillimeter, ReciprocalLengthUnit.InverseMeter, quantity => new ReciprocalLength(quantity.Value*1e3, ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseUsSurveyFoot, ReciprocalLengthUnit.InverseMeter, quantity => new ReciprocalLength(quantity.Value*3937/1200, ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseYard, ReciprocalLengthUnit.InverseMeter, quantity => new ReciprocalLength(quantity.Value/0.9144, ReciprocalLengthUnit.InverseMeter)); } /// @@ -772,11 +779,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ReciprocalLength to another ReciprocalLength with the unit representation . /// + /// The unit to convert to. /// A ReciprocalLength with the specified unit. public ReciprocalLength ToUnit(ReciprocalLengthUnit unit) { - var convertedValue = GetValueAs(unit); - return new ReciprocalLength(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ReciprocalLength to another ReciprocalLength using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ReciprocalLength with the specified unit. + public ReciprocalLength ToUnit(ReciprocalLengthUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ReciprocalLength), Unit, typeof(ReciprocalLength), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ReciprocalLength)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -785,7 +823,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ReciprocalLengthUnit unitAsReciprocalLengthUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsReciprocalLengthUnit); + return ToUnit(unitAsReciprocalLengthUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ReciprocalLengthUnit unitAsReciprocalLengthUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsReciprocalLengthUnit, unitConverter); } /// @@ -810,65 +857,15 @@ public ReciprocalLength ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ReciprocalLengthUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ReciprocalLengthUnit.InverseCentimeter: return _value*1e2; - case ReciprocalLengthUnit.InverseFoot: return _value/0.3048; - case ReciprocalLengthUnit.InverseInch: return _value/2.54e-2; - case ReciprocalLengthUnit.InverseMeter: return _value; - case ReciprocalLengthUnit.InverseMicroinch: return _value/2.54e-8; - case ReciprocalLengthUnit.InverseMil: return _value/2.54e-5; - case ReciprocalLengthUnit.InverseMile: return _value/1609.34; - case ReciprocalLengthUnit.InverseMillimeter: return _value*1e3; - case ReciprocalLengthUnit.InverseUsSurveyFoot: return _value*3937/1200; - case ReciprocalLengthUnit.InverseYard: return _value/0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ReciprocalLengthUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ReciprocalLength ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ReciprocalLength(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ReciprocalLengthUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ReciprocalLengthUnit.InverseCentimeter: return baseUnitValue/1e2; - case ReciprocalLengthUnit.InverseFoot: return baseUnitValue*0.3048; - case ReciprocalLengthUnit.InverseInch: return baseUnitValue*2.54e-2; - case ReciprocalLengthUnit.InverseMeter: return baseUnitValue; - case ReciprocalLengthUnit.InverseMicroinch: return baseUnitValue*2.54e-8; - case ReciprocalLengthUnit.InverseMil: return baseUnitValue*2.54e-5; - case ReciprocalLengthUnit.InverseMile: return baseUnitValue*1609.34; - case ReciprocalLengthUnit.InverseMillimeter: return baseUnitValue/1e3; - case ReciprocalLengthUnit.InverseUsSurveyFoot: return baseUnitValue*1200/3937; - case ReciprocalLengthUnit.InverseYard: return baseUnitValue*0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs index 362db8f404..cac5aa4717 100644 --- a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs @@ -65,6 +65,8 @@ static RelativeHumidity() new UnitInfo(RelativeHumidityUnit.Percent, "Percent", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.RelativeHumidity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -103,6 +105,11 @@ public RelativeHumidity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -616,11 +623,42 @@ double IQuantity.As(Enum unit) /// /// Converts this RelativeHumidity to another RelativeHumidity with the unit representation . /// + /// The unit to convert to. /// A RelativeHumidity with the specified unit. public RelativeHumidity ToUnit(RelativeHumidityUnit unit) { - var convertedValue = GetValueAs(unit); - return new RelativeHumidity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this RelativeHumidity to another RelativeHumidity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A RelativeHumidity with the specified unit. + public RelativeHumidity ToUnit(RelativeHumidityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(RelativeHumidity), Unit, typeof(RelativeHumidity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (RelativeHumidity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -629,7 +667,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is RelativeHumidityUnit unitAsRelativeHumidityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RelativeHumidityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRelativeHumidityUnit); + return ToUnit(unitAsRelativeHumidityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is RelativeHumidityUnit unitAsRelativeHumidityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RelativeHumidityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsRelativeHumidityUnit, unitConverter); } /// @@ -654,47 +701,15 @@ public RelativeHumidity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(RelativeHumidityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case RelativeHumidityUnit.Percent: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(RelativeHumidityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal RelativeHumidity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new RelativeHumidity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(RelativeHumidityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case RelativeHumidityUnit.Percent: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs index 4d8514d3ec..9f6fcecc94 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs @@ -68,6 +68,8 @@ static RotationalAcceleration() new UnitInfo(RotationalAccelerationUnit.RevolutionPerSecondSquared, "RevolutionsPerSecondSquared", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.RotationalAcceleration); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -213,17 +220,17 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> RotationalAccelerationUnit - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.DegreePerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.DegreePerSecondSquared)); - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerMinutePerSecond, quantity => quantity.ToUnit(RotationalAccelerationUnit.RevolutionPerMinutePerSecond)); - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.RevolutionPerSecondSquared)); + unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.DegreePerSecondSquared, quantity => new RotationalAcceleration((180/Math.PI)*quantity.Value, RotationalAccelerationUnit.DegreePerSecondSquared)); + unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerMinutePerSecond, quantity => new RotationalAcceleration((60/(2*Math.PI))*quantity.Value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond)); + unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerSecondSquared, quantity => new RotationalAcceleration((1/(2*Math.PI))*quantity.Value, RotationalAccelerationUnit.RevolutionPerSecondSquared)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity); // Register in unit converter: RotationalAccelerationUnit -> BaseUnit - unitConverter.SetConversionFunction(RotationalAccelerationUnit.DegreePerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RevolutionPerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(RotationalAccelerationUnit.DegreePerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => new RotationalAcceleration((Math.PI/180)*quantity.Value, RotationalAccelerationUnit.RadianPerSecondSquared)); + unitConverter.SetConversionFunction(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => new RotationalAcceleration(((2*Math.PI)/60)*quantity.Value, RotationalAccelerationUnit.RadianPerSecondSquared)); + unitConverter.SetConversionFunction(RotationalAccelerationUnit.RevolutionPerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => new RotationalAcceleration((2*Math.PI)*quantity.Value, RotationalAccelerationUnit.RadianPerSecondSquared)); } /// @@ -667,11 +674,42 @@ double IQuantity.As(Enum unit) /// /// Converts this RotationalAcceleration to another RotationalAcceleration with the unit representation . /// + /// The unit to convert to. /// A RotationalAcceleration with the specified unit. public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) { - var convertedValue = GetValueAs(unit); - return new RotationalAcceleration(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this RotationalAcceleration to another RotationalAcceleration using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A RotationalAcceleration with the specified unit. + public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(RotationalAcceleration), Unit, typeof(RotationalAcceleration), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (RotationalAcceleration)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -680,7 +718,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is RotationalAccelerationUnit unitAsRotationalAccelerationUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalAccelerationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRotationalAccelerationUnit); + return ToUnit(unitAsRotationalAccelerationUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is RotationalAccelerationUnit unitAsRotationalAccelerationUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalAccelerationUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsRotationalAccelerationUnit, unitConverter); } /// @@ -705,53 +752,15 @@ public RotationalAcceleration ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(RotationalAccelerationUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: return (Math.PI/180)*_value; - case RotationalAccelerationUnit.RadianPerSecondSquared: return _value; - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return ((2*Math.PI)/60)*_value; - case RotationalAccelerationUnit.RevolutionPerSecondSquared: return (2*Math.PI)*_value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(RotationalAccelerationUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal RotationalAcceleration ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new RotationalAcceleration(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(RotationalAccelerationUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: return (180/Math.PI)*baseUnitValue; - case RotationalAccelerationUnit.RadianPerSecondSquared: return baseUnitValue; - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return (60/(2*Math.PI))*baseUnitValue; - case RotationalAccelerationUnit.RevolutionPerSecondSquared: return (1/(2*Math.PI))*baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs index 467b2d63af..ee44a12cc9 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs @@ -77,6 +77,8 @@ static RotationalSpeed() new UnitInfo(RotationalSpeedUnit.RevolutionPerSecond, "RevolutionsPerSecond", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.RotationalSpeed); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -115,6 +117,11 @@ public RotationalSpeed(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -267,35 +274,35 @@ public RotationalSpeed(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> RotationalSpeedUnit - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.CentiradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.CentiradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DeciradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.DeciradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerMinute, quantity => quantity.ToUnit(RotationalSpeedUnit.DegreePerMinute)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.DegreePerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicrodegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MicrodegreePerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicroradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MicroradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MillidegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MillidegreePerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MilliradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MilliradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanodegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.NanodegreePerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanoradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.NanoradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerMinute, quantity => quantity.ToUnit(RotationalSpeedUnit.RevolutionPerMinute)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RevolutionPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.CentiradianPerSecond, quantity => new RotationalSpeed((quantity.Value) / 1e-2d, RotationalSpeedUnit.CentiradianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DeciradianPerSecond, quantity => new RotationalSpeed((quantity.Value) / 1e-1d, RotationalSpeedUnit.DeciradianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerMinute, quantity => new RotationalSpeed((180*60/Math.PI)*quantity.Value, RotationalSpeedUnit.DegreePerMinute)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerSecond, quantity => new RotationalSpeed((180/Math.PI)*quantity.Value, RotationalSpeedUnit.DegreePerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicrodegreePerSecond, quantity => new RotationalSpeed(((180/Math.PI)*quantity.Value) / 1e-6d, RotationalSpeedUnit.MicrodegreePerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicroradianPerSecond, quantity => new RotationalSpeed((quantity.Value) / 1e-6d, RotationalSpeedUnit.MicroradianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MillidegreePerSecond, quantity => new RotationalSpeed(((180/Math.PI)*quantity.Value) / 1e-3d, RotationalSpeedUnit.MillidegreePerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MilliradianPerSecond, quantity => new RotationalSpeed((quantity.Value) / 1e-3d, RotationalSpeedUnit.MilliradianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanodegreePerSecond, quantity => new RotationalSpeed(((180/Math.PI)*quantity.Value) / 1e-9d, RotationalSpeedUnit.NanodegreePerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanoradianPerSecond, quantity => new RotationalSpeed((quantity.Value) / 1e-9d, RotationalSpeedUnit.NanoradianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerMinute, quantity => new RotationalSpeed((quantity.Value/6.2831853072)*60, RotationalSpeedUnit.RevolutionPerMinute)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerSecond, quantity => new RotationalSpeed(quantity.Value/6.2831853072, RotationalSpeedUnit.RevolutionPerSecond)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity); // Register in unit converter: RotationalSpeedUnit -> BaseUnit - unitConverter.SetConversionFunction(RotationalSpeedUnit.CentiradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.DeciradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.DegreePerMinute, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.DegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.MicrodegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.MicroradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.MillidegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.MilliradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.NanodegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.NanoradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RevolutionPerMinute, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RevolutionPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(RotationalSpeedUnit.CentiradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed((quantity.Value) * 1e-2d, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.DeciradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed((quantity.Value) * 1e-1d, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.DegreePerMinute, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed((Math.PI/(180*60))*quantity.Value, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.DegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed((Math.PI/180)*quantity.Value, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.MicrodegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed(((Math.PI/180)*quantity.Value) * 1e-6d, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.MicroradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed((quantity.Value) * 1e-6d, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.MillidegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed(((Math.PI/180)*quantity.Value) * 1e-3d, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.MilliradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed((quantity.Value) * 1e-3d, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.NanodegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed(((Math.PI/180)*quantity.Value) * 1e-9d, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.NanoradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed((quantity.Value) * 1e-9d, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RevolutionPerMinute, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed((quantity.Value*6.2831853072)/60, RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction(RotationalSpeedUnit.RevolutionPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => new RotationalSpeed(quantity.Value*6.2831853072, RotationalSpeedUnit.RadianPerSecond)); } /// @@ -820,11 +827,42 @@ double IQuantity.As(Enum unit) /// /// Converts this RotationalSpeed to another RotationalSpeed with the unit representation . /// + /// The unit to convert to. /// A RotationalSpeed with the specified unit. public RotationalSpeed ToUnit(RotationalSpeedUnit unit) { - var convertedValue = GetValueAs(unit); - return new RotationalSpeed(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this RotationalSpeed to another RotationalSpeed using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A RotationalSpeed with the specified unit. + public RotationalSpeed ToUnit(RotationalSpeedUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(RotationalSpeed), Unit, typeof(RotationalSpeed), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (RotationalSpeed)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -833,7 +871,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is RotationalSpeedUnit unitAsRotationalSpeedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalSpeedUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRotationalSpeedUnit); + return ToUnit(unitAsRotationalSpeedUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is RotationalSpeedUnit unitAsRotationalSpeedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalSpeedUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsRotationalSpeedUnit, unitConverter); } /// @@ -858,71 +905,15 @@ public RotationalSpeed ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(RotationalSpeedUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case RotationalSpeedUnit.CentiradianPerSecond: return (_value) * 1e-2d; - case RotationalSpeedUnit.DeciradianPerSecond: return (_value) * 1e-1d; - case RotationalSpeedUnit.DegreePerMinute: return (Math.PI/(180*60))*_value; - case RotationalSpeedUnit.DegreePerSecond: return (Math.PI/180)*_value; - case RotationalSpeedUnit.MicrodegreePerSecond: return ((Math.PI/180)*_value) * 1e-6d; - case RotationalSpeedUnit.MicroradianPerSecond: return (_value) * 1e-6d; - case RotationalSpeedUnit.MillidegreePerSecond: return ((Math.PI/180)*_value) * 1e-3d; - case RotationalSpeedUnit.MilliradianPerSecond: return (_value) * 1e-3d; - case RotationalSpeedUnit.NanodegreePerSecond: return ((Math.PI/180)*_value) * 1e-9d; - case RotationalSpeedUnit.NanoradianPerSecond: return (_value) * 1e-9d; - case RotationalSpeedUnit.RadianPerSecond: return _value; - case RotationalSpeedUnit.RevolutionPerMinute: return (_value*6.2831853072)/60; - case RotationalSpeedUnit.RevolutionPerSecond: return _value*6.2831853072; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(RotationalSpeedUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal RotationalSpeed ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new RotationalSpeed(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(RotationalSpeedUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case RotationalSpeedUnit.CentiradianPerSecond: return (baseUnitValue) / 1e-2d; - case RotationalSpeedUnit.DeciradianPerSecond: return (baseUnitValue) / 1e-1d; - case RotationalSpeedUnit.DegreePerMinute: return (180*60/Math.PI)*baseUnitValue; - case RotationalSpeedUnit.DegreePerSecond: return (180/Math.PI)*baseUnitValue; - case RotationalSpeedUnit.MicrodegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-6d; - case RotationalSpeedUnit.MicroradianPerSecond: return (baseUnitValue) / 1e-6d; - case RotationalSpeedUnit.MillidegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-3d; - case RotationalSpeedUnit.MilliradianPerSecond: return (baseUnitValue) / 1e-3d; - case RotationalSpeedUnit.NanodegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-9d; - case RotationalSpeedUnit.NanoradianPerSecond: return (baseUnitValue) / 1e-9d; - case RotationalSpeedUnit.RadianPerSecond: return baseUnitValue; - case RotationalSpeedUnit.RevolutionPerMinute: return (baseUnitValue/6.2831853072)*60; - case RotationalSpeedUnit.RevolutionPerSecond: return baseUnitValue/6.2831853072; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs index f97f7b2807..b9e10d468f 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs @@ -97,6 +97,8 @@ static RotationalStiffness() new UnitInfo(RotationalStiffnessUnit.PoundForceFootPerDegrees, "PoundForceFeetPerDegrees", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.RotationalStiffness); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -135,6 +137,11 @@ public RotationalStiffness(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -387,75 +394,75 @@ public RotationalStiffness(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> RotationalStiffnessUnit - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.CentinewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecanewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecinewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilopoundForceFootPerDegrees, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilopoundForceFootPerDegrees)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MicronewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MillinewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NanonewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFeetPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.PoundForceFeetPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFootPerDegrees, quantity => quantity.ToUnit(RotationalStiffnessUnit.PoundForceFootPerDegrees)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMeterPerDegree, quantity => new RotationalStiffness((quantity.Value/(180/Math.PI)) / 1e-2d, RotationalStiffnessUnit.CentinewtonMeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, quantity => new RotationalStiffness((quantity.Value/180*Math.PI*1000) / 1e-2d, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, quantity => new RotationalStiffness((quantity.Value*1000) / 1e-2d, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMeterPerDegree, quantity => new RotationalStiffness((quantity.Value/(180/Math.PI)) / 1e1d, RotationalStiffnessUnit.DecanewtonMeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, quantity => new RotationalStiffness((quantity.Value/180*Math.PI*1000) / 1e1d, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, quantity => new RotationalStiffness((quantity.Value*1000) / 1e1d, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMeterPerDegree, quantity => new RotationalStiffness((quantity.Value/(180/Math.PI)) / 1e-1d, RotationalStiffnessUnit.DecinewtonMeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, quantity => new RotationalStiffness((quantity.Value/180*Math.PI*1000) / 1e-1d, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, quantity => new RotationalStiffness((quantity.Value*1000) / 1e-1d, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerDegree, quantity => new RotationalStiffness((quantity.Value/(180/Math.PI)) / 1e3d, RotationalStiffnessUnit.KilonewtonMeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value) / 1e3d, RotationalStiffnessUnit.KilonewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, quantity => new RotationalStiffness((quantity.Value/180*Math.PI*1000) / 1e3d, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, quantity => new RotationalStiffness((quantity.Value*1000) / 1e3d, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilopoundForceFootPerDegrees, quantity => new RotationalStiffness(quantity.Value/77682.6, RotationalStiffnessUnit.KilopoundForceFootPerDegrees)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerDegree, quantity => new RotationalStiffness((quantity.Value/(180/Math.PI)) / 1e6d, RotationalStiffnessUnit.MeganewtonMeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value) / 1e6d, RotationalStiffnessUnit.MeganewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, quantity => new RotationalStiffness((quantity.Value/180*Math.PI*1000) / 1e6d, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, quantity => new RotationalStiffness((quantity.Value*1000) / 1e6d, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMeterPerDegree, quantity => new RotationalStiffness((quantity.Value/(180/Math.PI)) / 1e-6d, RotationalStiffnessUnit.MicronewtonMeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, quantity => new RotationalStiffness((quantity.Value/180*Math.PI*1000) / 1e-6d, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, quantity => new RotationalStiffness((quantity.Value*1000) / 1e-6d, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMeterPerDegree, quantity => new RotationalStiffness((quantity.Value/(180/Math.PI)) / 1e-3d, RotationalStiffnessUnit.MillinewtonMeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, quantity => new RotationalStiffness((quantity.Value/180*Math.PI*1000) / 1e-3d, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, quantity => new RotationalStiffness((quantity.Value*1000) / 1e-3d, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMeterPerDegree, quantity => new RotationalStiffness((quantity.Value/(180/Math.PI)) / 1e-9d, RotationalStiffnessUnit.NanonewtonMeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, quantity => new RotationalStiffness((quantity.Value/180*Math.PI*1000) / 1e-9d, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, quantity => new RotationalStiffness((quantity.Value*1000) / 1e-9d, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerDegree, quantity => new RotationalStiffness(quantity.Value/(180/Math.PI), RotationalStiffnessUnit.NewtonMeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerDegree, quantity => new RotationalStiffness(quantity.Value/180*Math.PI*1000, RotationalStiffnessUnit.NewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerRadian, quantity => new RotationalStiffness(quantity.Value*1000, RotationalStiffnessUnit.NewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFeetPerRadian, quantity => new RotationalStiffness(quantity.Value/1.3558179483314, RotationalStiffnessUnit.PoundForceFeetPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFootPerDegrees, quantity => new RotationalStiffness(quantity.Value/77.6826, RotationalStiffnessUnit.PoundForceFootPerDegrees)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity); // Register in unit converter: RotationalStiffnessUnit -> BaseUnit - unitConverter.SetConversionFunction(RotationalStiffnessUnit.CentinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecanewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MicronewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MillinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NanonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.PoundForceFeetPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.PoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.CentinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*(180/Math.PI)) * 1e-2d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*180/Math.PI*0.001) * 1e-2d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*0.001) * 1e-2d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecanewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*(180/Math.PI)) * 1e1d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*180/Math.PI*0.001) * 1e1d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*0.001) * 1e1d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*(180/Math.PI)) * 1e-1d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*180/Math.PI*0.001) * 1e-1d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*0.001) * 1e-1d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*(180/Math.PI)) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*180/Math.PI*0.001) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*0.001) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness(quantity.Value*77682.6, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*(180/Math.PI)) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*180/Math.PI*0.001) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*0.001) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MicronewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*(180/Math.PI)) * 1e-6d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*180/Math.PI*0.001) * 1e-6d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*0.001) * 1e-6d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MillinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*(180/Math.PI)) * 1e-3d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*180/Math.PI*0.001) * 1e-3d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*0.001) * 1e-3d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NanonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*(180/Math.PI)) * 1e-9d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*180/Math.PI*0.001) * 1e-9d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness((quantity.Value*0.001) * 1e-9d, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness(quantity.Value*(180/Math.PI), RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness(quantity.Value*180/Math.PI*0.001, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness(quantity.Value*0.001, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.PoundForceFeetPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness(quantity.Value*1.3558179483314, RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction(RotationalStiffnessUnit.PoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => new RotationalStiffness(quantity.Value*77.6826, RotationalStiffnessUnit.NewtonMeterPerRadian)); } /// @@ -1160,11 +1167,42 @@ double IQuantity.As(Enum unit) /// /// Converts this RotationalStiffness to another RotationalStiffness with the unit representation . /// + /// The unit to convert to. /// A RotationalStiffness with the specified unit. public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) { - var convertedValue = GetValueAs(unit); - return new RotationalStiffness(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this RotationalStiffness to another RotationalStiffness using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A RotationalStiffness with the specified unit. + public RotationalStiffness ToUnit(RotationalStiffnessUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(RotationalStiffness), Unit, typeof(RotationalStiffness), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (RotationalStiffness)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1173,7 +1211,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is RotationalStiffnessUnit unitAsRotationalStiffnessUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRotationalStiffnessUnit); + return ToUnit(unitAsRotationalStiffnessUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is RotationalStiffnessUnit unitAsRotationalStiffnessUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsRotationalStiffnessUnit, unitConverter); } /// @@ -1198,111 +1245,15 @@ public RotationalStiffness ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(RotationalStiffnessUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case RotationalStiffnessUnit.CentinewtonMeterPerDegree: return (_value*(180/Math.PI)) * 1e-2d; - case RotationalStiffnessUnit.CentinewtonMillimeterPerDegree: return (_value*180/Math.PI*0.001) * 1e-2d; - case RotationalStiffnessUnit.CentinewtonMillimeterPerRadian: return (_value*0.001) * 1e-2d; - case RotationalStiffnessUnit.DecanewtonMeterPerDegree: return (_value*(180/Math.PI)) * 1e1d; - case RotationalStiffnessUnit.DecanewtonMillimeterPerDegree: return (_value*180/Math.PI*0.001) * 1e1d; - case RotationalStiffnessUnit.DecanewtonMillimeterPerRadian: return (_value*0.001) * 1e1d; - case RotationalStiffnessUnit.DecinewtonMeterPerDegree: return (_value*(180/Math.PI)) * 1e-1d; - case RotationalStiffnessUnit.DecinewtonMillimeterPerDegree: return (_value*180/Math.PI*0.001) * 1e-1d; - case RotationalStiffnessUnit.DecinewtonMillimeterPerRadian: return (_value*0.001) * 1e-1d; - case RotationalStiffnessUnit.KilonewtonMeterPerDegree: return (_value*(180/Math.PI)) * 1e3d; - case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (_value) * 1e3d; - case RotationalStiffnessUnit.KilonewtonMillimeterPerDegree: return (_value*180/Math.PI*0.001) * 1e3d; - case RotationalStiffnessUnit.KilonewtonMillimeterPerRadian: return (_value*0.001) * 1e3d; - case RotationalStiffnessUnit.KilopoundForceFootPerDegrees: return _value*77682.6; - case RotationalStiffnessUnit.MeganewtonMeterPerDegree: return (_value*(180/Math.PI)) * 1e6d; - case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (_value) * 1e6d; - case RotationalStiffnessUnit.MeganewtonMillimeterPerDegree: return (_value*180/Math.PI*0.001) * 1e6d; - case RotationalStiffnessUnit.MeganewtonMillimeterPerRadian: return (_value*0.001) * 1e6d; - case RotationalStiffnessUnit.MicronewtonMeterPerDegree: return (_value*(180/Math.PI)) * 1e-6d; - case RotationalStiffnessUnit.MicronewtonMillimeterPerDegree: return (_value*180/Math.PI*0.001) * 1e-6d; - case RotationalStiffnessUnit.MicronewtonMillimeterPerRadian: return (_value*0.001) * 1e-6d; - case RotationalStiffnessUnit.MillinewtonMeterPerDegree: return (_value*(180/Math.PI)) * 1e-3d; - case RotationalStiffnessUnit.MillinewtonMillimeterPerDegree: return (_value*180/Math.PI*0.001) * 1e-3d; - case RotationalStiffnessUnit.MillinewtonMillimeterPerRadian: return (_value*0.001) * 1e-3d; - case RotationalStiffnessUnit.NanonewtonMeterPerDegree: return (_value*(180/Math.PI)) * 1e-9d; - case RotationalStiffnessUnit.NanonewtonMillimeterPerDegree: return (_value*180/Math.PI*0.001) * 1e-9d; - case RotationalStiffnessUnit.NanonewtonMillimeterPerRadian: return (_value*0.001) * 1e-9d; - case RotationalStiffnessUnit.NewtonMeterPerDegree: return _value*(180/Math.PI); - case RotationalStiffnessUnit.NewtonMeterPerRadian: return _value; - case RotationalStiffnessUnit.NewtonMillimeterPerDegree: return _value*180/Math.PI*0.001; - case RotationalStiffnessUnit.NewtonMillimeterPerRadian: return _value*0.001; - case RotationalStiffnessUnit.PoundForceFeetPerRadian: return _value*1.3558179483314; - case RotationalStiffnessUnit.PoundForceFootPerDegrees: return _value*77.6826; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(RotationalStiffnessUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal RotationalStiffness ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new RotationalStiffness(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(RotationalStiffnessUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case RotationalStiffnessUnit.CentinewtonMeterPerDegree: return (baseUnitValue/(180/Math.PI)) / 1e-2d; - case RotationalStiffnessUnit.CentinewtonMillimeterPerDegree: return (baseUnitValue/180*Math.PI*1000) / 1e-2d; - case RotationalStiffnessUnit.CentinewtonMillimeterPerRadian: return (baseUnitValue*1000) / 1e-2d; - case RotationalStiffnessUnit.DecanewtonMeterPerDegree: return (baseUnitValue/(180/Math.PI)) / 1e1d; - case RotationalStiffnessUnit.DecanewtonMillimeterPerDegree: return (baseUnitValue/180*Math.PI*1000) / 1e1d; - case RotationalStiffnessUnit.DecanewtonMillimeterPerRadian: return (baseUnitValue*1000) / 1e1d; - case RotationalStiffnessUnit.DecinewtonMeterPerDegree: return (baseUnitValue/(180/Math.PI)) / 1e-1d; - case RotationalStiffnessUnit.DecinewtonMillimeterPerDegree: return (baseUnitValue/180*Math.PI*1000) / 1e-1d; - case RotationalStiffnessUnit.DecinewtonMillimeterPerRadian: return (baseUnitValue*1000) / 1e-1d; - case RotationalStiffnessUnit.KilonewtonMeterPerDegree: return (baseUnitValue/(180/Math.PI)) / 1e3d; - case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (baseUnitValue) / 1e3d; - case RotationalStiffnessUnit.KilonewtonMillimeterPerDegree: return (baseUnitValue/180*Math.PI*1000) / 1e3d; - case RotationalStiffnessUnit.KilonewtonMillimeterPerRadian: return (baseUnitValue*1000) / 1e3d; - case RotationalStiffnessUnit.KilopoundForceFootPerDegrees: return baseUnitValue/77682.6; - case RotationalStiffnessUnit.MeganewtonMeterPerDegree: return (baseUnitValue/(180/Math.PI)) / 1e6d; - case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (baseUnitValue) / 1e6d; - case RotationalStiffnessUnit.MeganewtonMillimeterPerDegree: return (baseUnitValue/180*Math.PI*1000) / 1e6d; - case RotationalStiffnessUnit.MeganewtonMillimeterPerRadian: return (baseUnitValue*1000) / 1e6d; - case RotationalStiffnessUnit.MicronewtonMeterPerDegree: return (baseUnitValue/(180/Math.PI)) / 1e-6d; - case RotationalStiffnessUnit.MicronewtonMillimeterPerDegree: return (baseUnitValue/180*Math.PI*1000) / 1e-6d; - case RotationalStiffnessUnit.MicronewtonMillimeterPerRadian: return (baseUnitValue*1000) / 1e-6d; - case RotationalStiffnessUnit.MillinewtonMeterPerDegree: return (baseUnitValue/(180/Math.PI)) / 1e-3d; - case RotationalStiffnessUnit.MillinewtonMillimeterPerDegree: return (baseUnitValue/180*Math.PI*1000) / 1e-3d; - case RotationalStiffnessUnit.MillinewtonMillimeterPerRadian: return (baseUnitValue*1000) / 1e-3d; - case RotationalStiffnessUnit.NanonewtonMeterPerDegree: return (baseUnitValue/(180/Math.PI)) / 1e-9d; - case RotationalStiffnessUnit.NanonewtonMillimeterPerDegree: return (baseUnitValue/180*Math.PI*1000) / 1e-9d; - case RotationalStiffnessUnit.NanonewtonMillimeterPerRadian: return (baseUnitValue*1000) / 1e-9d; - case RotationalStiffnessUnit.NewtonMeterPerDegree: return baseUnitValue/(180/Math.PI); - case RotationalStiffnessUnit.NewtonMeterPerRadian: return baseUnitValue; - case RotationalStiffnessUnit.NewtonMillimeterPerDegree: return baseUnitValue/180*Math.PI*1000; - case RotationalStiffnessUnit.NewtonMillimeterPerRadian: return baseUnitValue*1000; - case RotationalStiffnessUnit.PoundForceFeetPerRadian: return baseUnitValue/1.3558179483314; - case RotationalStiffnessUnit.PoundForceFootPerDegrees: return baseUnitValue/77.6826; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs index f94a2530db..484b312dab 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs @@ -69,6 +69,8 @@ static RotationalStiffnessPerLength() new UnitInfo(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, "PoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.RotationalStiffnessPerLength); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -107,6 +109,11 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -219,19 +226,19 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> RotationalStiffnessPerLengthUnit - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter)); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot)); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter)); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot)); + unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, quantity => new RotationalStiffnessPerLength((quantity.Value) / 1e3d, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, quantity => new RotationalStiffnessPerLength(quantity.Value/254864.324570, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot)); + unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, quantity => new RotationalStiffnessPerLength((quantity.Value) / 1e6d, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, quantity => new RotationalStiffnessPerLength(quantity.Value/254.864324570, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity); // Register in unit converter: RotationalStiffnessPerLengthUnit -> BaseUnit - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => new RotationalStiffnessPerLength((quantity.Value) * 1e3d, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => new RotationalStiffnessPerLength(quantity.Value*254864.324570, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => new RotationalStiffnessPerLength((quantity.Value) * 1e6d, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => new RotationalStiffnessPerLength(quantity.Value*254.864324570, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); } /// @@ -684,11 +691,42 @@ double IQuantity.As(Enum unit) /// /// Converts this RotationalStiffnessPerLength to another RotationalStiffnessPerLength with the unit representation . /// + /// The unit to convert to. /// A RotationalStiffnessPerLength with the specified unit. public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) { - var convertedValue = GetValueAs(unit); - return new RotationalStiffnessPerLength(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this RotationalStiffnessPerLength to another RotationalStiffnessPerLength using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A RotationalStiffnessPerLength with the specified unit. + public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(RotationalStiffnessPerLength), Unit, typeof(RotationalStiffnessPerLength), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (RotationalStiffnessPerLength)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -697,7 +735,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is RotationalStiffnessPerLengthUnit unitAsRotationalStiffnessPerLengthUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessPerLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRotationalStiffnessPerLengthUnit); + return ToUnit(unitAsRotationalStiffnessPerLengthUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is RotationalStiffnessPerLengthUnit unitAsRotationalStiffnessPerLengthUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessPerLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsRotationalStiffnessPerLengthUnit, unitConverter); } /// @@ -722,55 +769,15 @@ public RotationalStiffnessPerLength ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(RotationalStiffnessPerLengthUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (_value) * 1e3d; - case RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot: return _value*254864.324570; - case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (_value) * 1e6d; - case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return _value; - case RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot: return _value*254.864324570; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(RotationalStiffnessPerLengthUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal RotationalStiffnessPerLength ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new RotationalStiffnessPerLength(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(RotationalStiffnessPerLengthUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e3d; - case RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot: return baseUnitValue/254864.324570; - case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e6d; - case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return baseUnitValue; - case RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot: return baseUnitValue/254.864324570; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs index efb6c11b22..22d5c68e1f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs @@ -65,6 +65,8 @@ static Scalar() new UnitInfo(ScalarUnit.Amount, "Amount", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Scalar); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -103,6 +105,11 @@ public Scalar(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -616,11 +623,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Scalar to another Scalar with the unit representation . /// + /// The unit to convert to. /// A Scalar with the specified unit. public Scalar ToUnit(ScalarUnit unit) { - var convertedValue = GetValueAs(unit); - return new Scalar(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Scalar to another Scalar using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Scalar with the specified unit. + public Scalar ToUnit(ScalarUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Scalar), Unit, typeof(Scalar), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Scalar)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -629,7 +667,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ScalarUnit unitAsScalarUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsScalarUnit); + return ToUnit(unitAsScalarUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ScalarUnit unitAsScalarUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsScalarUnit, unitConverter); } /// @@ -654,47 +701,15 @@ public Scalar ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ScalarUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ScalarUnit.Amount: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ScalarUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Scalar ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Scalar(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ScalarUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ScalarUnit.Amount: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs index 13e62cc473..5110cf3f1f 100644 --- a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs @@ -68,6 +68,8 @@ static SolidAngle() new UnitInfo(SolidAngleUnit.Steradian, "Steradians", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.SolidAngle); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public SolidAngle(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this SolidAngle to another SolidAngle with the unit representation . /// + /// The unit to convert to. /// A SolidAngle with the specified unit. public SolidAngle ToUnit(SolidAngleUnit unit) { - var convertedValue = GetValueAs(unit); - return new SolidAngle(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this SolidAngle to another SolidAngle using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A SolidAngle with the specified unit. + public SolidAngle ToUnit(SolidAngleUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(SolidAngle), Unit, typeof(SolidAngle), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (SolidAngle)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is SolidAngleUnit unitAsSolidAngleUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SolidAngleUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSolidAngleUnit); + return ToUnit(unitAsSolidAngleUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is SolidAngleUnit unitAsSolidAngleUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SolidAngleUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsSolidAngleUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public SolidAngle ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(SolidAngleUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case SolidAngleUnit.Steradian: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(SolidAngleUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal SolidAngle ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new SolidAngle(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(SolidAngleUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case SolidAngleUnit.Steradian: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs index 199c956a94..0c03a88f55 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs @@ -92,6 +92,8 @@ static SpecificEnergy() new UnitInfo(SpecificEnergyUnit.WattHourPerKilogram, "WattHoursPerKilogram", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.SpecificEnergy); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -130,6 +132,11 @@ public SpecificEnergy(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -342,59 +349,59 @@ public SpecificEnergy(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> SpecificEnergyUnit - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.BtuPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.BtuPerPound)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.CaloriePerGram, quantity => quantity.ToUnit(SpecificEnergyUnit.CaloriePerGram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattHourPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilocaloriePerGram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilocaloriePerGram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilojoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilojoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattHourPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegajoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.MegajoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattHourPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.TerawattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.TerawattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.TerawattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.WattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.WattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.WattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.WattHourPerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.BtuPerPound, quantity => new SpecificEnergy(quantity.Value/2326.000075362, SpecificEnergyUnit.BtuPerPound)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.CaloriePerGram, quantity => new SpecificEnergy(quantity.Value/4.184e3, SpecificEnergyUnit.CaloriePerGram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerKilogram, quantity => new SpecificEnergy((quantity.Value/(24*3.6e3)) / 1e9d, SpecificEnergyUnit.GigawattDayPerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerShortTon, quantity => new SpecificEnergy((quantity.Value/((24*3.6e3)/9.0718474e2)) / 1e9d, SpecificEnergyUnit.GigawattDayPerShortTon)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerTonne, quantity => new SpecificEnergy((quantity.Value/((24*3.6e3)/1e3)) / 1e9d, SpecificEnergyUnit.GigawattDayPerTonne)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerKilogram, quantity => new SpecificEnergy((quantity.Value/3.6e3) / 1e9d, SpecificEnergyUnit.GigawattHourPerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilocaloriePerGram, quantity => new SpecificEnergy((quantity.Value/4.184e3) / 1e3d, SpecificEnergyUnit.KilocaloriePerGram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilojoulePerKilogram, quantity => new SpecificEnergy((quantity.Value) / 1e3d, SpecificEnergyUnit.KilojoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerKilogram, quantity => new SpecificEnergy((quantity.Value/(24*3.6e3)) / 1e3d, SpecificEnergyUnit.KilowattDayPerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerShortTon, quantity => new SpecificEnergy((quantity.Value/((24*3.6e3)/9.0718474e2)) / 1e3d, SpecificEnergyUnit.KilowattDayPerShortTon)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerTonne, quantity => new SpecificEnergy((quantity.Value/((24*3.6e3)/1e3)) / 1e3d, SpecificEnergyUnit.KilowattDayPerTonne)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerKilogram, quantity => new SpecificEnergy((quantity.Value/3.6e3) / 1e3d, SpecificEnergyUnit.KilowattHourPerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegajoulePerKilogram, quantity => new SpecificEnergy((quantity.Value) / 1e6d, SpecificEnergyUnit.MegajoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerKilogram, quantity => new SpecificEnergy((quantity.Value/(24*3.6e3)) / 1e6d, SpecificEnergyUnit.MegawattDayPerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerShortTon, quantity => new SpecificEnergy((quantity.Value/((24*3.6e3)/9.0718474e2)) / 1e6d, SpecificEnergyUnit.MegawattDayPerShortTon)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerTonne, quantity => new SpecificEnergy((quantity.Value/((24*3.6e3)/1e3)) / 1e6d, SpecificEnergyUnit.MegawattDayPerTonne)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerKilogram, quantity => new SpecificEnergy((quantity.Value/3.6e3) / 1e6d, SpecificEnergyUnit.MegawattHourPerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerKilogram, quantity => new SpecificEnergy((quantity.Value/(24*3.6e3)) / 1e12d, SpecificEnergyUnit.TerawattDayPerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerShortTon, quantity => new SpecificEnergy((quantity.Value/((24*3.6e3)/9.0718474e2)) / 1e12d, SpecificEnergyUnit.TerawattDayPerShortTon)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerTonne, quantity => new SpecificEnergy((quantity.Value/((24*3.6e3)/1e3)) / 1e12d, SpecificEnergyUnit.TerawattDayPerTonne)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerKilogram, quantity => new SpecificEnergy(quantity.Value/(24*3.6e3), SpecificEnergyUnit.WattDayPerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerShortTon, quantity => new SpecificEnergy(quantity.Value/((24*3.6e3)/9.0718474e2), SpecificEnergyUnit.WattDayPerShortTon)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerTonne, quantity => new SpecificEnergy(quantity.Value/((24*3.6e3)/1e3), SpecificEnergyUnit.WattDayPerTonne)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerKilogram, quantity => new SpecificEnergy(quantity.Value/3.6e3, SpecificEnergyUnit.WattHourPerKilogram)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity); // Register in unit converter: SpecificEnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificEnergyUnit.BtuPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.CaloriePerGram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilocaloriePerGram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilojoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegajoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.TerawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.TerawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.TerawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.WattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.WattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.WattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEnergyUnit.WattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(SpecificEnergyUnit.BtuPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy(quantity.Value*2326.000075362, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.CaloriePerGram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy(quantity.Value*4.184e3, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*(24*3.6e3)) * 1e9d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*((24*3.6e3)/9.0718474e2)) * 1e9d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*((24*3.6e3)/1e3)) * 1e9d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*3.6e3) * 1e9d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.KilocaloriePerGram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*4.184e3) * 1e3d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.KilojoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value) * 1e3d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*(24*3.6e3)) * 1e3d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*((24*3.6e3)/9.0718474e2)) * 1e3d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*((24*3.6e3)/1e3)) * 1e3d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*3.6e3) * 1e3d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.MegajoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value) * 1e6d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*(24*3.6e3)) * 1e6d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*((24*3.6e3)/9.0718474e2)) * 1e6d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*((24*3.6e3)/1e3)) * 1e6d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*3.6e3) * 1e6d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.TerawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*(24*3.6e3)) * 1e12d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.TerawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*((24*3.6e3)/9.0718474e2)) * 1e12d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.TerawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy((quantity.Value*((24*3.6e3)/1e3)) * 1e12d, SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.WattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy(quantity.Value*(24*3.6e3), SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.WattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy(quantity.Value*((24*3.6e3)/9.0718474e2), SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.WattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy(quantity.Value*((24*3.6e3)/1e3), SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction(SpecificEnergyUnit.WattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => new SpecificEnergy(quantity.Value*3.6e3, SpecificEnergyUnit.JoulePerKilogram)); } /// @@ -1027,11 +1034,42 @@ double IQuantity.As(Enum unit) /// /// Converts this SpecificEnergy to another SpecificEnergy with the unit representation . /// + /// The unit to convert to. /// A SpecificEnergy with the specified unit. public SpecificEnergy ToUnit(SpecificEnergyUnit unit) { - var convertedValue = GetValueAs(unit); - return new SpecificEnergy(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this SpecificEnergy to another SpecificEnergy using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A SpecificEnergy with the specified unit. + public SpecificEnergy ToUnit(SpecificEnergyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(SpecificEnergy), Unit, typeof(SpecificEnergy), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (SpecificEnergy)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1040,7 +1078,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is SpecificEnergyUnit unitAsSpecificEnergyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificEnergyUnit); + return ToUnit(unitAsSpecificEnergyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is SpecificEnergyUnit unitAsSpecificEnergyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsSpecificEnergyUnit, unitConverter); } /// @@ -1065,95 +1112,15 @@ public SpecificEnergy ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(SpecificEnergyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case SpecificEnergyUnit.BtuPerPound: return _value*2326.000075362; - case SpecificEnergyUnit.CaloriePerGram: return _value*4.184e3; - case SpecificEnergyUnit.GigawattDayPerKilogram: return (_value*(24*3.6e3)) * 1e9d; - case SpecificEnergyUnit.GigawattDayPerShortTon: return (_value*((24*3.6e3)/9.0718474e2)) * 1e9d; - case SpecificEnergyUnit.GigawattDayPerTonne: return (_value*((24*3.6e3)/1e3)) * 1e9d; - case SpecificEnergyUnit.GigawattHourPerKilogram: return (_value*3.6e3) * 1e9d; - case SpecificEnergyUnit.JoulePerKilogram: return _value; - case SpecificEnergyUnit.KilocaloriePerGram: return (_value*4.184e3) * 1e3d; - case SpecificEnergyUnit.KilojoulePerKilogram: return (_value) * 1e3d; - case SpecificEnergyUnit.KilowattDayPerKilogram: return (_value*(24*3.6e3)) * 1e3d; - case SpecificEnergyUnit.KilowattDayPerShortTon: return (_value*((24*3.6e3)/9.0718474e2)) * 1e3d; - case SpecificEnergyUnit.KilowattDayPerTonne: return (_value*((24*3.6e3)/1e3)) * 1e3d; - case SpecificEnergyUnit.KilowattHourPerKilogram: return (_value*3.6e3) * 1e3d; - case SpecificEnergyUnit.MegajoulePerKilogram: return (_value) * 1e6d; - case SpecificEnergyUnit.MegawattDayPerKilogram: return (_value*(24*3.6e3)) * 1e6d; - case SpecificEnergyUnit.MegawattDayPerShortTon: return (_value*((24*3.6e3)/9.0718474e2)) * 1e6d; - case SpecificEnergyUnit.MegawattDayPerTonne: return (_value*((24*3.6e3)/1e3)) * 1e6d; - case SpecificEnergyUnit.MegawattHourPerKilogram: return (_value*3.6e3) * 1e6d; - case SpecificEnergyUnit.TerawattDayPerKilogram: return (_value*(24*3.6e3)) * 1e12d; - case SpecificEnergyUnit.TerawattDayPerShortTon: return (_value*((24*3.6e3)/9.0718474e2)) * 1e12d; - case SpecificEnergyUnit.TerawattDayPerTonne: return (_value*((24*3.6e3)/1e3)) * 1e12d; - case SpecificEnergyUnit.WattDayPerKilogram: return _value*(24*3.6e3); - case SpecificEnergyUnit.WattDayPerShortTon: return _value*((24*3.6e3)/9.0718474e2); - case SpecificEnergyUnit.WattDayPerTonne: return _value*((24*3.6e3)/1e3); - case SpecificEnergyUnit.WattHourPerKilogram: return _value*3.6e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(SpecificEnergyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal SpecificEnergy ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new SpecificEnergy(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(SpecificEnergyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case SpecificEnergyUnit.BtuPerPound: return baseUnitValue/2326.000075362; - case SpecificEnergyUnit.CaloriePerGram: return baseUnitValue/4.184e3; - case SpecificEnergyUnit.GigawattDayPerKilogram: return (baseUnitValue/(24*3.6e3)) / 1e9d; - case SpecificEnergyUnit.GigawattDayPerShortTon: return (baseUnitValue/((24*3.6e3)/9.0718474e2)) / 1e9d; - case SpecificEnergyUnit.GigawattDayPerTonne: return (baseUnitValue/((24*3.6e3)/1e3)) / 1e9d; - case SpecificEnergyUnit.GigawattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e9d; - case SpecificEnergyUnit.JoulePerKilogram: return baseUnitValue; - case SpecificEnergyUnit.KilocaloriePerGram: return (baseUnitValue/4.184e3) / 1e3d; - case SpecificEnergyUnit.KilojoulePerKilogram: return (baseUnitValue) / 1e3d; - case SpecificEnergyUnit.KilowattDayPerKilogram: return (baseUnitValue/(24*3.6e3)) / 1e3d; - case SpecificEnergyUnit.KilowattDayPerShortTon: return (baseUnitValue/((24*3.6e3)/9.0718474e2)) / 1e3d; - case SpecificEnergyUnit.KilowattDayPerTonne: return (baseUnitValue/((24*3.6e3)/1e3)) / 1e3d; - case SpecificEnergyUnit.KilowattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e3d; - case SpecificEnergyUnit.MegajoulePerKilogram: return (baseUnitValue) / 1e6d; - case SpecificEnergyUnit.MegawattDayPerKilogram: return (baseUnitValue/(24*3.6e3)) / 1e6d; - case SpecificEnergyUnit.MegawattDayPerShortTon: return (baseUnitValue/((24*3.6e3)/9.0718474e2)) / 1e6d; - case SpecificEnergyUnit.MegawattDayPerTonne: return (baseUnitValue/((24*3.6e3)/1e3)) / 1e6d; - case SpecificEnergyUnit.MegawattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e6d; - case SpecificEnergyUnit.TerawattDayPerKilogram: return (baseUnitValue/(24*3.6e3)) / 1e12d; - case SpecificEnergyUnit.TerawattDayPerShortTon: return (baseUnitValue/((24*3.6e3)/9.0718474e2)) / 1e12d; - case SpecificEnergyUnit.TerawattDayPerTonne: return (baseUnitValue/((24*3.6e3)/1e3)) / 1e12d; - case SpecificEnergyUnit.WattDayPerKilogram: return baseUnitValue/(24*3.6e3); - case SpecificEnergyUnit.WattDayPerShortTon: return baseUnitValue/((24*3.6e3)/9.0718474e2); - case SpecificEnergyUnit.WattDayPerTonne: return baseUnitValue/((24*3.6e3)/1e3); - case SpecificEnergyUnit.WattHourPerKilogram: return baseUnitValue/3.6e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs index 23261ac00a..fe401995fa 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs @@ -73,6 +73,8 @@ static SpecificEntropy() new UnitInfo(SpecificEntropyUnit.MegajoulePerKilogramKelvin, "MegajoulesPerKilogramKelvin", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.SpecificEntropy); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -111,6 +113,11 @@ public SpecificEntropy(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -243,27 +250,27 @@ public SpecificEntropy(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> SpecificEntropyUnit - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.BtuPerPoundFahrenheit, quantity => quantity.ToUnit(SpecificEntropyUnit.BtuPerPoundFahrenheit)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.CaloriePerGramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.CaloriePerGramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilocaloriePerGramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.KilocaloriePerGramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, quantity => quantity.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, quantity => quantity.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.BtuPerPoundFahrenheit, quantity => new SpecificEntropy(quantity.Value / 4.1868e3, SpecificEntropyUnit.BtuPerPoundFahrenheit)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.CaloriePerGramKelvin, quantity => new SpecificEntropy(quantity.Value/4.184e3, SpecificEntropyUnit.CaloriePerGramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, quantity => new SpecificEntropy(quantity.Value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilocaloriePerGramKelvin, quantity => new SpecificEntropy((quantity.Value/4.184e3) / 1e3d, SpecificEntropyUnit.KilocaloriePerGramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, quantity => new SpecificEntropy((quantity.Value) / 1e3d, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramKelvin, quantity => new SpecificEntropy((quantity.Value) / 1e3d, SpecificEntropyUnit.KilojoulePerKilogramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, quantity => new SpecificEntropy((quantity.Value) / 1e6d, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramKelvin, quantity => new SpecificEntropy((quantity.Value) / 1e6d, SpecificEntropyUnit.MegajoulePerKilogramKelvin)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity); // Register in unit converter: SpecificEntropyUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificEntropyUnit.BtuPerPoundFahrenheit, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEntropyUnit.CaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEntropyUnit.KilocaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEntropyUnit.KilojoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificEntropyUnit.MegajoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(SpecificEntropyUnit.BtuPerPoundFahrenheit, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => new SpecificEntropy(quantity.Value * 4.1868e3, SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.CaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => new SpecificEntropy(quantity.Value*4.184e3, SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => new SpecificEntropy(quantity.Value, SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.KilocaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => new SpecificEntropy((quantity.Value*4.184e3) * 1e3d, SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => new SpecificEntropy((quantity.Value) * 1e3d, SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.KilojoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => new SpecificEntropy((quantity.Value) * 1e3d, SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => new SpecificEntropy((quantity.Value) * 1e6d, SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction(SpecificEntropyUnit.MegajoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => new SpecificEntropy((quantity.Value) * 1e6d, SpecificEntropyUnit.JoulePerKilogramKelvin)); } /// @@ -752,11 +759,42 @@ double IQuantity.As(Enum unit) /// /// Converts this SpecificEntropy to another SpecificEntropy with the unit representation . /// + /// The unit to convert to. /// A SpecificEntropy with the specified unit. public SpecificEntropy ToUnit(SpecificEntropyUnit unit) { - var convertedValue = GetValueAs(unit); - return new SpecificEntropy(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this SpecificEntropy to another SpecificEntropy using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A SpecificEntropy with the specified unit. + public SpecificEntropy ToUnit(SpecificEntropyUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(SpecificEntropy), Unit, typeof(SpecificEntropy), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (SpecificEntropy)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -765,7 +803,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is SpecificEntropyUnit unitAsSpecificEntropyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEntropyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificEntropyUnit); + return ToUnit(unitAsSpecificEntropyUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is SpecificEntropyUnit unitAsSpecificEntropyUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEntropyUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsSpecificEntropyUnit, unitConverter); } /// @@ -790,63 +837,15 @@ public SpecificEntropy ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(SpecificEntropyUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case SpecificEntropyUnit.BtuPerPoundFahrenheit: return _value * 4.1868e3; - case SpecificEntropyUnit.CaloriePerGramKelvin: return _value*4.184e3; - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return _value; - case SpecificEntropyUnit.JoulePerKilogramKelvin: return _value; - case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (_value*4.184e3) * 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (_value) * 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (_value) * 1e3d; - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (_value) * 1e6d; - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(SpecificEntropyUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal SpecificEntropy ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new SpecificEntropy(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(SpecificEntropyUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case SpecificEntropyUnit.BtuPerPoundFahrenheit: return baseUnitValue / 4.1868e3; - case SpecificEntropyUnit.CaloriePerGramKelvin: return baseUnitValue/4.184e3; - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return baseUnitValue; - case SpecificEntropyUnit.JoulePerKilogramKelvin: return baseUnitValue; - case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (baseUnitValue/4.184e3) / 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (baseUnitValue) / 1e3d; - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e6d; - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs index 7b156bf3ed..e216a4952f 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs @@ -71,6 +71,8 @@ static SpecificFuelConsumption() new UnitInfo(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, "PoundsMassPerPoundForceHour", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.SpecificFuelConsumption); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -109,6 +111,11 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -216,17 +223,17 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> SpecificFuelConsumptionUnit - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour)); - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond)); - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour)); + unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, quantity => new SpecificFuelConsumption(quantity.Value/28.33, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour)); + unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, quantity => new SpecificFuelConsumption((quantity.Value) / 1e3d, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond)); + unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, quantity => new SpecificFuelConsumption(quantity.Value/28.33, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => quantity); // Register in unit converter: SpecificFuelConsumptionUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => new SpecificFuelConsumption(quantity.Value*28.33, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond)); + unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => new SpecificFuelConsumption((quantity.Value) * 1e3d, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond)); + unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => new SpecificFuelConsumption(quantity.Value*28.33, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond)); } /// @@ -670,11 +677,42 @@ double IQuantity.As(Enum unit) /// /// Converts this SpecificFuelConsumption to another SpecificFuelConsumption with the unit representation . /// + /// The unit to convert to. /// A SpecificFuelConsumption with the specified unit. public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit) { - var convertedValue = GetValueAs(unit); - return new SpecificFuelConsumption(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this SpecificFuelConsumption to another SpecificFuelConsumption using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A SpecificFuelConsumption with the specified unit. + public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(SpecificFuelConsumption), Unit, typeof(SpecificFuelConsumption), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (SpecificFuelConsumption)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -683,7 +721,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is SpecificFuelConsumptionUnit unitAsSpecificFuelConsumptionUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificFuelConsumptionUnit); + return ToUnit(unitAsSpecificFuelConsumptionUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is SpecificFuelConsumptionUnit unitAsSpecificFuelConsumptionUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificFuelConsumptionUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsSpecificFuelConsumptionUnit, unitConverter); } /// @@ -708,53 +755,15 @@ public SpecificFuelConsumption ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(SpecificFuelConsumptionUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond: return _value; - case SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour: return _value*28.33; - case SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond: return (_value) * 1e3d; - case SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour: return _value*28.33; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(SpecificFuelConsumptionUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal SpecificFuelConsumption ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new SpecificFuelConsumption(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(SpecificFuelConsumptionUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond: return baseUnitValue; - case SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour: return baseUnitValue/28.33; - case SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond: return (baseUnitValue) / 1e3d; - case SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour: return baseUnitValue/28.33; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs index f261a79750..3428ccae74 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs @@ -67,6 +67,8 @@ static SpecificVolume() new UnitInfo(SpecificVolumeUnit.MillicubicMeterPerKilogram, "MillicubicMetersPerKilogram", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.SpecificVolume); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -105,6 +107,11 @@ public SpecificVolume(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -207,15 +214,15 @@ public SpecificVolume(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> SpecificVolumeUnit - unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.CubicFootPerPound, quantity => quantity.ToUnit(SpecificVolumeUnit.CubicFootPerPound)); - unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.MillicubicMeterPerKilogram, quantity => quantity.ToUnit(SpecificVolumeUnit.MillicubicMeterPerKilogram)); + unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.CubicFootPerPound, quantity => new SpecificVolume(quantity.Value*16.01846353, SpecificVolumeUnit.CubicFootPerPound)); + unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.MillicubicMeterPerKilogram, quantity => new SpecificVolume((quantity.Value) / 1e-3d, SpecificVolumeUnit.MillicubicMeterPerKilogram)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => quantity); // Register in unit converter: SpecificVolumeUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicFootPerPound, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificVolumeUnit.MillicubicMeterPerKilogram, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicFootPerPound, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => new SpecificVolume(quantity.Value/16.01846353, SpecificVolumeUnit.CubicMeterPerKilogram)); + unitConverter.SetConversionFunction(SpecificVolumeUnit.MillicubicMeterPerKilogram, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => new SpecificVolume((quantity.Value) * 1e-3d, SpecificVolumeUnit.CubicMeterPerKilogram)); } /// @@ -650,11 +657,42 @@ double IQuantity.As(Enum unit) /// /// Converts this SpecificVolume to another SpecificVolume with the unit representation . /// + /// The unit to convert to. /// A SpecificVolume with the specified unit. public SpecificVolume ToUnit(SpecificVolumeUnit unit) { - var convertedValue = GetValueAs(unit); - return new SpecificVolume(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this SpecificVolume to another SpecificVolume using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A SpecificVolume with the specified unit. + public SpecificVolume ToUnit(SpecificVolumeUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(SpecificVolume), Unit, typeof(SpecificVolume), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (SpecificVolume)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -663,7 +701,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is SpecificVolumeUnit unitAsSpecificVolumeUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificVolumeUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificVolumeUnit); + return ToUnit(unitAsSpecificVolumeUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is SpecificVolumeUnit unitAsSpecificVolumeUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificVolumeUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsSpecificVolumeUnit, unitConverter); } /// @@ -688,51 +735,15 @@ public SpecificVolume ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(SpecificVolumeUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case SpecificVolumeUnit.CubicFootPerPound: return _value/16.01846353; - case SpecificVolumeUnit.CubicMeterPerKilogram: return _value; - case SpecificVolumeUnit.MillicubicMeterPerKilogram: return (_value) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(SpecificVolumeUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal SpecificVolume ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new SpecificVolume(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(SpecificVolumeUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case SpecificVolumeUnit.CubicFootPerPound: return baseUnitValue*16.01846353; - case SpecificVolumeUnit.CubicMeterPerKilogram: return baseUnitValue; - case SpecificVolumeUnit.MillicubicMeterPerKilogram: return (baseUnitValue) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs index e637aee844..81ed9de775 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs @@ -84,6 +84,8 @@ static SpecificWeight() new UnitInfo(SpecificWeightUnit.TonneForcePerCubicMillimeter, "TonnesForcePerCubicMillimeter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.SpecificWeight); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -122,6 +124,11 @@ public SpecificWeight(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -294,43 +301,43 @@ public SpecificWeight(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> SpecificWeightUnit - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilogramForcePerCubicCentimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMillimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilonewtonPerCubicCentimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMillimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicFoot, quantity => quantity.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicFoot)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicInch, quantity => quantity.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicInch)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.MeganewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.MeganewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicCentimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMillimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicFoot, quantity => quantity.ToUnit(SpecificWeightUnit.PoundForcePerCubicFoot)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicInch, quantity => quantity.ToUnit(SpecificWeightUnit.PoundForcePerCubicInch)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.TonneForcePerCubicCentimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.TonneForcePerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.TonneForcePerCubicMillimeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicCentimeter, quantity => new SpecificWeight(quantity.Value/9.80665e6, SpecificWeightUnit.KilogramForcePerCubicCentimeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMeter, quantity => new SpecificWeight(quantity.Value/9.80665, SpecificWeightUnit.KilogramForcePerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMillimeter, quantity => new SpecificWeight(quantity.Value/9.80665e9, SpecificWeightUnit.KilogramForcePerCubicMillimeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicCentimeter, quantity => new SpecificWeight((quantity.Value*0.000001) / 1e3d, SpecificWeightUnit.KilonewtonPerCubicCentimeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMeter, quantity => new SpecificWeight((quantity.Value) / 1e3d, SpecificWeightUnit.KilonewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMillimeter, quantity => new SpecificWeight((quantity.Value*0.000000001) / 1e3d, SpecificWeightUnit.KilonewtonPerCubicMillimeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicFoot, quantity => new SpecificWeight((quantity.Value/1.570874638462462e2) / 1e3d, SpecificWeightUnit.KilopoundForcePerCubicFoot)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicInch, quantity => new SpecificWeight((quantity.Value/2.714471375263134e5) / 1e3d, SpecificWeightUnit.KilopoundForcePerCubicInch)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.MeganewtonPerCubicMeter, quantity => new SpecificWeight((quantity.Value) / 1e6d, SpecificWeightUnit.MeganewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicCentimeter, quantity => new SpecificWeight(quantity.Value*0.000001, SpecificWeightUnit.NewtonPerCubicCentimeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMillimeter, quantity => new SpecificWeight(quantity.Value*0.000000001, SpecificWeightUnit.NewtonPerCubicMillimeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicFoot, quantity => new SpecificWeight(quantity.Value/1.570874638462462e2, SpecificWeightUnit.PoundForcePerCubicFoot)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicInch, quantity => new SpecificWeight(quantity.Value/2.714471375263134e5, SpecificWeightUnit.PoundForcePerCubicInch)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicCentimeter, quantity => new SpecificWeight(quantity.Value/9.80665e9, SpecificWeightUnit.TonneForcePerCubicCentimeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMeter, quantity => new SpecificWeight(quantity.Value/9.80665e3, SpecificWeightUnit.TonneForcePerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMillimeter, quantity => new SpecificWeight(quantity.Value/9.80665e12, SpecificWeightUnit.TonneForcePerCubicMillimeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity); // Register in unit converter: SpecificWeightUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificWeightUnit.KilogramForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilogramForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilogramForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilonewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilonewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilonewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilopoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilopoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.MeganewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.PoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.PoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.TonneForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.TonneForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpecificWeightUnit.TonneForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(SpecificWeightUnit.KilogramForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*9.80665e6, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.KilogramForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*9.80665, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.KilogramForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*9.80665e9, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.KilonewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight((quantity.Value*1000000) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.KilonewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight((quantity.Value) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.KilonewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight((quantity.Value*1000000000) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.KilopoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight((quantity.Value*1.570874638462462e2) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.KilopoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight((quantity.Value*2.714471375263134e5) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.MeganewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight((quantity.Value) * 1e6d, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*1000000, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*1000000000, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.PoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*1.570874638462462e2, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.PoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*2.714471375263134e5, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.TonneForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*9.80665e9, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.TonneForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*9.80665e3, SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction(SpecificWeightUnit.TonneForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => new SpecificWeight(quantity.Value*9.80665e12, SpecificWeightUnit.NewtonPerCubicMeter)); } /// @@ -891,11 +898,42 @@ double IQuantity.As(Enum unit) /// /// Converts this SpecificWeight to another SpecificWeight with the unit representation . /// + /// The unit to convert to. /// A SpecificWeight with the specified unit. public SpecificWeight ToUnit(SpecificWeightUnit unit) { - var convertedValue = GetValueAs(unit); - return new SpecificWeight(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this SpecificWeight to another SpecificWeight using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A SpecificWeight with the specified unit. + public SpecificWeight ToUnit(SpecificWeightUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(SpecificWeight), Unit, typeof(SpecificWeight), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (SpecificWeight)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -904,7 +942,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is SpecificWeightUnit unitAsSpecificWeightUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificWeightUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificWeightUnit); + return ToUnit(unitAsSpecificWeightUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is SpecificWeightUnit unitAsSpecificWeightUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificWeightUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsSpecificWeightUnit, unitConverter); } /// @@ -929,79 +976,15 @@ public SpecificWeight ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(SpecificWeightUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return _value*9.80665e6; - case SpecificWeightUnit.KilogramForcePerCubicMeter: return _value*9.80665; - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return _value*9.80665e9; - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (_value*1000000) * 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMeter: return (_value) * 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (_value*1000000000) * 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (_value*1.570874638462462e2) * 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicInch: return (_value*2.714471375263134e5) * 1e3d; - case SpecificWeightUnit.MeganewtonPerCubicMeter: return (_value) * 1e6d; - case SpecificWeightUnit.NewtonPerCubicCentimeter: return _value*1000000; - case SpecificWeightUnit.NewtonPerCubicMeter: return _value; - case SpecificWeightUnit.NewtonPerCubicMillimeter: return _value*1000000000; - case SpecificWeightUnit.PoundForcePerCubicFoot: return _value*1.570874638462462e2; - case SpecificWeightUnit.PoundForcePerCubicInch: return _value*2.714471375263134e5; - case SpecificWeightUnit.TonneForcePerCubicCentimeter: return _value*9.80665e9; - case SpecificWeightUnit.TonneForcePerCubicMeter: return _value*9.80665e3; - case SpecificWeightUnit.TonneForcePerCubicMillimeter: return _value*9.80665e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(SpecificWeightUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal SpecificWeight ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new SpecificWeight(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(SpecificWeightUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return baseUnitValue/9.80665e6; - case SpecificWeightUnit.KilogramForcePerCubicMeter: return baseUnitValue/9.80665; - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return baseUnitValue/9.80665e9; - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (baseUnitValue*0.000001) / 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMeter: return (baseUnitValue) / 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (baseUnitValue*0.000000001) / 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (baseUnitValue/1.570874638462462e2) / 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicInch: return (baseUnitValue/2.714471375263134e5) / 1e3d; - case SpecificWeightUnit.MeganewtonPerCubicMeter: return (baseUnitValue) / 1e6d; - case SpecificWeightUnit.NewtonPerCubicCentimeter: return baseUnitValue*0.000001; - case SpecificWeightUnit.NewtonPerCubicMeter: return baseUnitValue; - case SpecificWeightUnit.NewtonPerCubicMillimeter: return baseUnitValue*0.000000001; - case SpecificWeightUnit.PoundForcePerCubicFoot: return baseUnitValue/1.570874638462462e2; - case SpecificWeightUnit.PoundForcePerCubicInch: return baseUnitValue/2.714471375263134e5; - case SpecificWeightUnit.TonneForcePerCubicCentimeter: return baseUnitValue/9.80665e9; - case SpecificWeightUnit.TonneForcePerCubicMeter: return baseUnitValue/9.80665e3; - case SpecificWeightUnit.TonneForcePerCubicMillimeter: return baseUnitValue/9.80665e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs index 6c99bea7e0..3a5701a29e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs @@ -96,6 +96,8 @@ static Speed() new UnitInfo(SpeedUnit.YardPerSecond, "YardsPerSecond", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Second)), }, BaseUnit, Zero, BaseDimensions, QuantityType.Speed); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -134,6 +136,11 @@ public Speed(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -381,73 +388,73 @@ public Speed(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> SpeedUnit - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerHour, quantity => quantity.ToUnit(SpeedUnit.CentimeterPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.CentimeterPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.CentimeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.DecimeterPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.DecimeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerHour, quantity => quantity.ToUnit(SpeedUnit.FootPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerMinute, quantity => quantity.ToUnit(SpeedUnit.FootPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerSecond, quantity => quantity.ToUnit(SpeedUnit.FootPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerHour, quantity => quantity.ToUnit(SpeedUnit.InchPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerMinute, quantity => quantity.ToUnit(SpeedUnit.InchPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerSecond, quantity => quantity.ToUnit(SpeedUnit.InchPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerHour, quantity => quantity.ToUnit(SpeedUnit.KilometerPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerMinute, quantity => quantity.ToUnit(SpeedUnit.KilometerPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerSecond, quantity => quantity.ToUnit(SpeedUnit.KilometerPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.Knot, quantity => quantity.ToUnit(SpeedUnit.Knot)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerHour, quantity => quantity.ToUnit(SpeedUnit.MeterPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.MeterPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerMinute, quantity => quantity.ToUnit(SpeedUnit.MicrometerPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerSecond, quantity => quantity.ToUnit(SpeedUnit.MicrometerPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MilePerHour, quantity => quantity.ToUnit(SpeedUnit.MilePerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerHour, quantity => quantity.ToUnit(SpeedUnit.MillimeterPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.MillimeterPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MillimeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerMinute, quantity => quantity.ToUnit(SpeedUnit.NanometerPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerSecond, quantity => quantity.ToUnit(SpeedUnit.NanometerPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerHour, quantity => quantity.ToUnit(SpeedUnit.UsSurveyFootPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerMinute, quantity => quantity.ToUnit(SpeedUnit.UsSurveyFootPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerSecond, quantity => quantity.ToUnit(SpeedUnit.UsSurveyFootPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerHour, quantity => quantity.ToUnit(SpeedUnit.YardPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerMinute, quantity => quantity.ToUnit(SpeedUnit.YardPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerSecond, quantity => quantity.ToUnit(SpeedUnit.YardPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerHour, quantity => new Speed((quantity.Value*3600) / 1e-2d, SpeedUnit.CentimeterPerHour)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerMinute, quantity => new Speed((quantity.Value*60) / 1e-2d, SpeedUnit.CentimeterPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerSecond, quantity => new Speed((quantity.Value) / 1e-2d, SpeedUnit.CentimeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerMinute, quantity => new Speed((quantity.Value*60) / 1e-1d, SpeedUnit.DecimeterPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerSecond, quantity => new Speed((quantity.Value) / 1e-1d, SpeedUnit.DecimeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerHour, quantity => new Speed(quantity.Value/0.3048*3600, SpeedUnit.FootPerHour)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerMinute, quantity => new Speed(quantity.Value/0.3048*60, SpeedUnit.FootPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerSecond, quantity => new Speed(quantity.Value/0.3048, SpeedUnit.FootPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerHour, quantity => new Speed((quantity.Value/2.54e-2)*3600, SpeedUnit.InchPerHour)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerMinute, quantity => new Speed((quantity.Value/2.54e-2)*60, SpeedUnit.InchPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerSecond, quantity => new Speed(quantity.Value/2.54e-2, SpeedUnit.InchPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerHour, quantity => new Speed((quantity.Value*3600) / 1e3d, SpeedUnit.KilometerPerHour)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerMinute, quantity => new Speed((quantity.Value*60) / 1e3d, SpeedUnit.KilometerPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerSecond, quantity => new Speed((quantity.Value) / 1e3d, SpeedUnit.KilometerPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.Knot, quantity => new Speed(quantity.Value/0.514444, SpeedUnit.Knot)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerHour, quantity => new Speed(quantity.Value*3600, SpeedUnit.MeterPerHour)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerMinute, quantity => new Speed(quantity.Value*60, SpeedUnit.MeterPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerMinute, quantity => new Speed((quantity.Value*60) / 1e-6d, SpeedUnit.MicrometerPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerSecond, quantity => new Speed((quantity.Value) / 1e-6d, SpeedUnit.MicrometerPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MilePerHour, quantity => new Speed(quantity.Value/0.44704, SpeedUnit.MilePerHour)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerHour, quantity => new Speed((quantity.Value*3600) / 1e-3d, SpeedUnit.MillimeterPerHour)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerMinute, quantity => new Speed((quantity.Value*60) / 1e-3d, SpeedUnit.MillimeterPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerSecond, quantity => new Speed((quantity.Value) / 1e-3d, SpeedUnit.MillimeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerMinute, quantity => new Speed((quantity.Value*60) / 1e-9d, SpeedUnit.NanometerPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerSecond, quantity => new Speed((quantity.Value) / 1e-9d, SpeedUnit.NanometerPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerHour, quantity => new Speed((quantity.Value*3937/1200)*3600, SpeedUnit.UsSurveyFootPerHour)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerMinute, quantity => new Speed((quantity.Value*3937/1200)*60, SpeedUnit.UsSurveyFootPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerSecond, quantity => new Speed(quantity.Value*3937/1200, SpeedUnit.UsSurveyFootPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerHour, quantity => new Speed(quantity.Value/0.9144*3600, SpeedUnit.YardPerHour)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerMinute, quantity => new Speed(quantity.Value/0.9144*60, SpeedUnit.YardPerMinute)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerSecond, quantity => new Speed(quantity.Value/0.9144, SpeedUnit.YardPerSecond)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity); // Register in unit converter: SpeedUnit -> BaseUnit - unitConverter.SetConversionFunction(SpeedUnit.CentimeterPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.CentimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.CentimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.DecimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.DecimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.FootPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.FootPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.FootPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.InchPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.InchPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.InchPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.KilometerPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.KilometerPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.KilometerPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.Knot, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.MicrometerPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.MicrometerPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.MilePerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.MillimeterPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.MillimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.MillimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.NanometerPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.NanometerPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.UsSurveyFootPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.UsSurveyFootPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.UsSurveyFootPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.YardPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.YardPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(SpeedUnit.YardPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(SpeedUnit.CentimeterPerHour, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/3600) * 1e-2d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.CentimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/60) * 1e-2d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.CentimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value) * 1e-2d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.DecimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/60) * 1e-1d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.DecimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value) * 1e-1d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.FootPerHour, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*0.3048/3600, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.FootPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*0.3048/60, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.FootPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*0.3048, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.InchPerHour, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/3600)*2.54e-2, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.InchPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/60)*2.54e-2, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.InchPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*2.54e-2, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.KilometerPerHour, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/3600) * 1e3d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.KilometerPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/60) * 1e3d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.KilometerPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value) * 1e3d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.Knot, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*0.514444, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerHour, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value/3600, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MeterPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value/60, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MicrometerPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/60) * 1e-6d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MicrometerPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value) * 1e-6d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MilePerHour, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*0.44704, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MillimeterPerHour, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/3600) * 1e-3d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MillimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/60) * 1e-3d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.MillimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value) * 1e-3d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.NanometerPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value/60) * 1e-9d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.NanometerPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value) * 1e-9d, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.UsSurveyFootPerHour, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value*1200/3937)/3600, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.UsSurveyFootPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed((quantity.Value*1200/3937)/60, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.UsSurveyFootPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*1200/3937, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.YardPerHour, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*0.9144/3600, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.YardPerMinute, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*0.9144/60, SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction(SpeedUnit.YardPerSecond, SpeedUnit.MeterPerSecond, quantity => new Speed(quantity.Value*0.9144, SpeedUnit.MeterPerSecond)); } /// @@ -1143,11 +1150,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Speed to another Speed with the unit representation . /// + /// The unit to convert to. /// A Speed with the specified unit. public Speed ToUnit(SpeedUnit unit) { - var convertedValue = GetValueAs(unit); - return new Speed(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Speed to another Speed using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Speed with the specified unit. + public Speed ToUnit(SpeedUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Speed), Unit, typeof(Speed), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Speed)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1156,7 +1194,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is SpeedUnit unitAsSpeedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpeedUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpeedUnit); + return ToUnit(unitAsSpeedUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is SpeedUnit unitAsSpeedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpeedUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsSpeedUnit, unitConverter); } /// @@ -1181,109 +1228,15 @@ public Speed ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(SpeedUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case SpeedUnit.CentimeterPerHour: return (_value/3600) * 1e-2d; - case SpeedUnit.CentimeterPerMinute: return (_value/60) * 1e-2d; - case SpeedUnit.CentimeterPerSecond: return (_value) * 1e-2d; - case SpeedUnit.DecimeterPerMinute: return (_value/60) * 1e-1d; - case SpeedUnit.DecimeterPerSecond: return (_value) * 1e-1d; - case SpeedUnit.FootPerHour: return _value*0.3048/3600; - case SpeedUnit.FootPerMinute: return _value*0.3048/60; - case SpeedUnit.FootPerSecond: return _value*0.3048; - case SpeedUnit.InchPerHour: return (_value/3600)*2.54e-2; - case SpeedUnit.InchPerMinute: return (_value/60)*2.54e-2; - case SpeedUnit.InchPerSecond: return _value*2.54e-2; - case SpeedUnit.KilometerPerHour: return (_value/3600) * 1e3d; - case SpeedUnit.KilometerPerMinute: return (_value/60) * 1e3d; - case SpeedUnit.KilometerPerSecond: return (_value) * 1e3d; - case SpeedUnit.Knot: return _value*0.514444; - case SpeedUnit.MeterPerHour: return _value/3600; - case SpeedUnit.MeterPerMinute: return _value/60; - case SpeedUnit.MeterPerSecond: return _value; - case SpeedUnit.MicrometerPerMinute: return (_value/60) * 1e-6d; - case SpeedUnit.MicrometerPerSecond: return (_value) * 1e-6d; - case SpeedUnit.MilePerHour: return _value*0.44704; - case SpeedUnit.MillimeterPerHour: return (_value/3600) * 1e-3d; - case SpeedUnit.MillimeterPerMinute: return (_value/60) * 1e-3d; - case SpeedUnit.MillimeterPerSecond: return (_value) * 1e-3d; - case SpeedUnit.NanometerPerMinute: return (_value/60) * 1e-9d; - case SpeedUnit.NanometerPerSecond: return (_value) * 1e-9d; - case SpeedUnit.UsSurveyFootPerHour: return (_value*1200/3937)/3600; - case SpeedUnit.UsSurveyFootPerMinute: return (_value*1200/3937)/60; - case SpeedUnit.UsSurveyFootPerSecond: return _value*1200/3937; - case SpeedUnit.YardPerHour: return _value*0.9144/3600; - case SpeedUnit.YardPerMinute: return _value*0.9144/60; - case SpeedUnit.YardPerSecond: return _value*0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(SpeedUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Speed ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Speed(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(SpeedUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case SpeedUnit.CentimeterPerHour: return (baseUnitValue*3600) / 1e-2d; - case SpeedUnit.CentimeterPerMinute: return (baseUnitValue*60) / 1e-2d; - case SpeedUnit.CentimeterPerSecond: return (baseUnitValue) / 1e-2d; - case SpeedUnit.DecimeterPerMinute: return (baseUnitValue*60) / 1e-1d; - case SpeedUnit.DecimeterPerSecond: return (baseUnitValue) / 1e-1d; - case SpeedUnit.FootPerHour: return baseUnitValue/0.3048*3600; - case SpeedUnit.FootPerMinute: return baseUnitValue/0.3048*60; - case SpeedUnit.FootPerSecond: return baseUnitValue/0.3048; - case SpeedUnit.InchPerHour: return (baseUnitValue/2.54e-2)*3600; - case SpeedUnit.InchPerMinute: return (baseUnitValue/2.54e-2)*60; - case SpeedUnit.InchPerSecond: return baseUnitValue/2.54e-2; - case SpeedUnit.KilometerPerHour: return (baseUnitValue*3600) / 1e3d; - case SpeedUnit.KilometerPerMinute: return (baseUnitValue*60) / 1e3d; - case SpeedUnit.KilometerPerSecond: return (baseUnitValue) / 1e3d; - case SpeedUnit.Knot: return baseUnitValue/0.514444; - case SpeedUnit.MeterPerHour: return baseUnitValue*3600; - case SpeedUnit.MeterPerMinute: return baseUnitValue*60; - case SpeedUnit.MeterPerSecond: return baseUnitValue; - case SpeedUnit.MicrometerPerMinute: return (baseUnitValue*60) / 1e-6d; - case SpeedUnit.MicrometerPerSecond: return (baseUnitValue) / 1e-6d; - case SpeedUnit.MilePerHour: return baseUnitValue/0.44704; - case SpeedUnit.MillimeterPerHour: return (baseUnitValue*3600) / 1e-3d; - case SpeedUnit.MillimeterPerMinute: return (baseUnitValue*60) / 1e-3d; - case SpeedUnit.MillimeterPerSecond: return (baseUnitValue) / 1e-3d; - case SpeedUnit.NanometerPerMinute: return (baseUnitValue*60) / 1e-9d; - case SpeedUnit.NanometerPerSecond: return (baseUnitValue) / 1e-9d; - case SpeedUnit.UsSurveyFootPerHour: return (baseUnitValue*3937/1200)*3600; - case SpeedUnit.UsSurveyFootPerMinute: return (baseUnitValue*3937/1200)*60; - case SpeedUnit.UsSurveyFootPerSecond: return baseUnitValue*3937/1200; - case SpeedUnit.YardPerHour: return baseUnitValue/0.9144*3600; - case SpeedUnit.YardPerMinute: return baseUnitValue/0.9144*60; - case SpeedUnit.YardPerSecond: return baseUnitValue/0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs index aa8cea9aa2..9c1f265359 100644 --- a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs @@ -73,6 +73,8 @@ static StandardVolumeFlow() new UnitInfo(StandardVolumeFlowUnit.StandardLiterPerMinute, "StandardLitersPerMinute", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.StandardVolumeFlow); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -111,6 +113,11 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -243,27 +250,27 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> StandardVolumeFlowUnit - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerHour, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerHour)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerMinute)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerSecond)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerDay, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerDay)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerHour, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerHour)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerMinute)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardLiterPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardLiterPerMinute)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, quantity => new StandardVolumeFlow(quantity.Value*6e7, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerHour, quantity => new StandardVolumeFlow(quantity.Value/7.8657907199999087346816086183876e-6, StandardVolumeFlowUnit.StandardCubicFootPerHour)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerMinute, quantity => new StandardVolumeFlow(quantity.Value*2118.88000326, StandardVolumeFlowUnit.StandardCubicFootPerMinute)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerSecond, quantity => new StandardVolumeFlow(quantity.Value*35.314666721, StandardVolumeFlowUnit.StandardCubicFootPerSecond)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerDay, quantity => new StandardVolumeFlow(quantity.Value*86400, StandardVolumeFlowUnit.StandardCubicMeterPerDay)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerHour, quantity => new StandardVolumeFlow(quantity.Value*3600, StandardVolumeFlowUnit.StandardCubicMeterPerHour)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerMinute, quantity => new StandardVolumeFlow(quantity.Value*60, StandardVolumeFlowUnit.StandardCubicMeterPerMinute)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardLiterPerMinute, quantity => new StandardVolumeFlow(quantity.Value*60000, StandardVolumeFlowUnit.StandardLiterPerMinute)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity); // Register in unit converter: StandardVolumeFlowUnit -> BaseUnit - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicFootPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicFootPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicFootPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerDay, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardLiterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => new StandardVolumeFlow(quantity.Value/6e7, StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicFootPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => new StandardVolumeFlow(quantity.Value*7.8657907199999087346816086183876e-6, StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicFootPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => new StandardVolumeFlow(quantity.Value/2118.88000326, StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicFootPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => new StandardVolumeFlow(quantity.Value/35.314666721, StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerDay, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => new StandardVolumeFlow(quantity.Value/86400, StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => new StandardVolumeFlow(quantity.Value/3600, StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => new StandardVolumeFlow(quantity.Value/60, StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardLiterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => new StandardVolumeFlow(quantity.Value/60000, StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); } /// @@ -752,11 +759,42 @@ double IQuantity.As(Enum unit) /// /// Converts this StandardVolumeFlow to another StandardVolumeFlow with the unit representation . /// + /// The unit to convert to. /// A StandardVolumeFlow with the specified unit. public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit) { - var convertedValue = GetValueAs(unit); - return new StandardVolumeFlow(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this StandardVolumeFlow to another StandardVolumeFlow using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A StandardVolumeFlow with the specified unit. + public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(StandardVolumeFlow), Unit, typeof(StandardVolumeFlow), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (StandardVolumeFlow)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -765,7 +803,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is StandardVolumeFlowUnit unitAsStandardVolumeFlowUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(StandardVolumeFlowUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsStandardVolumeFlowUnit); + return ToUnit(unitAsStandardVolumeFlowUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is StandardVolumeFlowUnit unitAsStandardVolumeFlowUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(StandardVolumeFlowUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsStandardVolumeFlowUnit, unitConverter); } /// @@ -790,63 +837,15 @@ public StandardVolumeFlow ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(StandardVolumeFlowUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute: return _value/6e7; - case StandardVolumeFlowUnit.StandardCubicFootPerHour: return _value*7.8657907199999087346816086183876e-6; - case StandardVolumeFlowUnit.StandardCubicFootPerMinute: return _value/2118.88000326; - case StandardVolumeFlowUnit.StandardCubicFootPerSecond: return _value/35.314666721; - case StandardVolumeFlowUnit.StandardCubicMeterPerDay: return _value/86400; - case StandardVolumeFlowUnit.StandardCubicMeterPerHour: return _value/3600; - case StandardVolumeFlowUnit.StandardCubicMeterPerMinute: return _value/60; - case StandardVolumeFlowUnit.StandardCubicMeterPerSecond: return _value; - case StandardVolumeFlowUnit.StandardLiterPerMinute: return _value/60000; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(StandardVolumeFlowUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal StandardVolumeFlow ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new StandardVolumeFlow(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(StandardVolumeFlowUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute: return baseUnitValue*6e7; - case StandardVolumeFlowUnit.StandardCubicFootPerHour: return baseUnitValue/7.8657907199999087346816086183876e-6; - case StandardVolumeFlowUnit.StandardCubicFootPerMinute: return baseUnitValue*2118.88000326; - case StandardVolumeFlowUnit.StandardCubicFootPerSecond: return baseUnitValue*35.314666721; - case StandardVolumeFlowUnit.StandardCubicMeterPerDay: return baseUnitValue*86400; - case StandardVolumeFlowUnit.StandardCubicMeterPerHour: return baseUnitValue*3600; - case StandardVolumeFlowUnit.StandardCubicMeterPerMinute: return baseUnitValue*60; - case StandardVolumeFlowUnit.StandardCubicMeterPerSecond: return baseUnitValue; - case StandardVolumeFlowUnit.StandardLiterPerMinute: return baseUnitValue*60000; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs index 29d857313e..1739b95e8b 100644 --- a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs @@ -74,6 +74,8 @@ static Temperature() new UnitInfo(TemperatureUnit.SolarTemperature, "SolarTemperatures", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Temperature); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -112,6 +114,11 @@ public Temperature(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -249,29 +256,29 @@ public Temperature(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> TemperatureUnit - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeCelsius, quantity => quantity.ToUnit(TemperatureUnit.DegreeCelsius)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeDelisle, quantity => quantity.ToUnit(TemperatureUnit.DegreeDelisle)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeFahrenheit, quantity => quantity.ToUnit(TemperatureUnit.DegreeFahrenheit)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeNewton, quantity => quantity.ToUnit(TemperatureUnit.DegreeNewton)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeRankine, quantity => quantity.ToUnit(TemperatureUnit.DegreeRankine)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeReaumur, quantity => quantity.ToUnit(TemperatureUnit.DegreeReaumur)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeRoemer, quantity => quantity.ToUnit(TemperatureUnit.DegreeRoemer)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.MillidegreeCelsius, quantity => quantity.ToUnit(TemperatureUnit.MillidegreeCelsius)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.SolarTemperature, quantity => quantity.ToUnit(TemperatureUnit.SolarTemperature)); + unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeCelsius, quantity => new Temperature(quantity.Value - 273.15, TemperatureUnit.DegreeCelsius)); + unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeDelisle, quantity => new Temperature((quantity.Value - 373.15)*-3/2, TemperatureUnit.DegreeDelisle)); + unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeFahrenheit, quantity => new Temperature((quantity.Value - 459.67*5/9)*9/5, TemperatureUnit.DegreeFahrenheit)); + unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeNewton, quantity => new Temperature((quantity.Value - 273.15)*33/100, TemperatureUnit.DegreeNewton)); + unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeRankine, quantity => new Temperature(quantity.Value*9/5, TemperatureUnit.DegreeRankine)); + unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeReaumur, quantity => new Temperature((quantity.Value - 273.15)*4/5, TemperatureUnit.DegreeReaumur)); + unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeRoemer, quantity => new Temperature((quantity.Value - (273.15 - 7.5*40d/21))*21/40, TemperatureUnit.DegreeRoemer)); + unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.MillidegreeCelsius, quantity => new Temperature((quantity.Value - 273.15) * 1000, TemperatureUnit.MillidegreeCelsius)); + unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.SolarTemperature, quantity => new Temperature(quantity.Value / 5778, TemperatureUnit.SolarTemperature)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.Kelvin, quantity => quantity); // Register in unit converter: TemperatureUnit -> BaseUnit - unitConverter.SetConversionFunction(TemperatureUnit.DegreeCelsius, TemperatureUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeDelisle, TemperatureUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeFahrenheit, TemperatureUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeNewton, TemperatureUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeRankine, TemperatureUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeReaumur, TemperatureUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeRoemer, TemperatureUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureUnit.MillidegreeCelsius, TemperatureUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureUnit.SolarTemperature, TemperatureUnit.Kelvin, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(TemperatureUnit.DegreeCelsius, TemperatureUnit.Kelvin, quantity => new Temperature(quantity.Value + 273.15, TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureUnit.DegreeDelisle, TemperatureUnit.Kelvin, quantity => new Temperature(quantity.Value*-2/3 + 373.15, TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureUnit.DegreeFahrenheit, TemperatureUnit.Kelvin, quantity => new Temperature(quantity.Value*5/9 + 459.67*5/9, TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureUnit.DegreeNewton, TemperatureUnit.Kelvin, quantity => new Temperature(quantity.Value*100/33 + 273.15, TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureUnit.DegreeRankine, TemperatureUnit.Kelvin, quantity => new Temperature(quantity.Value*5/9, TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureUnit.DegreeReaumur, TemperatureUnit.Kelvin, quantity => new Temperature(quantity.Value*5/4 + 273.15, TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureUnit.DegreeRoemer, TemperatureUnit.Kelvin, quantity => new Temperature(quantity.Value*40/21 + 273.15 - 7.5*40d/21, TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureUnit.MillidegreeCelsius, TemperatureUnit.Kelvin, quantity => new Temperature(quantity.Value / 1000 + 273.15, TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureUnit.SolarTemperature, TemperatureUnit.Kelvin, quantity => new Temperature(quantity.Value * 5778, TemperatureUnit.Kelvin)); } /// @@ -723,11 +730,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Temperature to another Temperature with the unit representation . /// + /// The unit to convert to. /// A Temperature with the specified unit. public Temperature ToUnit(TemperatureUnit unit) { - var convertedValue = GetValueAs(unit); - return new Temperature(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Temperature to another Temperature using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Temperature with the specified unit. + public Temperature ToUnit(TemperatureUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Temperature), Unit, typeof(Temperature), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Temperature)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -736,7 +774,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is TemperatureUnit unitAsTemperatureUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTemperatureUnit); + return ToUnit(unitAsTemperatureUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is TemperatureUnit unitAsTemperatureUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsTemperatureUnit, unitConverter); } /// @@ -761,65 +808,15 @@ public Temperature ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(TemperatureUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case TemperatureUnit.DegreeCelsius: return _value + 273.15; - case TemperatureUnit.DegreeDelisle: return _value*-2/3 + 373.15; - case TemperatureUnit.DegreeFahrenheit: return _value*5/9 + 459.67*5/9; - case TemperatureUnit.DegreeNewton: return _value*100/33 + 273.15; - case TemperatureUnit.DegreeRankine: return _value*5/9; - case TemperatureUnit.DegreeReaumur: return _value*5/4 + 273.15; - case TemperatureUnit.DegreeRoemer: return _value*40/21 + 273.15 - 7.5*40d/21; - case TemperatureUnit.Kelvin: return _value; - case TemperatureUnit.MillidegreeCelsius: return _value / 1000 + 273.15; - case TemperatureUnit.SolarTemperature: return _value * 5778; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(TemperatureUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Temperature ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Temperature(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(TemperatureUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case TemperatureUnit.DegreeCelsius: return baseUnitValue - 273.15; - case TemperatureUnit.DegreeDelisle: return (baseUnitValue - 373.15)*-3/2; - case TemperatureUnit.DegreeFahrenheit: return (baseUnitValue - 459.67*5/9)*9/5; - case TemperatureUnit.DegreeNewton: return (baseUnitValue - 273.15)*33/100; - case TemperatureUnit.DegreeRankine: return baseUnitValue*9/5; - case TemperatureUnit.DegreeReaumur: return (baseUnitValue - 273.15)*4/5; - case TemperatureUnit.DegreeRoemer: return (baseUnitValue - (273.15 - 7.5*40d/21))*21/40; - case TemperatureUnit.Kelvin: return baseUnitValue; - case TemperatureUnit.MillidegreeCelsius: return (baseUnitValue - 273.15) * 1000; - case TemperatureUnit.SolarTemperature: return baseUnitValue / 5778; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs index 45bc55e19a..600b004abc 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs @@ -74,6 +74,8 @@ static TemperatureChangeRate() new UnitInfo(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, "NanodegreesCelsiusPerSecond", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.TemperatureChangeRate); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -112,6 +114,11 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -249,29 +256,29 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> TemperatureChangeRateUnit - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerMinute, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerMinute)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) / 1e-2d, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) / 1e1d, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) / 1e-1d, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerMinute, quantity => new TemperatureChangeRate(quantity.Value*60, TemperatureChangeRateUnit.DegreeCelsiusPerMinute)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) / 1e2d, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) / 1e3d, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) / 1e-6d, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) / 1e-3d, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) / 1e-9d, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity); // Register in unit converter: TemperatureChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) * 1e-2d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) * 1e1d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) * 1e-1d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => new TemperatureChangeRate(quantity.Value/60, TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) * 1e2d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) * 1e3d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) * 1e-6d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) * 1e-3d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => new TemperatureChangeRate((quantity.Value) * 1e-9d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); } /// @@ -769,11 +776,42 @@ double IQuantity.As(Enum unit) /// /// Converts this TemperatureChangeRate to another TemperatureChangeRate with the unit representation . /// + /// The unit to convert to. /// A TemperatureChangeRate with the specified unit. public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) { - var convertedValue = GetValueAs(unit); - return new TemperatureChangeRate(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this TemperatureChangeRate to another TemperatureChangeRate using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A TemperatureChangeRate with the specified unit. + public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(TemperatureChangeRate), Unit, typeof(TemperatureChangeRate), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (TemperatureChangeRate)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -782,7 +820,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is TemperatureChangeRateUnit unitAsTemperatureChangeRateUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTemperatureChangeRateUnit); + return ToUnit(unitAsTemperatureChangeRateUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is TemperatureChangeRateUnit unitAsTemperatureChangeRateUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsTemperatureChangeRateUnit, unitConverter); } /// @@ -807,65 +854,15 @@ public TemperatureChangeRate ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(TemperatureChangeRateUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (_value) * 1e-2d; - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (_value) * 1e1d; - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (_value) * 1e-1d; - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return _value/60; - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return _value; - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (_value) * 1e2d; - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (_value) * 1e3d; - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (_value) * 1e-6d; - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (_value) * 1e-3d; - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (_value) * 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(TemperatureChangeRateUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal TemperatureChangeRate ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new TemperatureChangeRate(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(TemperatureChangeRateUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-2d; - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (baseUnitValue) / 1e1d; - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-1d; - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return baseUnitValue*60; - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return baseUnitValue; - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (baseUnitValue) / 1e2d; - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (baseUnitValue) / 1e3d; - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-6d; - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-3d; - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs index bad6645e65..6cddec2aae 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs @@ -73,6 +73,8 @@ static TemperatureDelta() new UnitInfo(TemperatureDeltaUnit.MillidegreeCelsius, "MillidegreesCelsius", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.TemperatureDelta); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -111,6 +113,11 @@ public TemperatureDelta(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -243,27 +250,27 @@ public TemperatureDelta(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> TemperatureDeltaUnit - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeCelsius, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeCelsius)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeDelisle, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeDelisle)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeFahrenheit, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeFahrenheit)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeNewton, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeNewton)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRankine, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeRankine)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeReaumur, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeReaumur)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRoemer, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeRoemer)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.MillidegreeCelsius, quantity => quantity.ToUnit(TemperatureDeltaUnit.MillidegreeCelsius)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeCelsius, quantity => new TemperatureDelta(quantity.Value, TemperatureDeltaUnit.DegreeCelsius)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeDelisle, quantity => new TemperatureDelta(quantity.Value*-3/2, TemperatureDeltaUnit.DegreeDelisle)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeFahrenheit, quantity => new TemperatureDelta(quantity.Value*9/5, TemperatureDeltaUnit.DegreeFahrenheit)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeNewton, quantity => new TemperatureDelta(quantity.Value*33/100, TemperatureDeltaUnit.DegreeNewton)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRankine, quantity => new TemperatureDelta(quantity.Value*9/5, TemperatureDeltaUnit.DegreeRankine)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeReaumur, quantity => new TemperatureDelta(quantity.Value*4/5, TemperatureDeltaUnit.DegreeReaumur)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRoemer, quantity => new TemperatureDelta(quantity.Value*21/40, TemperatureDeltaUnit.DegreeRoemer)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.MillidegreeCelsius, quantity => new TemperatureDelta((quantity.Value) / 1e-3d, TemperatureDeltaUnit.MillidegreeCelsius)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.Kelvin, quantity => quantity); // Register in unit converter: TemperatureDeltaUnit -> BaseUnit - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeCelsius, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeDelisle, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeFahrenheit, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeNewton, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeRankine, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeReaumur, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeRoemer, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.MillidegreeCelsius, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeCelsius, TemperatureDeltaUnit.Kelvin, quantity => new TemperatureDelta(quantity.Value, TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeDelisle, TemperatureDeltaUnit.Kelvin, quantity => new TemperatureDelta(quantity.Value*-2/3, TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeFahrenheit, TemperatureDeltaUnit.Kelvin, quantity => new TemperatureDelta(quantity.Value*5/9, TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeNewton, TemperatureDeltaUnit.Kelvin, quantity => new TemperatureDelta(quantity.Value*100/33, TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeRankine, TemperatureDeltaUnit.Kelvin, quantity => new TemperatureDelta(quantity.Value*5/9, TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeReaumur, TemperatureDeltaUnit.Kelvin, quantity => new TemperatureDelta(quantity.Value*5/4, TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeRoemer, TemperatureDeltaUnit.Kelvin, quantity => new TemperatureDelta(quantity.Value*40/21, TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction(TemperatureDeltaUnit.MillidegreeCelsius, TemperatureDeltaUnit.Kelvin, quantity => new TemperatureDelta((quantity.Value) * 1e-3d, TemperatureDeltaUnit.Kelvin)); } /// @@ -752,11 +759,42 @@ double IQuantity.As(Enum unit) /// /// Converts this TemperatureDelta to another TemperatureDelta with the unit representation . /// + /// The unit to convert to. /// A TemperatureDelta with the specified unit. public TemperatureDelta ToUnit(TemperatureDeltaUnit unit) { - var convertedValue = GetValueAs(unit); - return new TemperatureDelta(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this TemperatureDelta to another TemperatureDelta using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A TemperatureDelta with the specified unit. + public TemperatureDelta ToUnit(TemperatureDeltaUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(TemperatureDelta), Unit, typeof(TemperatureDelta), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (TemperatureDelta)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -765,7 +803,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is TemperatureDeltaUnit unitAsTemperatureDeltaUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureDeltaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTemperatureDeltaUnit); + return ToUnit(unitAsTemperatureDeltaUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is TemperatureDeltaUnit unitAsTemperatureDeltaUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureDeltaUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsTemperatureDeltaUnit, unitConverter); } /// @@ -790,63 +837,15 @@ public TemperatureDelta ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(TemperatureDeltaUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case TemperatureDeltaUnit.DegreeCelsius: return _value; - case TemperatureDeltaUnit.DegreeDelisle: return _value*-2/3; - case TemperatureDeltaUnit.DegreeFahrenheit: return _value*5/9; - case TemperatureDeltaUnit.DegreeNewton: return _value*100/33; - case TemperatureDeltaUnit.DegreeRankine: return _value*5/9; - case TemperatureDeltaUnit.DegreeReaumur: return _value*5/4; - case TemperatureDeltaUnit.DegreeRoemer: return _value*40/21; - case TemperatureDeltaUnit.Kelvin: return _value; - case TemperatureDeltaUnit.MillidegreeCelsius: return (_value) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(TemperatureDeltaUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal TemperatureDelta ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new TemperatureDelta(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(TemperatureDeltaUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case TemperatureDeltaUnit.DegreeCelsius: return baseUnitValue; - case TemperatureDeltaUnit.DegreeDelisle: return baseUnitValue*-3/2; - case TemperatureDeltaUnit.DegreeFahrenheit: return baseUnitValue*9/5; - case TemperatureDeltaUnit.DegreeNewton: return baseUnitValue*33/100; - case TemperatureDeltaUnit.DegreeRankine: return baseUnitValue*9/5; - case TemperatureDeltaUnit.DegreeReaumur: return baseUnitValue*4/5; - case TemperatureDeltaUnit.DegreeRoemer: return baseUnitValue*21/40; - case TemperatureDeltaUnit.Kelvin: return baseUnitValue; - case TemperatureDeltaUnit.MillidegreeCelsius: return (baseUnitValue) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs index 0915e16f8c..e6c454181a 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs @@ -68,6 +68,8 @@ static TemperatureGradient() new UnitInfo(TemperatureGradientUnit.KelvinPerMeter, "KelvinsPerMeter", new BaseUnits(length: LengthUnit.Meter, temperature: TemperatureUnit.Kelvin)), }, BaseUnit, Zero, BaseDimensions, QuantityType.TemperatureGradient); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public TemperatureGradient(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -213,17 +220,17 @@ public TemperatureGradient(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> TemperatureGradientUnit - unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerKilometer, quantity => quantity.ToUnit(TemperatureGradientUnit.DegreeCelsiusPerKilometer)); - unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerMeter, quantity => quantity.ToUnit(TemperatureGradientUnit.DegreeCelsiusPerMeter)); - unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeFahrenheitPerFoot, quantity => quantity.ToUnit(TemperatureGradientUnit.DegreeFahrenheitPerFoot)); + unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerKilometer, quantity => new TemperatureGradient(quantity.Value * 1e3, TemperatureGradientUnit.DegreeCelsiusPerKilometer)); + unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerMeter, quantity => new TemperatureGradient(quantity.Value, TemperatureGradientUnit.DegreeCelsiusPerMeter)); + unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeFahrenheitPerFoot, quantity => new TemperatureGradient((quantity.Value * 0.3048) * 9/5, TemperatureGradientUnit.DegreeFahrenheitPerFoot)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity); // Register in unit converter: TemperatureGradientUnit -> BaseUnit - unitConverter.SetConversionFunction(TemperatureGradientUnit.DegreeCelsiusPerKilometer, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureGradientUnit.DegreeCelsiusPerMeter, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TemperatureGradientUnit.DegreeFahrenheitPerFoot, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(TemperatureGradientUnit.DegreeCelsiusPerKilometer, TemperatureGradientUnit.KelvinPerMeter, quantity => new TemperatureGradient(quantity.Value / 1e3, TemperatureGradientUnit.KelvinPerMeter)); + unitConverter.SetConversionFunction(TemperatureGradientUnit.DegreeCelsiusPerMeter, TemperatureGradientUnit.KelvinPerMeter, quantity => new TemperatureGradient(quantity.Value, TemperatureGradientUnit.KelvinPerMeter)); + unitConverter.SetConversionFunction(TemperatureGradientUnit.DegreeFahrenheitPerFoot, TemperatureGradientUnit.KelvinPerMeter, quantity => new TemperatureGradient((quantity.Value / 0.3048) * 5/9, TemperatureGradientUnit.KelvinPerMeter)); } /// @@ -667,11 +674,42 @@ double IQuantity.As(Enum unit) /// /// Converts this TemperatureGradient to another TemperatureGradient with the unit representation . /// + /// The unit to convert to. /// A TemperatureGradient with the specified unit. public TemperatureGradient ToUnit(TemperatureGradientUnit unit) { - var convertedValue = GetValueAs(unit); - return new TemperatureGradient(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this TemperatureGradient to another TemperatureGradient using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A TemperatureGradient with the specified unit. + public TemperatureGradient ToUnit(TemperatureGradientUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(TemperatureGradient), Unit, typeof(TemperatureGradient), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (TemperatureGradient)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -680,7 +718,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is TemperatureGradientUnit unitAsTemperatureGradientUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureGradientUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTemperatureGradientUnit); + return ToUnit(unitAsTemperatureGradientUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is TemperatureGradientUnit unitAsTemperatureGradientUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureGradientUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsTemperatureGradientUnit, unitConverter); } /// @@ -705,53 +752,15 @@ public TemperatureGradient ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(TemperatureGradientUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case TemperatureGradientUnit.DegreeCelsiusPerKilometer: return _value / 1e3; - case TemperatureGradientUnit.DegreeCelsiusPerMeter: return _value; - case TemperatureGradientUnit.DegreeFahrenheitPerFoot: return (_value / 0.3048) * 5/9; - case TemperatureGradientUnit.KelvinPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(TemperatureGradientUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal TemperatureGradient ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new TemperatureGradient(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(TemperatureGradientUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case TemperatureGradientUnit.DegreeCelsiusPerKilometer: return baseUnitValue * 1e3; - case TemperatureGradientUnit.DegreeCelsiusPerMeter: return baseUnitValue; - case TemperatureGradientUnit.DegreeFahrenheitPerFoot: return (baseUnitValue * 0.3048) * 9/5; - case TemperatureGradientUnit.KelvinPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs index d290e53dce..8a8c92f774 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs @@ -69,6 +69,8 @@ static ThermalConductivity() new UnitInfo(ThermalConductivityUnit.WattPerMeterKelvin, "WattsPerMeterKelvin", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ThermalConductivity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -107,6 +109,11 @@ public ThermalConductivity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -204,13 +211,13 @@ public ThermalConductivity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ThermalConductivityUnit - unitConverter.SetConversionFunction(ThermalConductivityUnit.WattPerMeterKelvin, ThermalConductivityUnit.BtuPerHourFootFahrenheit, quantity => quantity.ToUnit(ThermalConductivityUnit.BtuPerHourFootFahrenheit)); + unitConverter.SetConversionFunction(ThermalConductivityUnit.WattPerMeterKelvin, ThermalConductivityUnit.BtuPerHourFootFahrenheit, quantity => new ThermalConductivity(quantity.Value/1.73073467, ThermalConductivityUnit.BtuPerHourFootFahrenheit)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ThermalConductivityUnit.WattPerMeterKelvin, ThermalConductivityUnit.WattPerMeterKelvin, quantity => quantity); // Register in unit converter: ThermalConductivityUnit -> BaseUnit - unitConverter.SetConversionFunction(ThermalConductivityUnit.BtuPerHourFootFahrenheit, ThermalConductivityUnit.WattPerMeterKelvin, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ThermalConductivityUnit.BtuPerHourFootFahrenheit, ThermalConductivityUnit.WattPerMeterKelvin, quantity => new ThermalConductivity(quantity.Value*1.73073467, ThermalConductivityUnit.WattPerMeterKelvin)); } /// @@ -636,11 +643,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ThermalConductivity to another ThermalConductivity with the unit representation . /// + /// The unit to convert to. /// A ThermalConductivity with the specified unit. public ThermalConductivity ToUnit(ThermalConductivityUnit unit) { - var convertedValue = GetValueAs(unit); - return new ThermalConductivity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ThermalConductivity to another ThermalConductivity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ThermalConductivity with the specified unit. + public ThermalConductivity ToUnit(ThermalConductivityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ThermalConductivity), Unit, typeof(ThermalConductivity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ThermalConductivity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -649,7 +687,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ThermalConductivityUnit unitAsThermalConductivityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalConductivityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsThermalConductivityUnit); + return ToUnit(unitAsThermalConductivityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ThermalConductivityUnit unitAsThermalConductivityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalConductivityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsThermalConductivityUnit, unitConverter); } /// @@ -674,49 +721,15 @@ public ThermalConductivity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ThermalConductivityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ThermalConductivityUnit.BtuPerHourFootFahrenheit: return _value*1.73073467; - case ThermalConductivityUnit.WattPerMeterKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ThermalConductivityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ThermalConductivity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ThermalConductivity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ThermalConductivityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ThermalConductivityUnit.BtuPerHourFootFahrenheit: return baseUnitValue/1.73073467; - case ThermalConductivityUnit.WattPerMeterKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs index f04676f1da..a4940c6b83 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs @@ -70,6 +70,8 @@ static ThermalResistance() new UnitInfo(ThermalResistanceUnit.SquareMeterKelvinPerWatt, "SquareMeterKelvinsPerWatt", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.ThermalResistance); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -108,6 +110,11 @@ public ThermalResistance(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -225,21 +232,21 @@ public ThermalResistance(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> ThermalResistanceUnit - unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, quantity => quantity.ToUnit(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu)); - unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie)); - unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt)); - unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt)); - unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterKelvinPerWatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerWatt)); + unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, quantity => new ThermalResistance(quantity.Value/176.1121482159839, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu)); + unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, quantity => new ThermalResistance(quantity.Value/0.0859779507590433, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie)); + unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, quantity => new ThermalResistance(quantity.Value/0.0999964777570357, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt)); + unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, quantity => new ThermalResistance(quantity.Value/1000.088056074108, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt)); + unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterKelvinPerWatt, quantity => new ThermalResistance(quantity.Value/1000, ThermalResistanceUnit.SquareMeterKelvinPerWatt)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity); // Register in unit converter: ThermalResistanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => new ThermalResistance(quantity.Value*176.1121482159839, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); + unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => new ThermalResistance(quantity.Value*0.0859779507590433, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); + unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => new ThermalResistance(quantity.Value*0.0999964777570357, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); + unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => new ThermalResistance(quantity.Value*1000.088056074108, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); + unitConverter.SetConversionFunction(ThermalResistanceUnit.SquareMeterKelvinPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => new ThermalResistance(quantity.Value*1000, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); } /// @@ -701,11 +708,42 @@ double IQuantity.As(Enum unit) /// /// Converts this ThermalResistance to another ThermalResistance with the unit representation . /// + /// The unit to convert to. /// A ThermalResistance with the specified unit. public ThermalResistance ToUnit(ThermalResistanceUnit unit) { - var convertedValue = GetValueAs(unit); - return new ThermalResistance(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this ThermalResistance to another ThermalResistance using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A ThermalResistance with the specified unit. + public ThermalResistance ToUnit(ThermalResistanceUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(ThermalResistance), Unit, typeof(ThermalResistance), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (ThermalResistance)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -714,7 +752,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is ThermalResistanceUnit unitAsThermalResistanceUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalResistanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsThermalResistanceUnit); + return ToUnit(unitAsThermalResistanceUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is ThermalResistanceUnit unitAsThermalResistanceUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalResistanceUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsThermalResistanceUnit, unitConverter); } /// @@ -739,57 +786,15 @@ public ThermalResistance ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(ThermalResistanceUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return _value*176.1121482159839; - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return _value*0.0859779507590433; - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return _value*0.0999964777570357; - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return _value*1000.088056074108; - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return _value; - case ThermalResistanceUnit.SquareMeterKelvinPerWatt: return _value*1000; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(ThermalResistanceUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal ThermalResistance ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new ThermalResistance(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(ThermalResistanceUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return baseUnitValue/176.1121482159839; - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return baseUnitValue/0.0859779507590433; - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return baseUnitValue/0.0999964777570357; - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return baseUnitValue/1000.088056074108; - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return baseUnitValue; - case ThermalResistanceUnit.SquareMeterKelvinPerWatt: return baseUnitValue/1000; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs index 99f881c081..058123a677 100644 --- a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs @@ -89,6 +89,8 @@ static Torque() new UnitInfo(TorqueUnit.TonneForceMillimeter, "TonneForceMillimeters", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Torque); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -127,6 +129,11 @@ public Torque(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -339,59 +346,59 @@ public Torque(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> TorqueUnit - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.GramForceCentimeter, quantity => quantity.ToUnit(TorqueUnit.GramForceCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.GramForceMeter, quantity => quantity.ToUnit(TorqueUnit.GramForceMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.GramForceMillimeter, quantity => quantity.ToUnit(TorqueUnit.GramForceMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceCentimeter, quantity => quantity.ToUnit(TorqueUnit.KilogramForceCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMeter, quantity => quantity.ToUnit(TorqueUnit.KilogramForceMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMillimeter, quantity => quantity.ToUnit(TorqueUnit.KilogramForceMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonCentimeter, quantity => quantity.ToUnit(TorqueUnit.KilonewtonCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMeter, quantity => quantity.ToUnit(TorqueUnit.KilonewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMillimeter, quantity => quantity.ToUnit(TorqueUnit.KilonewtonMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceFoot, quantity => quantity.ToUnit(TorqueUnit.KilopoundForceFoot)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceInch, quantity => quantity.ToUnit(TorqueUnit.KilopoundForceInch)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonCentimeter, quantity => quantity.ToUnit(TorqueUnit.MeganewtonCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMeter, quantity => quantity.ToUnit(TorqueUnit.MeganewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMillimeter, quantity => quantity.ToUnit(TorqueUnit.MeganewtonMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceFoot, quantity => quantity.ToUnit(TorqueUnit.MegapoundForceFoot)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceInch, quantity => quantity.ToUnit(TorqueUnit.MegapoundForceInch)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.NewtonCentimeter, quantity => quantity.ToUnit(TorqueUnit.NewtonCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.NewtonMillimeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.PoundalFoot, quantity => quantity.ToUnit(TorqueUnit.PoundalFoot)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.PoundForceFoot, quantity => quantity.ToUnit(TorqueUnit.PoundForceFoot)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.PoundForceInch, quantity => quantity.ToUnit(TorqueUnit.PoundForceInch)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceCentimeter, quantity => quantity.ToUnit(TorqueUnit.TonneForceCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMeter, quantity => quantity.ToUnit(TorqueUnit.TonneForceMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMillimeter, quantity => quantity.ToUnit(TorqueUnit.TonneForceMillimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.GramForceCentimeter, quantity => new Torque(quantity.Value/9.80665e-5, TorqueUnit.GramForceCentimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.GramForceMeter, quantity => new Torque(quantity.Value/9.80665e-3, TorqueUnit.GramForceMeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.GramForceMillimeter, quantity => new Torque(quantity.Value/9.80665e-6, TorqueUnit.GramForceMillimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceCentimeter, quantity => new Torque(quantity.Value/9.80665e-2, TorqueUnit.KilogramForceCentimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMeter, quantity => new Torque(quantity.Value/9.80665, TorqueUnit.KilogramForceMeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMillimeter, quantity => new Torque(quantity.Value/9.80665e-3, TorqueUnit.KilogramForceMillimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonCentimeter, quantity => new Torque((quantity.Value*100) / 1e3d, TorqueUnit.KilonewtonCentimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMeter, quantity => new Torque((quantity.Value) / 1e3d, TorqueUnit.KilonewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMillimeter, quantity => new Torque((quantity.Value*1000) / 1e3d, TorqueUnit.KilonewtonMillimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceFoot, quantity => new Torque((quantity.Value/1.3558179483314) / 1e3d, TorqueUnit.KilopoundForceFoot)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceInch, quantity => new Torque((quantity.Value/1.129848290276167e-1) / 1e3d, TorqueUnit.KilopoundForceInch)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonCentimeter, quantity => new Torque((quantity.Value*100) / 1e6d, TorqueUnit.MeganewtonCentimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMeter, quantity => new Torque((quantity.Value) / 1e6d, TorqueUnit.MeganewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMillimeter, quantity => new Torque((quantity.Value*1000) / 1e6d, TorqueUnit.MeganewtonMillimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceFoot, quantity => new Torque((quantity.Value/1.3558179483314) / 1e6d, TorqueUnit.MegapoundForceFoot)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceInch, quantity => new Torque((quantity.Value/1.129848290276167e-1) / 1e6d, TorqueUnit.MegapoundForceInch)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.NewtonCentimeter, quantity => new Torque(quantity.Value*100, TorqueUnit.NewtonCentimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.NewtonMillimeter, quantity => new Torque(quantity.Value*1000, TorqueUnit.NewtonMillimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.PoundalFoot, quantity => new Torque(quantity.Value/4.21401100938048e-2, TorqueUnit.PoundalFoot)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.PoundForceFoot, quantity => new Torque(quantity.Value/1.3558179483314, TorqueUnit.PoundForceFoot)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.PoundForceInch, quantity => new Torque(quantity.Value/1.129848290276167e-1, TorqueUnit.PoundForceInch)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceCentimeter, quantity => new Torque(quantity.Value/9.80665e1, TorqueUnit.TonneForceCentimeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMeter, quantity => new Torque(quantity.Value/9.80665e3, TorqueUnit.TonneForceMeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMillimeter, quantity => new Torque(quantity.Value/9.80665, TorqueUnit.TonneForceMillimeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.NewtonMeter, quantity => quantity); // Register in unit converter: TorqueUnit -> BaseUnit - unitConverter.SetConversionFunction(TorqueUnit.GramForceCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.GramForceMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.GramForceMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.KilogramForceCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.KilogramForceMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.KilogramForceMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.KilonewtonCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.KilonewtonMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.KilonewtonMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.KilopoundForceFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.KilopoundForceInch, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.MeganewtonCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.MeganewtonMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.MeganewtonMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.MegapoundForceFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.MegapoundForceInch, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.NewtonCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.PoundalFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.PoundForceFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.PoundForceInch, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.TonneForceCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.TonneForceMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorqueUnit.TonneForceMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(TorqueUnit.GramForceCentimeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*9.80665e-5, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.GramForceMeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*9.80665e-3, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.GramForceMillimeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*9.80665e-6, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.KilogramForceCentimeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*9.80665e-2, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.KilogramForceMeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*9.80665, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.KilogramForceMillimeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*9.80665e-3, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.KilonewtonCentimeter, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value*0.01) * 1e3d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.KilonewtonMeter, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value) * 1e3d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.KilonewtonMillimeter, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value*0.001) * 1e3d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.KilopoundForceFoot, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value*1.3558179483314) * 1e3d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.KilopoundForceInch, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value*1.129848290276167e-1) * 1e3d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.MeganewtonCentimeter, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value*0.01) * 1e6d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.MeganewtonMeter, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value) * 1e6d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.MeganewtonMillimeter, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value*0.001) * 1e6d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.MegapoundForceFoot, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value*1.3558179483314) * 1e6d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.MegapoundForceInch, TorqueUnit.NewtonMeter, quantity => new Torque((quantity.Value*1.129848290276167e-1) * 1e6d, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonCentimeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*0.01, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.NewtonMillimeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*0.001, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.PoundalFoot, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*4.21401100938048e-2, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.PoundForceFoot, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*1.3558179483314, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.PoundForceInch, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*1.129848290276167e-1, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.TonneForceCentimeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*9.80665e1, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.TonneForceMeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*9.80665e3, TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction(TorqueUnit.TonneForceMillimeter, TorqueUnit.NewtonMeter, quantity => new Torque(quantity.Value*9.80665, TorqueUnit.NewtonMeter)); } /// @@ -1024,11 +1031,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Torque to another Torque with the unit representation . /// + /// The unit to convert to. /// A Torque with the specified unit. public Torque ToUnit(TorqueUnit unit) { - var convertedValue = GetValueAs(unit); - return new Torque(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Torque to another Torque using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Torque with the specified unit. + public Torque ToUnit(TorqueUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Torque), Unit, typeof(Torque), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Torque)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1037,7 +1075,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is TorqueUnit unitAsTorqueUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorqueUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTorqueUnit); + return ToUnit(unitAsTorqueUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is TorqueUnit unitAsTorqueUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorqueUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsTorqueUnit, unitConverter); } /// @@ -1062,95 +1109,15 @@ public Torque ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(TorqueUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case TorqueUnit.GramForceCentimeter: return _value*9.80665e-5; - case TorqueUnit.GramForceMeter: return _value*9.80665e-3; - case TorqueUnit.GramForceMillimeter: return _value*9.80665e-6; - case TorqueUnit.KilogramForceCentimeter: return _value*9.80665e-2; - case TorqueUnit.KilogramForceMeter: return _value*9.80665; - case TorqueUnit.KilogramForceMillimeter: return _value*9.80665e-3; - case TorqueUnit.KilonewtonCentimeter: return (_value*0.01) * 1e3d; - case TorqueUnit.KilonewtonMeter: return (_value) * 1e3d; - case TorqueUnit.KilonewtonMillimeter: return (_value*0.001) * 1e3d; - case TorqueUnit.KilopoundForceFoot: return (_value*1.3558179483314) * 1e3d; - case TorqueUnit.KilopoundForceInch: return (_value*1.129848290276167e-1) * 1e3d; - case TorqueUnit.MeganewtonCentimeter: return (_value*0.01) * 1e6d; - case TorqueUnit.MeganewtonMeter: return (_value) * 1e6d; - case TorqueUnit.MeganewtonMillimeter: return (_value*0.001) * 1e6d; - case TorqueUnit.MegapoundForceFoot: return (_value*1.3558179483314) * 1e6d; - case TorqueUnit.MegapoundForceInch: return (_value*1.129848290276167e-1) * 1e6d; - case TorqueUnit.NewtonCentimeter: return _value*0.01; - case TorqueUnit.NewtonMeter: return _value; - case TorqueUnit.NewtonMillimeter: return _value*0.001; - case TorqueUnit.PoundalFoot: return _value*4.21401100938048e-2; - case TorqueUnit.PoundForceFoot: return _value*1.3558179483314; - case TorqueUnit.PoundForceInch: return _value*1.129848290276167e-1; - case TorqueUnit.TonneForceCentimeter: return _value*9.80665e1; - case TorqueUnit.TonneForceMeter: return _value*9.80665e3; - case TorqueUnit.TonneForceMillimeter: return _value*9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(TorqueUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Torque ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Torque(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(TorqueUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case TorqueUnit.GramForceCentimeter: return baseUnitValue/9.80665e-5; - case TorqueUnit.GramForceMeter: return baseUnitValue/9.80665e-3; - case TorqueUnit.GramForceMillimeter: return baseUnitValue/9.80665e-6; - case TorqueUnit.KilogramForceCentimeter: return baseUnitValue/9.80665e-2; - case TorqueUnit.KilogramForceMeter: return baseUnitValue/9.80665; - case TorqueUnit.KilogramForceMillimeter: return baseUnitValue/9.80665e-3; - case TorqueUnit.KilonewtonCentimeter: return (baseUnitValue*100) / 1e3d; - case TorqueUnit.KilonewtonMeter: return (baseUnitValue) / 1e3d; - case TorqueUnit.KilonewtonMillimeter: return (baseUnitValue*1000) / 1e3d; - case TorqueUnit.KilopoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e3d; - case TorqueUnit.KilopoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e3d; - case TorqueUnit.MeganewtonCentimeter: return (baseUnitValue*100) / 1e6d; - case TorqueUnit.MeganewtonMeter: return (baseUnitValue) / 1e6d; - case TorqueUnit.MeganewtonMillimeter: return (baseUnitValue*1000) / 1e6d; - case TorqueUnit.MegapoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e6d; - case TorqueUnit.MegapoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e6d; - case TorqueUnit.NewtonCentimeter: return baseUnitValue*100; - case TorqueUnit.NewtonMeter: return baseUnitValue; - case TorqueUnit.NewtonMillimeter: return baseUnitValue*1000; - case TorqueUnit.PoundalFoot: return baseUnitValue/4.21401100938048e-2; - case TorqueUnit.PoundForceFoot: return baseUnitValue/1.3558179483314; - case TorqueUnit.PoundForceInch: return baseUnitValue/1.129848290276167e-1; - case TorqueUnit.TonneForceCentimeter: return baseUnitValue/9.80665e1; - case TorqueUnit.TonneForceMeter: return baseUnitValue/9.80665e3; - case TorqueUnit.TonneForceMillimeter: return baseUnitValue/9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs index 08b1d13b0c..6abd534194 100644 --- a/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs @@ -85,6 +85,8 @@ static TorquePerLength() new UnitInfo(TorquePerLengthUnit.TonneForceMillimeterPerMeter, "TonneForceMillimetersPerMeter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.TorquePerLength); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -123,6 +125,11 @@ public TorquePerLength(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -315,51 +322,51 @@ public TorquePerLength(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> TorquePerLengthUnit - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilogramForceCentimeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilogramForceMeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilogramForceMillimeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilonewtonCentimeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilonewtonMeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilonewtonMillimeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilopoundForceFootPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.KilopoundForceFootPerFoot)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilopoundForceInchPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.KilopoundForceInchPerFoot)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.MeganewtonCentimeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.MeganewtonMeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.MeganewtonMillimeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MegapoundForceFootPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.MegapoundForceFootPerFoot)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MegapoundForceInchPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.MegapoundForceInchPerFoot)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonCentimeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMillimeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.PoundForceFootPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.PoundForceFootPerFoot)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.PoundForceInchPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.PoundForceInchPerFoot)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.TonneForceCentimeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.TonneForceMeterPerMeter)); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.TonneForceMillimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceCentimeterPerMeter, quantity => new TorquePerLength(quantity.Value*10.1971619222242, TorquePerLengthUnit.KilogramForceCentimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceMeterPerMeter, quantity => new TorquePerLength(quantity.Value*0.101971619222242, TorquePerLengthUnit.KilogramForceMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceMillimeterPerMeter, quantity => new TorquePerLength(quantity.Value*101.971619222242, TorquePerLengthUnit.KilogramForceMillimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonCentimeterPerMeter, quantity => new TorquePerLength((quantity.Value*100) / 1e3d, TorquePerLengthUnit.KilonewtonCentimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value) / 1e3d, TorquePerLengthUnit.KilonewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonMillimeterPerMeter, quantity => new TorquePerLength((quantity.Value*1000) / 1e3d, TorquePerLengthUnit.KilonewtonMillimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilopoundForceFootPerFoot, quantity => new TorquePerLength((quantity.Value/4.44822161526) / 1e3d, TorquePerLengthUnit.KilopoundForceFootPerFoot)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilopoundForceInchPerFoot, quantity => new TorquePerLength((quantity.Value/0.370685147638) / 1e3d, TorquePerLengthUnit.KilopoundForceInchPerFoot)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonCentimeterPerMeter, quantity => new TorquePerLength((quantity.Value*100) / 1e6d, TorquePerLengthUnit.MeganewtonCentimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value) / 1e6d, TorquePerLengthUnit.MeganewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonMillimeterPerMeter, quantity => new TorquePerLength((quantity.Value*1000) / 1e6d, TorquePerLengthUnit.MeganewtonMillimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MegapoundForceFootPerFoot, quantity => new TorquePerLength((quantity.Value/4.44822161526) / 1e6d, TorquePerLengthUnit.MegapoundForceFootPerFoot)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MegapoundForceInchPerFoot, quantity => new TorquePerLength((quantity.Value/0.370685147638) / 1e6d, TorquePerLengthUnit.MegapoundForceInchPerFoot)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonCentimeterPerMeter, quantity => new TorquePerLength(quantity.Value*100, TorquePerLengthUnit.NewtonCentimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonMillimeterPerMeter, quantity => new TorquePerLength(quantity.Value*1000, TorquePerLengthUnit.NewtonMillimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.PoundForceFootPerFoot, quantity => new TorquePerLength(quantity.Value/4.44822161526, TorquePerLengthUnit.PoundForceFootPerFoot)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.PoundForceInchPerFoot, quantity => new TorquePerLength(quantity.Value/0.370685147638, TorquePerLengthUnit.PoundForceInchPerFoot)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceCentimeterPerMeter, quantity => new TorquePerLength(quantity.Value*0.0101971619222242, TorquePerLengthUnit.TonneForceCentimeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceMeterPerMeter, quantity => new TorquePerLength(quantity.Value*0.000101971619222242, TorquePerLengthUnit.TonneForceMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceMillimeterPerMeter, quantity => new TorquePerLength(quantity.Value*0.101971619222242, TorquePerLengthUnit.TonneForceMillimeterPerMeter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity); // Register in unit converter: TorquePerLengthUnit -> BaseUnit - unitConverter.SetConversionFunction(TorquePerLengthUnit.KilogramForceCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.KilogramForceMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.KilogramForceMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.KilonewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.KilonewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.KilonewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.KilopoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.KilopoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.MeganewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.MeganewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.MeganewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.MegapoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.MegapoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.PoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.PoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.TonneForceCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.TonneForceMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(TorquePerLengthUnit.TonneForceMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(TorquePerLengthUnit.KilogramForceCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*0.0980665019960652, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.KilogramForceMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*9.80665019960652, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.KilogramForceMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*0.00980665019960652, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.KilonewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value*0.01) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.KilonewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.KilonewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value*0.001) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.KilopoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value*4.44822161526) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.KilopoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value*0.370685147638) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.MeganewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value*0.01) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.MeganewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.MeganewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value*0.001) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.MegapoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value*4.44822161526) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.MegapoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength((quantity.Value*0.370685147638) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*0.01, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.NewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*0.001, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.PoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*4.44822161526, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.PoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*0.370685147638, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.TonneForceCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*98.0665019960652, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.TonneForceMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*9806.65019960653, TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction(TorquePerLengthUnit.TonneForceMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => new TorquePerLength(quantity.Value*9.80665019960652, TorquePerLengthUnit.NewtonMeterPerMeter)); } /// @@ -956,11 +963,42 @@ double IQuantity.As(Enum unit) /// /// Converts this TorquePerLength to another TorquePerLength with the unit representation . /// + /// The unit to convert to. /// A TorquePerLength with the specified unit. public TorquePerLength ToUnit(TorquePerLengthUnit unit) { - var convertedValue = GetValueAs(unit); - return new TorquePerLength(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this TorquePerLength to another TorquePerLength using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A TorquePerLength with the specified unit. + public TorquePerLength ToUnit(TorquePerLengthUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(TorquePerLength), Unit, typeof(TorquePerLength), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (TorquePerLength)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -969,7 +1007,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is TorquePerLengthUnit unitAsTorquePerLengthUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorquePerLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTorquePerLengthUnit); + return ToUnit(unitAsTorquePerLengthUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is TorquePerLengthUnit unitAsTorquePerLengthUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorquePerLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsTorquePerLengthUnit, unitConverter); } /// @@ -994,87 +1041,15 @@ public TorquePerLength ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(TorquePerLengthUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case TorquePerLengthUnit.KilogramForceCentimeterPerMeter: return _value*0.0980665019960652; - case TorquePerLengthUnit.KilogramForceMeterPerMeter: return _value*9.80665019960652; - case TorquePerLengthUnit.KilogramForceMillimeterPerMeter: return _value*0.00980665019960652; - case TorquePerLengthUnit.KilonewtonCentimeterPerMeter: return (_value*0.01) * 1e3d; - case TorquePerLengthUnit.KilonewtonMeterPerMeter: return (_value) * 1e3d; - case TorquePerLengthUnit.KilonewtonMillimeterPerMeter: return (_value*0.001) * 1e3d; - case TorquePerLengthUnit.KilopoundForceFootPerFoot: return (_value*4.44822161526) * 1e3d; - case TorquePerLengthUnit.KilopoundForceInchPerFoot: return (_value*0.370685147638) * 1e3d; - case TorquePerLengthUnit.MeganewtonCentimeterPerMeter: return (_value*0.01) * 1e6d; - case TorquePerLengthUnit.MeganewtonMeterPerMeter: return (_value) * 1e6d; - case TorquePerLengthUnit.MeganewtonMillimeterPerMeter: return (_value*0.001) * 1e6d; - case TorquePerLengthUnit.MegapoundForceFootPerFoot: return (_value*4.44822161526) * 1e6d; - case TorquePerLengthUnit.MegapoundForceInchPerFoot: return (_value*0.370685147638) * 1e6d; - case TorquePerLengthUnit.NewtonCentimeterPerMeter: return _value*0.01; - case TorquePerLengthUnit.NewtonMeterPerMeter: return _value; - case TorquePerLengthUnit.NewtonMillimeterPerMeter: return _value*0.001; - case TorquePerLengthUnit.PoundForceFootPerFoot: return _value*4.44822161526; - case TorquePerLengthUnit.PoundForceInchPerFoot: return _value*0.370685147638; - case TorquePerLengthUnit.TonneForceCentimeterPerMeter: return _value*98.0665019960652; - case TorquePerLengthUnit.TonneForceMeterPerMeter: return _value*9806.65019960653; - case TorquePerLengthUnit.TonneForceMillimeterPerMeter: return _value*9.80665019960652; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(TorquePerLengthUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal TorquePerLength ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new TorquePerLength(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(TorquePerLengthUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case TorquePerLengthUnit.KilogramForceCentimeterPerMeter: return baseUnitValue*10.1971619222242; - case TorquePerLengthUnit.KilogramForceMeterPerMeter: return baseUnitValue*0.101971619222242; - case TorquePerLengthUnit.KilogramForceMillimeterPerMeter: return baseUnitValue*101.971619222242; - case TorquePerLengthUnit.KilonewtonCentimeterPerMeter: return (baseUnitValue*100) / 1e3d; - case TorquePerLengthUnit.KilonewtonMeterPerMeter: return (baseUnitValue) / 1e3d; - case TorquePerLengthUnit.KilonewtonMillimeterPerMeter: return (baseUnitValue*1000) / 1e3d; - case TorquePerLengthUnit.KilopoundForceFootPerFoot: return (baseUnitValue/4.44822161526) / 1e3d; - case TorquePerLengthUnit.KilopoundForceInchPerFoot: return (baseUnitValue/0.370685147638) / 1e3d; - case TorquePerLengthUnit.MeganewtonCentimeterPerMeter: return (baseUnitValue*100) / 1e6d; - case TorquePerLengthUnit.MeganewtonMeterPerMeter: return (baseUnitValue) / 1e6d; - case TorquePerLengthUnit.MeganewtonMillimeterPerMeter: return (baseUnitValue*1000) / 1e6d; - case TorquePerLengthUnit.MegapoundForceFootPerFoot: return (baseUnitValue/4.44822161526) / 1e6d; - case TorquePerLengthUnit.MegapoundForceInchPerFoot: return (baseUnitValue/0.370685147638) / 1e6d; - case TorquePerLengthUnit.NewtonCentimeterPerMeter: return baseUnitValue*100; - case TorquePerLengthUnit.NewtonMeterPerMeter: return baseUnitValue; - case TorquePerLengthUnit.NewtonMillimeterPerMeter: return baseUnitValue*1000; - case TorquePerLengthUnit.PoundForceFootPerFoot: return baseUnitValue/4.44822161526; - case TorquePerLengthUnit.PoundForceInchPerFoot: return baseUnitValue/0.370685147638; - case TorquePerLengthUnit.TonneForceCentimeterPerMeter: return baseUnitValue*0.0101971619222242; - case TorquePerLengthUnit.TonneForceMeterPerMeter: return baseUnitValue*0.000101971619222242; - case TorquePerLengthUnit.TonneForceMillimeterPerMeter: return baseUnitValue*0.101971619222242; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs index 6b4aaa9a4d..41528464f1 100644 --- a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs @@ -68,6 +68,8 @@ static Turbidity() new UnitInfo(TurbidityUnit.NTU, "NTU", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Turbidity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -106,6 +108,11 @@ public Turbidity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -619,11 +626,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Turbidity to another Turbidity with the unit representation . /// + /// The unit to convert to. /// A Turbidity with the specified unit. public Turbidity ToUnit(TurbidityUnit unit) { - var convertedValue = GetValueAs(unit); - return new Turbidity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Turbidity to another Turbidity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Turbidity with the specified unit. + public Turbidity ToUnit(TurbidityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Turbidity), Unit, typeof(Turbidity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Turbidity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -632,7 +670,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is TurbidityUnit unitAsTurbidityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TurbidityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTurbidityUnit); + return ToUnit(unitAsTurbidityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is TurbidityUnit unitAsTurbidityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TurbidityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsTurbidityUnit, unitConverter); } /// @@ -657,47 +704,15 @@ public Turbidity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(TurbidityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case TurbidityUnit.NTU: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(TurbidityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Turbidity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Turbidity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(TurbidityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case TurbidityUnit.NTU: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs index cf9ed92322..e0b0f0544c 100644 --- a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs @@ -65,6 +65,8 @@ static VitaminA() new UnitInfo(VitaminAUnit.InternationalUnit, "InternationalUnits", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.VitaminA); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -103,6 +105,11 @@ public VitaminA(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -616,11 +623,42 @@ double IQuantity.As(Enum unit) /// /// Converts this VitaminA to another VitaminA with the unit representation . /// + /// The unit to convert to. /// A VitaminA with the specified unit. public VitaminA ToUnit(VitaminAUnit unit) { - var convertedValue = GetValueAs(unit); - return new VitaminA(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this VitaminA to another VitaminA using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A VitaminA with the specified unit. + public VitaminA ToUnit(VitaminAUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(VitaminA), Unit, typeof(VitaminA), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (VitaminA)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -629,7 +667,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is VitaminAUnit unitAsVitaminAUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VitaminAUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVitaminAUnit); + return ToUnit(unitAsVitaminAUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is VitaminAUnit unitAsVitaminAUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VitaminAUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsVitaminAUnit, unitConverter); } /// @@ -654,47 +701,15 @@ public VitaminA ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(VitaminAUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case VitaminAUnit.InternationalUnit: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(VitaminAUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal VitaminA ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new VitaminA(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(VitaminAUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case VitaminAUnit.InternationalUnit: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs index a15666fab2..2de64ccd3c 100644 --- a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs @@ -115,6 +115,8 @@ static Volume() new UnitInfo(VolumeUnit.UsTeaspoon, "UsTeaspoons", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Volume); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -153,6 +155,11 @@ public Volume(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -495,111 +502,111 @@ public Volume(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> VolumeUnit - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.AcreFoot, quantity => quantity.ToUnit(VolumeUnit.AcreFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.AuTablespoon, quantity => quantity.ToUnit(VolumeUnit.AuTablespoon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.BoardFoot, quantity => quantity.ToUnit(VolumeUnit.BoardFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Centiliter, quantity => quantity.ToUnit(VolumeUnit.Centiliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicCentimeter, quantity => quantity.ToUnit(VolumeUnit.CubicCentimeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicDecimeter, quantity => quantity.ToUnit(VolumeUnit.CubicDecimeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicFoot, quantity => quantity.ToUnit(VolumeUnit.CubicFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicHectometer, quantity => quantity.ToUnit(VolumeUnit.CubicHectometer)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicInch, quantity => quantity.ToUnit(VolumeUnit.CubicInch)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicKilometer, quantity => quantity.ToUnit(VolumeUnit.CubicKilometer)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMicrometer, quantity => quantity.ToUnit(VolumeUnit.CubicMicrometer)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMile, quantity => quantity.ToUnit(VolumeUnit.CubicMile)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMillimeter, quantity => quantity.ToUnit(VolumeUnit.CubicMillimeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicYard, quantity => quantity.ToUnit(VolumeUnit.CubicYard)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.DecausGallon, quantity => quantity.ToUnit(VolumeUnit.DecausGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Deciliter, quantity => quantity.ToUnit(VolumeUnit.Deciliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.DeciusGallon, quantity => quantity.ToUnit(VolumeUnit.DeciusGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.HectocubicFoot, quantity => quantity.ToUnit(VolumeUnit.HectocubicFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.HectocubicMeter, quantity => quantity.ToUnit(VolumeUnit.HectocubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Hectoliter, quantity => quantity.ToUnit(VolumeUnit.Hectoliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.HectousGallon, quantity => quantity.ToUnit(VolumeUnit.HectousGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialBeerBarrel, quantity => quantity.ToUnit(VolumeUnit.ImperialBeerBarrel)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialGallon, quantity => quantity.ToUnit(VolumeUnit.ImperialGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialOunce, quantity => quantity.ToUnit(VolumeUnit.ImperialOunce)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialPint, quantity => quantity.ToUnit(VolumeUnit.ImperialPint)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KilocubicFoot, quantity => quantity.ToUnit(VolumeUnit.KilocubicFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KilocubicMeter, quantity => quantity.ToUnit(VolumeUnit.KilocubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KiloimperialGallon, quantity => quantity.ToUnit(VolumeUnit.KiloimperialGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Kiloliter, quantity => quantity.ToUnit(VolumeUnit.Kiloliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KilousGallon, quantity => quantity.ToUnit(VolumeUnit.KilousGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Liter, quantity => quantity.ToUnit(VolumeUnit.Liter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MegacubicFoot, quantity => quantity.ToUnit(VolumeUnit.MegacubicFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MegaimperialGallon, quantity => quantity.ToUnit(VolumeUnit.MegaimperialGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Megaliter, quantity => quantity.ToUnit(VolumeUnit.Megaliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MegausGallon, quantity => quantity.ToUnit(VolumeUnit.MegausGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MetricCup, quantity => quantity.ToUnit(VolumeUnit.MetricCup)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MetricTeaspoon, quantity => quantity.ToUnit(VolumeUnit.MetricTeaspoon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Microliter, quantity => quantity.ToUnit(VolumeUnit.Microliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Milliliter, quantity => quantity.ToUnit(VolumeUnit.Milliliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.OilBarrel, quantity => quantity.ToUnit(VolumeUnit.OilBarrel)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UkTablespoon, quantity => quantity.ToUnit(VolumeUnit.UkTablespoon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsBeerBarrel, quantity => quantity.ToUnit(VolumeUnit.UsBeerBarrel)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsCustomaryCup, quantity => quantity.ToUnit(VolumeUnit.UsCustomaryCup)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsGallon, quantity => quantity.ToUnit(VolumeUnit.UsGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsLegalCup, quantity => quantity.ToUnit(VolumeUnit.UsLegalCup)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsOunce, quantity => quantity.ToUnit(VolumeUnit.UsOunce)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsPint, quantity => quantity.ToUnit(VolumeUnit.UsPint)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsQuart, quantity => quantity.ToUnit(VolumeUnit.UsQuart)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsTablespoon, quantity => quantity.ToUnit(VolumeUnit.UsTablespoon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsTeaspoon, quantity => quantity.ToUnit(VolumeUnit.UsTeaspoon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.AcreFoot, quantity => new Volume(quantity.Value*0.000810714, VolumeUnit.AcreFoot)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.AuTablespoon, quantity => new Volume(quantity.Value/2e-5, VolumeUnit.AuTablespoon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.BoardFoot, quantity => new Volume(quantity.Value/2.3597372158e-3, VolumeUnit.BoardFoot)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Centiliter, quantity => new Volume((quantity.Value*1e3) / 1e-2d, VolumeUnit.Centiliter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicCentimeter, quantity => new Volume(quantity.Value*1e6, VolumeUnit.CubicCentimeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicDecimeter, quantity => new Volume(quantity.Value*1e3, VolumeUnit.CubicDecimeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicFoot, quantity => new Volume(quantity.Value/0.0283168, VolumeUnit.CubicFoot)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicHectometer, quantity => new Volume(quantity.Value/1e6, VolumeUnit.CubicHectometer)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicInch, quantity => new Volume(quantity.Value/(1.6387*1e-5), VolumeUnit.CubicInch)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicKilometer, quantity => new Volume(quantity.Value/1e9, VolumeUnit.CubicKilometer)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMicrometer, quantity => new Volume(quantity.Value*1e18, VolumeUnit.CubicMicrometer)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMile, quantity => new Volume(quantity.Value/4.16818182544058e9, VolumeUnit.CubicMile)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMillimeter, quantity => new Volume(quantity.Value*1e9, VolumeUnit.CubicMillimeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicYard, quantity => new Volume(quantity.Value/0.764554858, VolumeUnit.CubicYard)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.DecausGallon, quantity => new Volume((quantity.Value/0.00378541) / 1e1d, VolumeUnit.DecausGallon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Deciliter, quantity => new Volume((quantity.Value*1e3) / 1e-1d, VolumeUnit.Deciliter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.DeciusGallon, quantity => new Volume((quantity.Value/0.00378541) / 1e-1d, VolumeUnit.DeciusGallon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.HectocubicFoot, quantity => new Volume((quantity.Value/0.0283168) / 1e2d, VolumeUnit.HectocubicFoot)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.HectocubicMeter, quantity => new Volume((quantity.Value) / 1e2d, VolumeUnit.HectocubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Hectoliter, quantity => new Volume((quantity.Value*1e3) / 1e2d, VolumeUnit.Hectoliter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.HectousGallon, quantity => new Volume((quantity.Value/0.00378541) / 1e2d, VolumeUnit.HectousGallon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialBeerBarrel, quantity => new Volume(quantity.Value/0.16365924, VolumeUnit.ImperialBeerBarrel)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialGallon, quantity => new Volume(quantity.Value/0.00454609000000181429905810072407, VolumeUnit.ImperialGallon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialOunce, quantity => new Volume(quantity.Value/2.8413062499962901241875439064617e-5, VolumeUnit.ImperialOunce)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialPint, quantity => new Volume(quantity.Value / 5.6826125e-4, VolumeUnit.ImperialPint)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KilocubicFoot, quantity => new Volume((quantity.Value/0.0283168) / 1e3d, VolumeUnit.KilocubicFoot)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KilocubicMeter, quantity => new Volume((quantity.Value) / 1e3d, VolumeUnit.KilocubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KiloimperialGallon, quantity => new Volume((quantity.Value/0.00454609000000181429905810072407) / 1e3d, VolumeUnit.KiloimperialGallon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Kiloliter, quantity => new Volume((quantity.Value*1e3) / 1e3d, VolumeUnit.Kiloliter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KilousGallon, quantity => new Volume((quantity.Value/0.00378541) / 1e3d, VolumeUnit.KilousGallon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Liter, quantity => new Volume(quantity.Value*1e3, VolumeUnit.Liter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MegacubicFoot, quantity => new Volume((quantity.Value/0.0283168) / 1e6d, VolumeUnit.MegacubicFoot)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MegaimperialGallon, quantity => new Volume((quantity.Value/0.00454609000000181429905810072407) / 1e6d, VolumeUnit.MegaimperialGallon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Megaliter, quantity => new Volume((quantity.Value*1e3) / 1e6d, VolumeUnit.Megaliter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MegausGallon, quantity => new Volume((quantity.Value/0.00378541) / 1e6d, VolumeUnit.MegausGallon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MetricCup, quantity => new Volume(quantity.Value/0.00025, VolumeUnit.MetricCup)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MetricTeaspoon, quantity => new Volume(quantity.Value/0.5e-5, VolumeUnit.MetricTeaspoon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Microliter, quantity => new Volume((quantity.Value*1e3) / 1e-6d, VolumeUnit.Microliter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Milliliter, quantity => new Volume((quantity.Value*1e3) / 1e-3d, VolumeUnit.Milliliter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.OilBarrel, quantity => new Volume(quantity.Value/0.158987294928, VolumeUnit.OilBarrel)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UkTablespoon, quantity => new Volume(quantity.Value/1.5e-5, VolumeUnit.UkTablespoon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsBeerBarrel, quantity => new Volume(quantity.Value/0.1173477658, VolumeUnit.UsBeerBarrel)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsCustomaryCup, quantity => new Volume(quantity.Value/0.0002365882365, VolumeUnit.UsCustomaryCup)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsGallon, quantity => new Volume(quantity.Value/0.00378541, VolumeUnit.UsGallon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsLegalCup, quantity => new Volume(quantity.Value/0.00024, VolumeUnit.UsLegalCup)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsOunce, quantity => new Volume(quantity.Value/2.957352956253760505068307980135e-5, VolumeUnit.UsOunce)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsPint, quantity => new Volume(quantity.Value/4.73176473e-4, VolumeUnit.UsPint)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsQuart, quantity => new Volume(quantity.Value/9.46352946e-4, VolumeUnit.UsQuart)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsTablespoon, quantity => new Volume(quantity.Value/1.478676478125e-5, VolumeUnit.UsTablespoon)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsTeaspoon, quantity => new Volume(quantity.Value/4.92892159375e-6, VolumeUnit.UsTeaspoon)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMeter, quantity => quantity); // Register in unit converter: VolumeUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumeUnit.AcreFoot, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.AuTablespoon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.BoardFoot, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.Centiliter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicCentimeter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicDecimeter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicHectometer, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicInch, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicKilometer, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicMicrometer, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicMile, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicMillimeter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.CubicYard, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.DecausGallon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.Deciliter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.DeciusGallon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.HectocubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.HectocubicMeter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.Hectoliter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.HectousGallon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.ImperialBeerBarrel, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.ImperialGallon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.ImperialOunce, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.ImperialPint, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.KilocubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.KilocubicMeter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.KiloimperialGallon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.Kiloliter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.KilousGallon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.Liter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.MegacubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.MegaimperialGallon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.Megaliter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.MegausGallon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.MetricCup, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.MetricTeaspoon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.Microliter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.Milliliter, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UkTablespoon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UsBeerBarrel, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UsCustomaryCup, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UsGallon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UsLegalCup, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UsOunce, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UsPint, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UsQuart, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UsTablespoon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeUnit.UsTeaspoon, VolumeUnit.CubicMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(VolumeUnit.AcreFoot, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value/0.000810714, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.AuTablespoon, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*2e-5, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.BoardFoot, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*2.3597372158e-3, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.Centiliter, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value/1e3) * 1e-2d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicCentimeter, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value/1e6, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicDecimeter, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value/1e3, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicFoot, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.0283168, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicHectometer, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*1e6, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicInch, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*1.6387*1e-5, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicKilometer, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*1e9, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMicrometer, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value/1e18, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMile, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*4.16818182544058e9, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicMillimeter, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value/1e9, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.CubicYard, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.764554858, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.DecausGallon, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.00378541) * 1e1d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.Deciliter, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value/1e3) * 1e-1d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.DeciusGallon, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.00378541) * 1e-1d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.HectocubicFoot, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.0283168) * 1e2d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.HectocubicMeter, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value) * 1e2d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.Hectoliter, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value/1e3) * 1e2d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.HectousGallon, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.00378541) * 1e2d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.ImperialBeerBarrel, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.16365924, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.ImperialGallon, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.00454609000000181429905810072407, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.ImperialOunce, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*2.8413062499962901241875439064617e-5, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.ImperialPint, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value * 5.6826125e-4, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.KilocubicFoot, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.0283168) * 1e3d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.KilocubicMeter, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value) * 1e3d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.KiloimperialGallon, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.00454609000000181429905810072407) * 1e3d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.Kiloliter, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value/1e3) * 1e3d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.KilousGallon, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.00378541) * 1e3d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.Liter, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value/1e3, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.MegacubicFoot, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.0283168) * 1e6d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.MegaimperialGallon, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.00454609000000181429905810072407) * 1e6d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.Megaliter, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value/1e3) * 1e6d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.MegausGallon, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value*0.00378541) * 1e6d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.MetricCup, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.00025, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.MetricTeaspoon, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.5e-5, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.Microliter, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value/1e3) * 1e-6d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.Milliliter, VolumeUnit.CubicMeter, quantity => new Volume((quantity.Value/1e3) * 1e-3d, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.158987294928, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UkTablespoon, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*1.5e-5, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UsBeerBarrel, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.1173477658, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UsCustomaryCup, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.0002365882365, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UsGallon, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.00378541, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UsLegalCup, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*0.00024, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UsOunce, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*2.957352956253760505068307980135e-5, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UsPint, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*4.73176473e-4, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UsQuart, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*9.46352946e-4, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UsTablespoon, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*1.478676478125e-5, VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction(VolumeUnit.UsTeaspoon, VolumeUnit.CubicMeter, quantity => new Volume(quantity.Value*4.92892159375e-6, VolumeUnit.CubicMeter)); } /// @@ -1466,11 +1473,42 @@ double IQuantity.As(Enum unit) /// /// Converts this Volume to another Volume with the unit representation . /// + /// The unit to convert to. /// A Volume with the specified unit. public Volume ToUnit(VolumeUnit unit) { - var convertedValue = GetValueAs(unit); - return new Volume(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this Volume to another Volume using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A Volume with the specified unit. + public Volume ToUnit(VolumeUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(Volume), Unit, typeof(Volume), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (Volume)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1479,7 +1517,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is VolumeUnit unitAsVolumeUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumeUnit); + return ToUnit(unitAsVolumeUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is VolumeUnit unitAsVolumeUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsVolumeUnit, unitConverter); } /// @@ -1504,147 +1551,15 @@ public Volume ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(VolumeUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case VolumeUnit.AcreFoot: return _value/0.000810714; - case VolumeUnit.AuTablespoon: return _value*2e-5; - case VolumeUnit.BoardFoot: return _value*2.3597372158e-3; - case VolumeUnit.Centiliter: return (_value/1e3) * 1e-2d; - case VolumeUnit.CubicCentimeter: return _value/1e6; - case VolumeUnit.CubicDecimeter: return _value/1e3; - case VolumeUnit.CubicFoot: return _value*0.0283168; - case VolumeUnit.CubicHectometer: return _value*1e6; - case VolumeUnit.CubicInch: return _value*1.6387*1e-5; - case VolumeUnit.CubicKilometer: return _value*1e9; - case VolumeUnit.CubicMeter: return _value; - case VolumeUnit.CubicMicrometer: return _value/1e18; - case VolumeUnit.CubicMile: return _value*4.16818182544058e9; - case VolumeUnit.CubicMillimeter: return _value/1e9; - case VolumeUnit.CubicYard: return _value*0.764554858; - case VolumeUnit.DecausGallon: return (_value*0.00378541) * 1e1d; - case VolumeUnit.Deciliter: return (_value/1e3) * 1e-1d; - case VolumeUnit.DeciusGallon: return (_value*0.00378541) * 1e-1d; - case VolumeUnit.HectocubicFoot: return (_value*0.0283168) * 1e2d; - case VolumeUnit.HectocubicMeter: return (_value) * 1e2d; - case VolumeUnit.Hectoliter: return (_value/1e3) * 1e2d; - case VolumeUnit.HectousGallon: return (_value*0.00378541) * 1e2d; - case VolumeUnit.ImperialBeerBarrel: return _value*0.16365924; - case VolumeUnit.ImperialGallon: return _value*0.00454609000000181429905810072407; - case VolumeUnit.ImperialOunce: return _value*2.8413062499962901241875439064617e-5; - case VolumeUnit.ImperialPint: return _value * 5.6826125e-4; - case VolumeUnit.KilocubicFoot: return (_value*0.0283168) * 1e3d; - case VolumeUnit.KilocubicMeter: return (_value) * 1e3d; - case VolumeUnit.KiloimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e3d; - case VolumeUnit.Kiloliter: return (_value/1e3) * 1e3d; - case VolumeUnit.KilousGallon: return (_value*0.00378541) * 1e3d; - case VolumeUnit.Liter: return _value/1e3; - case VolumeUnit.MegacubicFoot: return (_value*0.0283168) * 1e6d; - case VolumeUnit.MegaimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e6d; - case VolumeUnit.Megaliter: return (_value/1e3) * 1e6d; - case VolumeUnit.MegausGallon: return (_value*0.00378541) * 1e6d; - case VolumeUnit.MetricCup: return _value*0.00025; - case VolumeUnit.MetricTeaspoon: return _value*0.5e-5; - case VolumeUnit.Microliter: return (_value/1e3) * 1e-6d; - case VolumeUnit.Milliliter: return (_value/1e3) * 1e-3d; - case VolumeUnit.OilBarrel: return _value*0.158987294928; - case VolumeUnit.UkTablespoon: return _value*1.5e-5; - case VolumeUnit.UsBeerBarrel: return _value*0.1173477658; - case VolumeUnit.UsCustomaryCup: return _value*0.0002365882365; - case VolumeUnit.UsGallon: return _value*0.00378541; - case VolumeUnit.UsLegalCup: return _value*0.00024; - case VolumeUnit.UsOunce: return _value*2.957352956253760505068307980135e-5; - case VolumeUnit.UsPint: return _value*4.73176473e-4; - case VolumeUnit.UsQuart: return _value*9.46352946e-4; - case VolumeUnit.UsTablespoon: return _value*1.478676478125e-5; - case VolumeUnit.UsTeaspoon: return _value*4.92892159375e-6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(VolumeUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal Volume ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new Volume(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(VolumeUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case VolumeUnit.AcreFoot: return baseUnitValue*0.000810714; - case VolumeUnit.AuTablespoon: return baseUnitValue/2e-5; - case VolumeUnit.BoardFoot: return baseUnitValue/2.3597372158e-3; - case VolumeUnit.Centiliter: return (baseUnitValue*1e3) / 1e-2d; - case VolumeUnit.CubicCentimeter: return baseUnitValue*1e6; - case VolumeUnit.CubicDecimeter: return baseUnitValue*1e3; - case VolumeUnit.CubicFoot: return baseUnitValue/0.0283168; - case VolumeUnit.CubicHectometer: return baseUnitValue/1e6; - case VolumeUnit.CubicInch: return baseUnitValue/(1.6387*1e-5); - case VolumeUnit.CubicKilometer: return baseUnitValue/1e9; - case VolumeUnit.CubicMeter: return baseUnitValue; - case VolumeUnit.CubicMicrometer: return baseUnitValue*1e18; - case VolumeUnit.CubicMile: return baseUnitValue/4.16818182544058e9; - case VolumeUnit.CubicMillimeter: return baseUnitValue*1e9; - case VolumeUnit.CubicYard: return baseUnitValue/0.764554858; - case VolumeUnit.DecausGallon: return (baseUnitValue/0.00378541) / 1e1d; - case VolumeUnit.Deciliter: return (baseUnitValue*1e3) / 1e-1d; - case VolumeUnit.DeciusGallon: return (baseUnitValue/0.00378541) / 1e-1d; - case VolumeUnit.HectocubicFoot: return (baseUnitValue/0.0283168) / 1e2d; - case VolumeUnit.HectocubicMeter: return (baseUnitValue) / 1e2d; - case VolumeUnit.Hectoliter: return (baseUnitValue*1e3) / 1e2d; - case VolumeUnit.HectousGallon: return (baseUnitValue/0.00378541) / 1e2d; - case VolumeUnit.ImperialBeerBarrel: return baseUnitValue/0.16365924; - case VolumeUnit.ImperialGallon: return baseUnitValue/0.00454609000000181429905810072407; - case VolumeUnit.ImperialOunce: return baseUnitValue/2.8413062499962901241875439064617e-5; - case VolumeUnit.ImperialPint: return baseUnitValue / 5.6826125e-4; - case VolumeUnit.KilocubicFoot: return (baseUnitValue/0.0283168) / 1e3d; - case VolumeUnit.KilocubicMeter: return (baseUnitValue) / 1e3d; - case VolumeUnit.KiloimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e3d; - case VolumeUnit.Kiloliter: return (baseUnitValue*1e3) / 1e3d; - case VolumeUnit.KilousGallon: return (baseUnitValue/0.00378541) / 1e3d; - case VolumeUnit.Liter: return baseUnitValue*1e3; - case VolumeUnit.MegacubicFoot: return (baseUnitValue/0.0283168) / 1e6d; - case VolumeUnit.MegaimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e6d; - case VolumeUnit.Megaliter: return (baseUnitValue*1e3) / 1e6d; - case VolumeUnit.MegausGallon: return (baseUnitValue/0.00378541) / 1e6d; - case VolumeUnit.MetricCup: return baseUnitValue/0.00025; - case VolumeUnit.MetricTeaspoon: return baseUnitValue/0.5e-5; - case VolumeUnit.Microliter: return (baseUnitValue*1e3) / 1e-6d; - case VolumeUnit.Milliliter: return (baseUnitValue*1e3) / 1e-3d; - case VolumeUnit.OilBarrel: return baseUnitValue/0.158987294928; - case VolumeUnit.UkTablespoon: return baseUnitValue/1.5e-5; - case VolumeUnit.UsBeerBarrel: return baseUnitValue/0.1173477658; - case VolumeUnit.UsCustomaryCup: return baseUnitValue/0.0002365882365; - case VolumeUnit.UsGallon: return baseUnitValue/0.00378541; - case VolumeUnit.UsLegalCup: return baseUnitValue/0.00024; - case VolumeUnit.UsOunce: return baseUnitValue/2.957352956253760505068307980135e-5; - case VolumeUnit.UsPint: return baseUnitValue/4.73176473e-4; - case VolumeUnit.UsQuart: return baseUnitValue/9.46352946e-4; - case VolumeUnit.UsTablespoon: return baseUnitValue/1.478676478125e-5; - case VolumeUnit.UsTeaspoon: return baseUnitValue/4.92892159375e-6; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs index 0ad30e8924..e0b2294a8e 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs @@ -87,6 +87,8 @@ static VolumeConcentration() new UnitInfo(VolumeConcentrationUnit.PicolitersPerMililiter, "PicolitersPerMililiter", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.VolumeConcentration); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -125,6 +127,11 @@ public VolumeConcentration(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -312,49 +319,49 @@ public VolumeConcentration(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> VolumeConcentrationUnit - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentilitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.CentilitersPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentilitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.CentilitersPerMililiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecilitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecilitersPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecilitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecilitersPerMililiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.LitersPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.LitersPerMililiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicrolitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MicrolitersPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicrolitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MicrolitersPerMililiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MillilitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MillilitersPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MillilitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MillilitersPerMililiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanolitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.NanolitersPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanolitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.NanolitersPerMililiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerBillion, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerBillion)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerMillion, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerMillion)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerThousand, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerThousand)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerTrillion, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerTrillion)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.Percent, quantity => quantity.ToUnit(VolumeConcentrationUnit.Percent)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicolitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.PicolitersPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicolitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.PicolitersPerMililiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentilitersPerLiter, quantity => new VolumeConcentration((quantity.Value) / 1e-2d, VolumeConcentrationUnit.CentilitersPerLiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentilitersPerMililiter, quantity => new VolumeConcentration((quantity.Value*1e-3) / 1e-2d, VolumeConcentrationUnit.CentilitersPerMililiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecilitersPerLiter, quantity => new VolumeConcentration((quantity.Value) / 1e-1d, VolumeConcentrationUnit.DecilitersPerLiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecilitersPerMililiter, quantity => new VolumeConcentration((quantity.Value*1e-3) / 1e-1d, VolumeConcentrationUnit.DecilitersPerMililiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LitersPerLiter, quantity => new VolumeConcentration(quantity.Value, VolumeConcentrationUnit.LitersPerLiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LitersPerMililiter, quantity => new VolumeConcentration(quantity.Value*1e-3, VolumeConcentrationUnit.LitersPerMililiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicrolitersPerLiter, quantity => new VolumeConcentration((quantity.Value) / 1e-6d, VolumeConcentrationUnit.MicrolitersPerLiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicrolitersPerMililiter, quantity => new VolumeConcentration((quantity.Value*1e-3) / 1e-6d, VolumeConcentrationUnit.MicrolitersPerMililiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MillilitersPerLiter, quantity => new VolumeConcentration((quantity.Value) / 1e-3d, VolumeConcentrationUnit.MillilitersPerLiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MillilitersPerMililiter, quantity => new VolumeConcentration((quantity.Value*1e-3) / 1e-3d, VolumeConcentrationUnit.MillilitersPerMililiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanolitersPerLiter, quantity => new VolumeConcentration((quantity.Value) / 1e-9d, VolumeConcentrationUnit.NanolitersPerLiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanolitersPerMililiter, quantity => new VolumeConcentration((quantity.Value*1e-3) / 1e-9d, VolumeConcentrationUnit.NanolitersPerMililiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerBillion, quantity => new VolumeConcentration(quantity.Value*1e9, VolumeConcentrationUnit.PartPerBillion)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerMillion, quantity => new VolumeConcentration(quantity.Value*1e6, VolumeConcentrationUnit.PartPerMillion)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerThousand, quantity => new VolumeConcentration(quantity.Value*1e3, VolumeConcentrationUnit.PartPerThousand)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerTrillion, quantity => new VolumeConcentration(quantity.Value*1e12, VolumeConcentrationUnit.PartPerTrillion)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.Percent, quantity => new VolumeConcentration(quantity.Value*1e2, VolumeConcentrationUnit.Percent)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicolitersPerLiter, quantity => new VolumeConcentration((quantity.Value) / 1e-12d, VolumeConcentrationUnit.PicolitersPerLiter)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicolitersPerMililiter, quantity => new VolumeConcentration((quantity.Value*1e-3) / 1e-12d, VolumeConcentrationUnit.PicolitersPerMililiter)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecimalFraction, quantity => quantity); // Register in unit converter: VolumeConcentrationUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumeConcentrationUnit.CentilitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.CentilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecilitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.LitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.LitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.MicrolitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.MicrolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.MillilitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.MillilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.NanolitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.NanolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerBillion, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerMillion, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerThousand, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerTrillion, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.Percent, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PicolitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PicolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.CentilitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value) * 1e-2d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.CentilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value/1e-3) * 1e-2d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecilitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value) * 1e-1d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value/1e-3) * 1e-1d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.LitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration(quantity.Value, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.LitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration(quantity.Value/1e-3, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.MicrolitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value) * 1e-6d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.MicrolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value/1e-3) * 1e-6d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.MillilitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value) * 1e-3d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.MillilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value/1e-3) * 1e-3d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.NanolitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value) * 1e-9d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.NanolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value/1e-3) * 1e-9d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerBillion, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration(quantity.Value/1e9, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerMillion, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration(quantity.Value/1e6, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerThousand, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration(quantity.Value/1e3, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerTrillion, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration(quantity.Value/1e12, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.Percent, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration(quantity.Value/1e2, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.PicolitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value) * 1e-12d, VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction(VolumeConcentrationUnit.PicolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => new VolumeConcentration((quantity.Value/1e-3) * 1e-12d, VolumeConcentrationUnit.DecimalFraction)); } /// @@ -942,11 +949,42 @@ double IQuantity.As(Enum unit) /// /// Converts this VolumeConcentration to another VolumeConcentration with the unit representation . /// + /// The unit to convert to. /// A VolumeConcentration with the specified unit. public VolumeConcentration ToUnit(VolumeConcentrationUnit unit) { - var convertedValue = GetValueAs(unit); - return new VolumeConcentration(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this VolumeConcentration to another VolumeConcentration using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A VolumeConcentration with the specified unit. + public VolumeConcentration ToUnit(VolumeConcentrationUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(VolumeConcentration), Unit, typeof(VolumeConcentration), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (VolumeConcentration)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -955,7 +993,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is VolumeConcentrationUnit unitAsVolumeConcentrationUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeConcentrationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumeConcentrationUnit); + return ToUnit(unitAsVolumeConcentrationUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is VolumeConcentrationUnit unitAsVolumeConcentrationUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeConcentrationUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsVolumeConcentrationUnit, unitConverter); } /// @@ -980,85 +1027,15 @@ public VolumeConcentration ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(VolumeConcentrationUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case VolumeConcentrationUnit.CentilitersPerLiter: return (_value) * 1e-2d; - case VolumeConcentrationUnit.CentilitersPerMililiter: return (_value/1e-3) * 1e-2d; - case VolumeConcentrationUnit.DecilitersPerLiter: return (_value) * 1e-1d; - case VolumeConcentrationUnit.DecilitersPerMililiter: return (_value/1e-3) * 1e-1d; - case VolumeConcentrationUnit.DecimalFraction: return _value; - case VolumeConcentrationUnit.LitersPerLiter: return _value; - case VolumeConcentrationUnit.LitersPerMililiter: return _value/1e-3; - case VolumeConcentrationUnit.MicrolitersPerLiter: return (_value) * 1e-6d; - case VolumeConcentrationUnit.MicrolitersPerMililiter: return (_value/1e-3) * 1e-6d; - case VolumeConcentrationUnit.MillilitersPerLiter: return (_value) * 1e-3d; - case VolumeConcentrationUnit.MillilitersPerMililiter: return (_value/1e-3) * 1e-3d; - case VolumeConcentrationUnit.NanolitersPerLiter: return (_value) * 1e-9d; - case VolumeConcentrationUnit.NanolitersPerMililiter: return (_value/1e-3) * 1e-9d; - case VolumeConcentrationUnit.PartPerBillion: return _value/1e9; - case VolumeConcentrationUnit.PartPerMillion: return _value/1e6; - case VolumeConcentrationUnit.PartPerThousand: return _value/1e3; - case VolumeConcentrationUnit.PartPerTrillion: return _value/1e12; - case VolumeConcentrationUnit.Percent: return _value/1e2; - case VolumeConcentrationUnit.PicolitersPerLiter: return (_value) * 1e-12d; - case VolumeConcentrationUnit.PicolitersPerMililiter: return (_value/1e-3) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(VolumeConcentrationUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal VolumeConcentration ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new VolumeConcentration(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(VolumeConcentrationUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case VolumeConcentrationUnit.CentilitersPerLiter: return (baseUnitValue) / 1e-2d; - case VolumeConcentrationUnit.CentilitersPerMililiter: return (baseUnitValue*1e-3) / 1e-2d; - case VolumeConcentrationUnit.DecilitersPerLiter: return (baseUnitValue) / 1e-1d; - case VolumeConcentrationUnit.DecilitersPerMililiter: return (baseUnitValue*1e-3) / 1e-1d; - case VolumeConcentrationUnit.DecimalFraction: return baseUnitValue; - case VolumeConcentrationUnit.LitersPerLiter: return baseUnitValue; - case VolumeConcentrationUnit.LitersPerMililiter: return baseUnitValue*1e-3; - case VolumeConcentrationUnit.MicrolitersPerLiter: return (baseUnitValue) / 1e-6d; - case VolumeConcentrationUnit.MicrolitersPerMililiter: return (baseUnitValue*1e-3) / 1e-6d; - case VolumeConcentrationUnit.MillilitersPerLiter: return (baseUnitValue) / 1e-3d; - case VolumeConcentrationUnit.MillilitersPerMililiter: return (baseUnitValue*1e-3) / 1e-3d; - case VolumeConcentrationUnit.NanolitersPerLiter: return (baseUnitValue) / 1e-9d; - case VolumeConcentrationUnit.NanolitersPerMililiter: return (baseUnitValue*1e-3) / 1e-9d; - case VolumeConcentrationUnit.PartPerBillion: return baseUnitValue*1e9; - case VolumeConcentrationUnit.PartPerMillion: return baseUnitValue*1e6; - case VolumeConcentrationUnit.PartPerThousand: return baseUnitValue*1e3; - case VolumeConcentrationUnit.PartPerTrillion: return baseUnitValue*1e12; - case VolumeConcentrationUnit.Percent: return baseUnitValue*1e2; - case VolumeConcentrationUnit.PicolitersPerLiter: return (baseUnitValue) / 1e-12d; - case VolumeConcentrationUnit.PicolitersPerMililiter: return (baseUnitValue*1e-3) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs index cd84b13238..2d7446d292 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs @@ -126,6 +126,8 @@ static VolumeFlow() new UnitInfo(VolumeFlowUnit.UsGallonPerSecond, "UsGallonsPerSecond", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.VolumeFlow); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -164,6 +166,11 @@ public VolumeFlow(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -561,133 +568,133 @@ public VolumeFlow(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> VolumeFlowUnit - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicCentimeterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicCentimeterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicDecimeterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicDecimeterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CubicFootPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicFootPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicFootPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMillimeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMillimeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KilousGallonPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.KilousGallonPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MegaliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaukGallonPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MegaukGallonPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MillionUsGallonsPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MillionUsGallonsPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerDay, quantity => new VolumeFlow(quantity.Value*70.0457, VolumeFlowUnit.AcreFootPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerHour, quantity => new VolumeFlow(quantity.Value*2.91857, VolumeFlowUnit.AcreFootPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerMinute, quantity => new VolumeFlow(quantity.Value*0.0486427916, VolumeFlowUnit.AcreFootPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerSecond, quantity => new VolumeFlow(quantity.Value*0.000810713194, VolumeFlowUnit.AcreFootPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerDay, quantity => new VolumeFlow((quantity.Value*86400000) / 1e-2d, VolumeFlowUnit.CentiliterPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerHour, quantity => new VolumeFlow((quantity.Value*3600000.000) / 1e-2d, VolumeFlowUnit.CentiliterPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerMinute, quantity => new VolumeFlow((quantity.Value*60000.00000) / 1e-2d, VolumeFlowUnit.CentiliterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerSecond, quantity => new VolumeFlow((quantity.Value*1000) / 1e-2d, VolumeFlowUnit.CentiliterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicCentimeterPerMinute, quantity => new VolumeFlow(quantity.Value/1.6666666666667e-8, VolumeFlowUnit.CubicCentimeterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicDecimeterPerMinute, quantity => new VolumeFlow(quantity.Value*60000.00000, VolumeFlowUnit.CubicDecimeterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerHour, quantity => new VolumeFlow(quantity.Value/7.8657907199999087346816086183876e-6, VolumeFlowUnit.CubicFootPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerMinute, quantity => new VolumeFlow(quantity.Value*2118.88000326, VolumeFlowUnit.CubicFootPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerSecond, quantity => new VolumeFlow(quantity.Value*35.314666721, VolumeFlowUnit.CubicFootPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerDay, quantity => new VolumeFlow(quantity.Value*86400, VolumeFlowUnit.CubicMeterPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerHour, quantity => new VolumeFlow(quantity.Value*3600, VolumeFlowUnit.CubicMeterPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerMinute, quantity => new VolumeFlow(quantity.Value*60, VolumeFlowUnit.CubicMeterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMillimeterPerSecond, quantity => new VolumeFlow(quantity.Value/1e-9, VolumeFlowUnit.CubicMillimeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerDay, quantity => new VolumeFlow(quantity.Value*113007, VolumeFlowUnit.CubicYardPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerHour, quantity => new VolumeFlow(quantity.Value/2.1237634944E-4, VolumeFlowUnit.CubicYardPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerMinute, quantity => new VolumeFlow(quantity.Value/0.0127425809664, VolumeFlowUnit.CubicYardPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerSecond, quantity => new VolumeFlow(quantity.Value/0.764554857984, VolumeFlowUnit.CubicYardPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerDay, quantity => new VolumeFlow((quantity.Value*86400000) / 1e-1d, VolumeFlowUnit.DeciliterPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerHour, quantity => new VolumeFlow((quantity.Value*3600000.000) / 1e-1d, VolumeFlowUnit.DeciliterPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerMinute, quantity => new VolumeFlow((quantity.Value*60000.00000) / 1e-1d, VolumeFlowUnit.DeciliterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerSecond, quantity => new VolumeFlow((quantity.Value*1000) / 1e-1d, VolumeFlowUnit.DeciliterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerDay, quantity => new VolumeFlow((quantity.Value*86400000) / 1e3d, VolumeFlowUnit.KiloliterPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerHour, quantity => new VolumeFlow((quantity.Value*3600000.000) / 1e3d, VolumeFlowUnit.KiloliterPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerMinute, quantity => new VolumeFlow((quantity.Value*60000.00000) / 1e3d, VolumeFlowUnit.KiloliterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerSecond, quantity => new VolumeFlow((quantity.Value*1000) / 1e3d, VolumeFlowUnit.KiloliterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KilousGallonPerMinute, quantity => new VolumeFlow(quantity.Value*15.850323141489, VolumeFlowUnit.KilousGallonPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerDay, quantity => new VolumeFlow(quantity.Value*86400000, VolumeFlowUnit.LiterPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerHour, quantity => new VolumeFlow(quantity.Value*3600000.000, VolumeFlowUnit.LiterPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerMinute, quantity => new VolumeFlow(quantity.Value*60000.00000, VolumeFlowUnit.LiterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerSecond, quantity => new VolumeFlow(quantity.Value*1000, VolumeFlowUnit.LiterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerDay, quantity => new VolumeFlow((quantity.Value*86400000) / 1e6d, VolumeFlowUnit.MegaliterPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaukGallonPerSecond, quantity => new VolumeFlow((quantity.Value*219.969) / 1e6d, VolumeFlowUnit.MegaukGallonPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerDay, quantity => new VolumeFlow((quantity.Value*86400000) / 1e-6d, VolumeFlowUnit.MicroliterPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerHour, quantity => new VolumeFlow((quantity.Value*3600000.000) / 1e-6d, VolumeFlowUnit.MicroliterPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerMinute, quantity => new VolumeFlow((quantity.Value*60000.00000) / 1e-6d, VolumeFlowUnit.MicroliterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerSecond, quantity => new VolumeFlow((quantity.Value*1000) / 1e-6d, VolumeFlowUnit.MicroliterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerDay, quantity => new VolumeFlow((quantity.Value*86400000) / 1e-3d, VolumeFlowUnit.MilliliterPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerHour, quantity => new VolumeFlow((quantity.Value*3600000.000) / 1e-3d, VolumeFlowUnit.MilliliterPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerMinute, quantity => new VolumeFlow((quantity.Value*60000.00000) / 1e-3d, VolumeFlowUnit.MilliliterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerSecond, quantity => new VolumeFlow((quantity.Value*1000) / 1e-3d, VolumeFlowUnit.MilliliterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MillionUsGallonsPerDay, quantity => new VolumeFlow(quantity.Value*22.824465227, VolumeFlowUnit.MillionUsGallonsPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerDay, quantity => new VolumeFlow((quantity.Value*86400000) / 1e-9d, VolumeFlowUnit.NanoliterPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerHour, quantity => new VolumeFlow((quantity.Value*3600000.000) / 1e-9d, VolumeFlowUnit.NanoliterPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerMinute, quantity => new VolumeFlow((quantity.Value*60000.00000) / 1e-9d, VolumeFlowUnit.NanoliterPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerSecond, quantity => new VolumeFlow((quantity.Value*1000) / 1e-9d, VolumeFlowUnit.NanoliterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerDay, quantity => new VolumeFlow(quantity.Value/1.8401307283333333333333333333333e-6, VolumeFlowUnit.OilBarrelPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerHour, quantity => new VolumeFlow(quantity.Value/4.41631375e-5, VolumeFlowUnit.OilBarrelPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerMinute, quantity => new VolumeFlow(quantity.Value/2.64978825e-3, VolumeFlowUnit.OilBarrelPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerSecond, quantity => new VolumeFlow(quantity.Value*6.28981, VolumeFlowUnit.OilBarrelPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerDay, quantity => new VolumeFlow(quantity.Value*19005304, VolumeFlowUnit.UkGallonPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerHour, quantity => new VolumeFlow(quantity.Value*791887.667, VolumeFlowUnit.UkGallonPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerMinute, quantity => new VolumeFlow(quantity.Value*13198.2, VolumeFlowUnit.UkGallonPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerSecond, quantity => new VolumeFlow(quantity.Value*219.969, VolumeFlowUnit.UkGallonPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerDay, quantity => new VolumeFlow(quantity.Value*22824465.227, VolumeFlowUnit.UsGallonPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerHour, quantity => new VolumeFlow(quantity.Value*951019.38848933424, VolumeFlowUnit.UsGallonPerHour)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerMinute, quantity => new VolumeFlow(quantity.Value*15850.323141489, VolumeFlowUnit.UsGallonPerMinute)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerSecond, quantity => new VolumeFlow(quantity.Value*264.1720523581484, VolumeFlowUnit.UsGallonPerSecond)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity); // Register in unit converter: VolumeFlowUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicCentimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicDecimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicFootPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMillimeterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.KilousGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MegaliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MegaukGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.MillionUsGallonsPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/70.0457, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/2.91857, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/0.0486427916, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/0.000810713194, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/86400000) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/3600000.000) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/60000.00000) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/1000) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicCentimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value*1.6666666666667e-8, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicDecimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/60000.00000, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicFootPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value*7.8657907199999087346816086183876e-6, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/2118.88000326, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/35.314666721, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/86400, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/3600, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/60, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMillimeterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value*1e-9, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/113007, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value*2.1237634944E-4, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value*0.0127425809664, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value*0.764554857984, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/86400000) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/3600000.000) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/60000.00000) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/1000) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/86400000) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/3600000.000) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/60000.00000) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/1000) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.KilousGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/15.850323141489, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/86400000, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/3600000.000, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/60000.00000, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/1000, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MegaliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/86400000) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MegaukGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/219.969) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/86400000) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/3600000.000) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/60000.00000) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/1000) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/86400000) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/3600000.000) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/60000.00000) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/1000) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MillionUsGallonsPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/22.824465227, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/86400000) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/3600000.000) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/60000.00000) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow((quantity.Value/1000) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value*1.8401307283333333333333333333333e-6, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value*4.41631375e-5, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value*2.64978825e-3, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/6.28981, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/19005304, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/791887.667, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/13198.2, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/219.969, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/22824465.227, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/951019.38848933424, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/15850.323141489, VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => new VolumeFlow(quantity.Value/264.1720523581484, VolumeFlowUnit.CubicMeterPerSecond)); } /// @@ -1653,11 +1660,42 @@ double IQuantity.As(Enum unit) /// /// Converts this VolumeFlow to another VolumeFlow with the unit representation . /// + /// The unit to convert to. /// A VolumeFlow with the specified unit. public VolumeFlow ToUnit(VolumeFlowUnit unit) { - var convertedValue = GetValueAs(unit); - return new VolumeFlow(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this VolumeFlow to another VolumeFlow using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A VolumeFlow with the specified unit. + public VolumeFlow ToUnit(VolumeFlowUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(VolumeFlow), Unit, typeof(VolumeFlow), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (VolumeFlow)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -1666,7 +1704,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is VolumeFlowUnit unitAsVolumeFlowUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumeFlowUnit); + return ToUnit(unitAsVolumeFlowUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is VolumeFlowUnit unitAsVolumeFlowUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsVolumeFlowUnit, unitConverter); } /// @@ -1691,169 +1738,15 @@ public VolumeFlow ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(VolumeFlowUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case VolumeFlowUnit.AcreFootPerDay: return _value/70.0457; - case VolumeFlowUnit.AcreFootPerHour: return _value/2.91857; - case VolumeFlowUnit.AcreFootPerMinute: return _value/0.0486427916; - case VolumeFlowUnit.AcreFootPerSecond: return _value/0.000810713194; - case VolumeFlowUnit.CentiliterPerDay: return (_value/86400000) * 1e-2d; - case VolumeFlowUnit.CentiliterPerHour: return (_value/3600000.000) * 1e-2d; - case VolumeFlowUnit.CentiliterPerMinute: return (_value/60000.00000) * 1e-2d; - case VolumeFlowUnit.CentiliterPerSecond: return (_value/1000) * 1e-2d; - case VolumeFlowUnit.CubicCentimeterPerMinute: return _value*1.6666666666667e-8; - case VolumeFlowUnit.CubicDecimeterPerMinute: return _value/60000.00000; - case VolumeFlowUnit.CubicFootPerHour: return _value*7.8657907199999087346816086183876e-6; - case VolumeFlowUnit.CubicFootPerMinute: return _value/2118.88000326; - case VolumeFlowUnit.CubicFootPerSecond: return _value/35.314666721; - case VolumeFlowUnit.CubicMeterPerDay: return _value/86400; - case VolumeFlowUnit.CubicMeterPerHour: return _value/3600; - case VolumeFlowUnit.CubicMeterPerMinute: return _value/60; - case VolumeFlowUnit.CubicMeterPerSecond: return _value; - case VolumeFlowUnit.CubicMillimeterPerSecond: return _value*1e-9; - case VolumeFlowUnit.CubicYardPerDay: return _value/113007; - case VolumeFlowUnit.CubicYardPerHour: return _value*2.1237634944E-4; - case VolumeFlowUnit.CubicYardPerMinute: return _value*0.0127425809664; - case VolumeFlowUnit.CubicYardPerSecond: return _value*0.764554857984; - case VolumeFlowUnit.DeciliterPerDay: return (_value/86400000) * 1e-1d; - case VolumeFlowUnit.DeciliterPerHour: return (_value/3600000.000) * 1e-1d; - case VolumeFlowUnit.DeciliterPerMinute: return (_value/60000.00000) * 1e-1d; - case VolumeFlowUnit.DeciliterPerSecond: return (_value/1000) * 1e-1d; - case VolumeFlowUnit.KiloliterPerDay: return (_value/86400000) * 1e3d; - case VolumeFlowUnit.KiloliterPerHour: return (_value/3600000.000) * 1e3d; - case VolumeFlowUnit.KiloliterPerMinute: return (_value/60000.00000) * 1e3d; - case VolumeFlowUnit.KiloliterPerSecond: return (_value/1000) * 1e3d; - case VolumeFlowUnit.KilousGallonPerMinute: return _value/15.850323141489; - case VolumeFlowUnit.LiterPerDay: return _value/86400000; - case VolumeFlowUnit.LiterPerHour: return _value/3600000.000; - case VolumeFlowUnit.LiterPerMinute: return _value/60000.00000; - case VolumeFlowUnit.LiterPerSecond: return _value/1000; - case VolumeFlowUnit.MegaliterPerDay: return (_value/86400000) * 1e6d; - case VolumeFlowUnit.MegaukGallonPerSecond: return (_value/219.969) * 1e6d; - case VolumeFlowUnit.MicroliterPerDay: return (_value/86400000) * 1e-6d; - case VolumeFlowUnit.MicroliterPerHour: return (_value/3600000.000) * 1e-6d; - case VolumeFlowUnit.MicroliterPerMinute: return (_value/60000.00000) * 1e-6d; - case VolumeFlowUnit.MicroliterPerSecond: return (_value/1000) * 1e-6d; - case VolumeFlowUnit.MilliliterPerDay: return (_value/86400000) * 1e-3d; - case VolumeFlowUnit.MilliliterPerHour: return (_value/3600000.000) * 1e-3d; - case VolumeFlowUnit.MilliliterPerMinute: return (_value/60000.00000) * 1e-3d; - case VolumeFlowUnit.MilliliterPerSecond: return (_value/1000) * 1e-3d; - case VolumeFlowUnit.MillionUsGallonsPerDay: return _value/22.824465227; - case VolumeFlowUnit.NanoliterPerDay: return (_value/86400000) * 1e-9d; - case VolumeFlowUnit.NanoliterPerHour: return (_value/3600000.000) * 1e-9d; - case VolumeFlowUnit.NanoliterPerMinute: return (_value/60000.00000) * 1e-9d; - case VolumeFlowUnit.NanoliterPerSecond: return (_value/1000) * 1e-9d; - case VolumeFlowUnit.OilBarrelPerDay: return _value*1.8401307283333333333333333333333e-6; - case VolumeFlowUnit.OilBarrelPerHour: return _value*4.41631375e-5; - case VolumeFlowUnit.OilBarrelPerMinute: return _value*2.64978825e-3; - case VolumeFlowUnit.OilBarrelPerSecond: return _value/6.28981; - case VolumeFlowUnit.UkGallonPerDay: return _value/19005304; - case VolumeFlowUnit.UkGallonPerHour: return _value/791887.667; - case VolumeFlowUnit.UkGallonPerMinute: return _value/13198.2; - case VolumeFlowUnit.UkGallonPerSecond: return _value/219.969; - case VolumeFlowUnit.UsGallonPerDay: return _value/22824465.227; - case VolumeFlowUnit.UsGallonPerHour: return _value/951019.38848933424; - case VolumeFlowUnit.UsGallonPerMinute: return _value/15850.323141489; - case VolumeFlowUnit.UsGallonPerSecond: return _value/264.1720523581484; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(VolumeFlowUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal VolumeFlow ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new VolumeFlow(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(VolumeFlowUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case VolumeFlowUnit.AcreFootPerDay: return baseUnitValue*70.0457; - case VolumeFlowUnit.AcreFootPerHour: return baseUnitValue*2.91857; - case VolumeFlowUnit.AcreFootPerMinute: return baseUnitValue*0.0486427916; - case VolumeFlowUnit.AcreFootPerSecond: return baseUnitValue*0.000810713194; - case VolumeFlowUnit.CentiliterPerDay: return (baseUnitValue*86400000) / 1e-2d; - case VolumeFlowUnit.CentiliterPerHour: return (baseUnitValue*3600000.000) / 1e-2d; - case VolumeFlowUnit.CentiliterPerMinute: return (baseUnitValue*60000.00000) / 1e-2d; - case VolumeFlowUnit.CentiliterPerSecond: return (baseUnitValue*1000) / 1e-2d; - case VolumeFlowUnit.CubicCentimeterPerMinute: return baseUnitValue/1.6666666666667e-8; - case VolumeFlowUnit.CubicDecimeterPerMinute: return baseUnitValue*60000.00000; - case VolumeFlowUnit.CubicFootPerHour: return baseUnitValue/7.8657907199999087346816086183876e-6; - case VolumeFlowUnit.CubicFootPerMinute: return baseUnitValue*2118.88000326; - case VolumeFlowUnit.CubicFootPerSecond: return baseUnitValue*35.314666721; - case VolumeFlowUnit.CubicMeterPerDay: return baseUnitValue*86400; - case VolumeFlowUnit.CubicMeterPerHour: return baseUnitValue*3600; - case VolumeFlowUnit.CubicMeterPerMinute: return baseUnitValue*60; - case VolumeFlowUnit.CubicMeterPerSecond: return baseUnitValue; - case VolumeFlowUnit.CubicMillimeterPerSecond: return baseUnitValue/1e-9; - case VolumeFlowUnit.CubicYardPerDay: return baseUnitValue*113007; - case VolumeFlowUnit.CubicYardPerHour: return baseUnitValue/2.1237634944E-4; - case VolumeFlowUnit.CubicYardPerMinute: return baseUnitValue/0.0127425809664; - case VolumeFlowUnit.CubicYardPerSecond: return baseUnitValue/0.764554857984; - case VolumeFlowUnit.DeciliterPerDay: return (baseUnitValue*86400000) / 1e-1d; - case VolumeFlowUnit.DeciliterPerHour: return (baseUnitValue*3600000.000) / 1e-1d; - case VolumeFlowUnit.DeciliterPerMinute: return (baseUnitValue*60000.00000) / 1e-1d; - case VolumeFlowUnit.DeciliterPerSecond: return (baseUnitValue*1000) / 1e-1d; - case VolumeFlowUnit.KiloliterPerDay: return (baseUnitValue*86400000) / 1e3d; - case VolumeFlowUnit.KiloliterPerHour: return (baseUnitValue*3600000.000) / 1e3d; - case VolumeFlowUnit.KiloliterPerMinute: return (baseUnitValue*60000.00000) / 1e3d; - case VolumeFlowUnit.KiloliterPerSecond: return (baseUnitValue*1000) / 1e3d; - case VolumeFlowUnit.KilousGallonPerMinute: return baseUnitValue*15.850323141489; - case VolumeFlowUnit.LiterPerDay: return baseUnitValue*86400000; - case VolumeFlowUnit.LiterPerHour: return baseUnitValue*3600000.000; - case VolumeFlowUnit.LiterPerMinute: return baseUnitValue*60000.00000; - case VolumeFlowUnit.LiterPerSecond: return baseUnitValue*1000; - case VolumeFlowUnit.MegaliterPerDay: return (baseUnitValue*86400000) / 1e6d; - case VolumeFlowUnit.MegaukGallonPerSecond: return (baseUnitValue*219.969) / 1e6d; - case VolumeFlowUnit.MicroliterPerDay: return (baseUnitValue*86400000) / 1e-6d; - case VolumeFlowUnit.MicroliterPerHour: return (baseUnitValue*3600000.000) / 1e-6d; - case VolumeFlowUnit.MicroliterPerMinute: return (baseUnitValue*60000.00000) / 1e-6d; - case VolumeFlowUnit.MicroliterPerSecond: return (baseUnitValue*1000) / 1e-6d; - case VolumeFlowUnit.MilliliterPerDay: return (baseUnitValue*86400000) / 1e-3d; - case VolumeFlowUnit.MilliliterPerHour: return (baseUnitValue*3600000.000) / 1e-3d; - case VolumeFlowUnit.MilliliterPerMinute: return (baseUnitValue*60000.00000) / 1e-3d; - case VolumeFlowUnit.MilliliterPerSecond: return (baseUnitValue*1000) / 1e-3d; - case VolumeFlowUnit.MillionUsGallonsPerDay: return baseUnitValue*22.824465227; - case VolumeFlowUnit.NanoliterPerDay: return (baseUnitValue*86400000) / 1e-9d; - case VolumeFlowUnit.NanoliterPerHour: return (baseUnitValue*3600000.000) / 1e-9d; - case VolumeFlowUnit.NanoliterPerMinute: return (baseUnitValue*60000.00000) / 1e-9d; - case VolumeFlowUnit.NanoliterPerSecond: return (baseUnitValue*1000) / 1e-9d; - case VolumeFlowUnit.OilBarrelPerDay: return baseUnitValue/1.8401307283333333333333333333333e-6; - case VolumeFlowUnit.OilBarrelPerHour: return baseUnitValue/4.41631375e-5; - case VolumeFlowUnit.OilBarrelPerMinute: return baseUnitValue/2.64978825e-3; - case VolumeFlowUnit.OilBarrelPerSecond: return baseUnitValue*6.28981; - case VolumeFlowUnit.UkGallonPerDay: return baseUnitValue*19005304; - case VolumeFlowUnit.UkGallonPerHour: return baseUnitValue*791887.667; - case VolumeFlowUnit.UkGallonPerMinute: return baseUnitValue*13198.2; - case VolumeFlowUnit.UkGallonPerSecond: return baseUnitValue*219.969; - case VolumeFlowUnit.UsGallonPerDay: return baseUnitValue*22824465.227; - case VolumeFlowUnit.UsGallonPerHour: return baseUnitValue*951019.38848933424; - case VolumeFlowUnit.UsGallonPerMinute: return baseUnitValue*15850.323141489; - case VolumeFlowUnit.UsGallonPerSecond: return baseUnitValue*264.1720523581484; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs index f4864ce697..c6f0ba00b1 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs @@ -66,6 +66,8 @@ static VolumeFlowPerArea() new UnitInfo(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, "CubicMetersPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), }, BaseUnit, Zero, BaseDimensions, QuantityType.VolumeFlowPerArea); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -104,6 +106,11 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -201,13 +208,13 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> VolumeFlowPerAreaUnit - unitConverter.SetConversionFunction(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, quantity => quantity.ToUnit(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot)); + unitConverter.SetConversionFunction(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, quantity => new VolumeFlowPerArea(quantity.Value*196.850394, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, quantity => quantity); // Register in unit converter: VolumeFlowPerAreaUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, quantity => new VolumeFlowPerArea(quantity.Value/196.850394, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter)); } /// @@ -633,11 +640,42 @@ double IQuantity.As(Enum unit) /// /// Converts this VolumeFlowPerArea to another VolumeFlowPerArea with the unit representation . /// + /// The unit to convert to. /// A VolumeFlowPerArea with the specified unit. public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit) { - var convertedValue = GetValueAs(unit); - return new VolumeFlowPerArea(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this VolumeFlowPerArea to another VolumeFlowPerArea using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A VolumeFlowPerArea with the specified unit. + public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(VolumeFlowPerArea), Unit, typeof(VolumeFlowPerArea), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (VolumeFlowPerArea)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -646,7 +684,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is VolumeFlowPerAreaUnit unitAsVolumeFlowPerAreaUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowPerAreaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumeFlowPerAreaUnit); + return ToUnit(unitAsVolumeFlowPerAreaUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is VolumeFlowPerAreaUnit unitAsVolumeFlowPerAreaUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowPerAreaUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsVolumeFlowPerAreaUnit, unitConverter); } /// @@ -671,49 +718,15 @@ public VolumeFlowPerArea ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(VolumeFlowPerAreaUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot: return _value/196.850394; - case VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(VolumeFlowPerAreaUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal VolumeFlowPerArea ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new VolumeFlowPerArea(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(VolumeFlowPerAreaUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot: return baseUnitValue*196.850394; - case VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs index ddde6755cd..ad2c242fcf 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs @@ -71,6 +71,8 @@ static VolumePerLength() new UnitInfo(VolumePerLengthUnit.OilBarrelPerFoot, "OilBarrelsPerFoot", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.VolumePerLength); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -109,6 +111,11 @@ public VolumePerLength(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -231,23 +238,23 @@ public VolumePerLength(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> VolumePerLengthUnit - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerFoot, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicYardPerFoot)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerUsSurveyFoot, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicYardPerUsSurveyFoot)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerKilometer, quantity => quantity.ToUnit(VolumePerLengthUnit.LiterPerKilometer)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.LiterPerMeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMillimeter, quantity => quantity.ToUnit(VolumePerLengthUnit.LiterPerMillimeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.OilBarrelPerFoot, quantity => quantity.ToUnit(VolumePerLengthUnit.OilBarrelPerFoot)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerFoot, quantity => new VolumePerLength(quantity.Value/2.50838208, VolumePerLengthUnit.CubicYardPerFoot)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerUsSurveyFoot, quantity => new VolumePerLength(quantity.Value/2.50837706323584, VolumePerLengthUnit.CubicYardPerUsSurveyFoot)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerKilometer, quantity => new VolumePerLength(quantity.Value*1e6, VolumePerLengthUnit.LiterPerKilometer)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMeter, quantity => new VolumePerLength(quantity.Value*1000, VolumePerLengthUnit.LiterPerMeter)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMillimeter, quantity => new VolumePerLength(quantity.Value, VolumePerLengthUnit.LiterPerMillimeter)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.OilBarrelPerFoot, quantity => new VolumePerLength(quantity.Value*1.91713408, VolumePerLengthUnit.OilBarrelPerFoot)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity); // Register in unit converter: VolumePerLengthUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicYardPerFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumePerLengthUnit.LiterPerKilometer, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumePerLengthUnit.LiterPerMeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumePerLengthUnit.LiterPerMillimeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumePerLengthUnit.OilBarrelPerFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicYardPerFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => new VolumePerLength(quantity.Value*2.50838208, VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => new VolumePerLength(quantity.Value*2.50837706323584, VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.LiterPerKilometer, VolumePerLengthUnit.CubicMeterPerMeter, quantity => new VolumePerLength(quantity.Value/1e6, VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.LiterPerMeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => new VolumePerLength(quantity.Value/1000, VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.LiterPerMillimeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => new VolumePerLength(quantity.Value, VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction(VolumePerLengthUnit.OilBarrelPerFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => new VolumePerLength(quantity.Value/1.91713408, VolumePerLengthUnit.CubicMeterPerMeter)); } /// @@ -718,11 +725,42 @@ double IQuantity.As(Enum unit) /// /// Converts this VolumePerLength to another VolumePerLength with the unit representation . /// + /// The unit to convert to. /// A VolumePerLength with the specified unit. public VolumePerLength ToUnit(VolumePerLengthUnit unit) { - var convertedValue = GetValueAs(unit); - return new VolumePerLength(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this VolumePerLength to another VolumePerLength using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A VolumePerLength with the specified unit. + public VolumePerLength ToUnit(VolumePerLengthUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(VolumePerLength), Unit, typeof(VolumePerLength), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (VolumePerLength)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -731,7 +769,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is VolumePerLengthUnit unitAsVolumePerLengthUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumePerLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumePerLengthUnit); + return ToUnit(unitAsVolumePerLengthUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is VolumePerLengthUnit unitAsVolumePerLengthUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumePerLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsVolumePerLengthUnit, unitConverter); } /// @@ -756,59 +803,15 @@ public VolumePerLength ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(VolumePerLengthUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case VolumePerLengthUnit.CubicMeterPerMeter: return _value; - case VolumePerLengthUnit.CubicYardPerFoot: return _value*2.50838208; - case VolumePerLengthUnit.CubicYardPerUsSurveyFoot: return _value*2.50837706323584; - case VolumePerLengthUnit.LiterPerKilometer: return _value/1e6; - case VolumePerLengthUnit.LiterPerMeter: return _value/1000; - case VolumePerLengthUnit.LiterPerMillimeter: return _value; - case VolumePerLengthUnit.OilBarrelPerFoot: return _value/1.91713408; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(VolumePerLengthUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal VolumePerLength ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new VolumePerLength(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(VolumePerLengthUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case VolumePerLengthUnit.CubicMeterPerMeter: return baseUnitValue; - case VolumePerLengthUnit.CubicYardPerFoot: return baseUnitValue/2.50838208; - case VolumePerLengthUnit.CubicYardPerUsSurveyFoot: return baseUnitValue/2.50837706323584; - case VolumePerLengthUnit.LiterPerKilometer: return baseUnitValue*1e6; - case VolumePerLengthUnit.LiterPerMeter: return baseUnitValue*1000; - case VolumePerLengthUnit.LiterPerMillimeter: return baseUnitValue; - case VolumePerLengthUnit.OilBarrelPerFoot: return baseUnitValue*1.91713408; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs index 9309fdc167..4e11b4358f 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs @@ -76,6 +76,8 @@ static VolumetricHeatCapacity() new UnitInfo(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, "MegajoulesPerCubicMeterKelvin", BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.VolumetricHeatCapacity); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -114,6 +116,11 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -246,27 +253,27 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> VolumetricHeatCapacityUnit - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, quantity => new VolumetricHeatCapacity(quantity.Value * 1.4910660e-5, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, quantity => new VolumetricHeatCapacity(quantity.Value * 2.388459e-7, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, quantity => new VolumetricHeatCapacity(quantity.Value, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, quantity => new VolumetricHeatCapacity((quantity.Value * 2.388459e-7) / 1e3d, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, quantity => new VolumetricHeatCapacity((quantity.Value) / 1e3d, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity((quantity.Value) / 1e3d, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, quantity => new VolumetricHeatCapacity((quantity.Value) / 1e6d, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity((quantity.Value) / 1e6d, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity); // Register in unit converter: VolumetricHeatCapacityUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity(quantity.Value / 1.4910660e-5, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity(quantity.Value / 2.388459e-7, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity(quantity.Value, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity((quantity.Value / 2.388459e-7) * 1e3d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity((quantity.Value) * 1e3d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity((quantity.Value) * 1e3d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity((quantity.Value) * 1e6d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => new VolumetricHeatCapacity((quantity.Value) * 1e6d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); } /// @@ -755,11 +762,42 @@ double IQuantity.As(Enum unit) /// /// Converts this VolumetricHeatCapacity to another VolumetricHeatCapacity with the unit representation . /// + /// The unit to convert to. /// A VolumetricHeatCapacity with the specified unit. public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit) { - var convertedValue = GetValueAs(unit); - return new VolumetricHeatCapacity(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this VolumetricHeatCapacity to another VolumetricHeatCapacity using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A VolumetricHeatCapacity with the specified unit. + public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(VolumetricHeatCapacity), Unit, typeof(VolumetricHeatCapacity), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (VolumetricHeatCapacity)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -768,7 +806,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is VolumetricHeatCapacityUnit unitAsVolumetricHeatCapacityUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumetricHeatCapacityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumetricHeatCapacityUnit); + return ToUnit(unitAsVolumetricHeatCapacityUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is VolumetricHeatCapacityUnit unitAsVolumetricHeatCapacityUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumetricHeatCapacityUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsVolumetricHeatCapacityUnit, unitConverter); } /// @@ -793,63 +840,15 @@ public VolumetricHeatCapacity ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(VolumetricHeatCapacityUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit: return _value / 1.4910660e-5; - case VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius: return _value / 2.388459e-7; - case VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius: return _value; - case VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin: return _value; - case VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius: return (_value / 2.388459e-7) * 1e3d; - case VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius: return (_value) * 1e3d; - case VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin: return (_value) * 1e3d; - case VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius: return (_value) * 1e6d; - case VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(VolumetricHeatCapacityUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal VolumetricHeatCapacity ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new VolumetricHeatCapacity(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(VolumetricHeatCapacityUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit: return baseUnitValue * 1.4910660e-5; - case VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius: return baseUnitValue * 2.388459e-7; - case VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius: return baseUnitValue; - case VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin: return baseUnitValue; - case VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius: return (baseUnitValue * 2.388459e-7) / 1e3d; - case VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius: return (baseUnitValue) / 1e3d; - case VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin: return (baseUnitValue) / 1e3d; - case VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius: return (baseUnitValue) / 1e6d; - case VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs index 27c31d5fdd..a20a3aecb2 100644 --- a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs @@ -70,6 +70,8 @@ static WarpingMomentOfInertia() new UnitInfo(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, "MillimetersToTheSixth", new BaseUnits(length: LengthUnit.Millimeter)), }, BaseUnit, Zero, BaseDimensions, QuantityType.WarpingMomentOfInertia); + + RegisterDefaultConversions(DefaultConversionFunctions); } /// @@ -108,6 +110,11 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) #region Static Properties + /// + /// The containing the default generated conversion functions for instances. + /// + public static UnitConverter DefaultConversionFunctions { get; } = new UnitConverter(); + /// public static QuantityInfo Info { get; } @@ -225,21 +232,21 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> WarpingMomentOfInertiaUnit - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.CentimeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.CentimeterToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.DecimeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.DecimeterToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.FootToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.FootToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.InchToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.InchToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.MillimeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MillimeterToTheSixth)); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.CentimeterToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value*1e12, WarpingMomentOfInertiaUnit.CentimeterToTheSixth)); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.DecimeterToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value*1e6, WarpingMomentOfInertiaUnit.DecimeterToTheSixth)); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.FootToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value/Math.Pow(0.3048, 6), WarpingMomentOfInertiaUnit.FootToTheSixth)); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.InchToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value/Math.Pow(2.54e-2, 6), WarpingMomentOfInertiaUnit.InchToTheSixth)); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.MillimeterToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value*1e18, WarpingMomentOfInertiaUnit.MillimeterToTheSixth)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity); // Register in unit converter: WarpingMomentOfInertiaUnit -> BaseUnit - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.FootToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.InchToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToBaseUnit()); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToBaseUnit()); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value/1e12, WarpingMomentOfInertiaUnit.MeterToTheSixth)); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value/1e6, WarpingMomentOfInertiaUnit.MeterToTheSixth)); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.FootToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value*Math.Pow(0.3048, 6), WarpingMomentOfInertiaUnit.MeterToTheSixth)); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.InchToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value*Math.Pow(2.54e-2, 6), WarpingMomentOfInertiaUnit.MeterToTheSixth)); + unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => new WarpingMomentOfInertia(quantity.Value/1e18, WarpingMomentOfInertiaUnit.MeterToTheSixth)); } /// @@ -701,11 +708,42 @@ double IQuantity.As(Enum unit) /// /// Converts this WarpingMomentOfInertia to another WarpingMomentOfInertia with the unit representation . /// + /// The unit to convert to. /// A WarpingMomentOfInertia with the specified unit. public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit) { - var convertedValue = GetValueAs(unit); - return new WarpingMomentOfInertia(convertedValue, unit); + return ToUnit(unit, DefaultConversionFunctions); + } + + /// + /// Converts this WarpingMomentOfInertia to another WarpingMomentOfInertia using the given with the unit representation . + /// + /// The unit to convert to. + /// The to use for the conversion. + /// A WarpingMomentOfInertia with the specified unit. + public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit, UnitConverter unitConverter) + { + if(Unit == unit) + { + // Already in requested units. + return this; + } + else if(unitConverter.TryGetConversionFunction((typeof(WarpingMomentOfInertia), Unit, typeof(WarpingMomentOfInertia), unit), out var conversionFunction)) + { + // Direct conversion to requested unit found. Return the converted quantity. + var converted = conversionFunction(this); + return (WarpingMomentOfInertia)converted; + } + else if(Unit != BaseUnit) + { + // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } /// @@ -714,7 +752,16 @@ IQuantity IQuantity.ToUnit(Enum unit) if(!(unit is WarpingMomentOfInertiaUnit unitAsWarpingMomentOfInertiaUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(WarpingMomentOfInertiaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsWarpingMomentOfInertiaUnit); + return ToUnit(unitAsWarpingMomentOfInertiaUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter) + { + if(!(unit is WarpingMomentOfInertiaUnit unitAsWarpingMomentOfInertiaUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(WarpingMomentOfInertiaUnit)} is supported.", nameof(unit)); + + return ToUnit(unitAsWarpingMomentOfInertiaUnit, unitConverter); } /// @@ -739,57 +786,15 @@ public WarpingMomentOfInertia ToUnit(UnitSystem unitSystem) IQuantity IQuantity.ToUnit(WarpingMomentOfInertiaUnit unit) => ToUnit(unit); /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - switch(Unit) - { - case WarpingMomentOfInertiaUnit.CentimeterToTheSixth: return _value/1e12; - case WarpingMomentOfInertiaUnit.DecimeterToTheSixth: return _value/1e6; - case WarpingMomentOfInertiaUnit.FootToTheSixth: return _value*Math.Pow(0.3048, 6); - case WarpingMomentOfInertiaUnit.InchToTheSixth: return _value*Math.Pow(2.54e-2, 6); - case WarpingMomentOfInertiaUnit.MeterToTheSixth: return _value; - case WarpingMomentOfInertiaUnit.MillimeterToTheSixth: return _value/1e18; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } + IQuantity IQuantity.ToUnit(WarpingMomentOfInertiaUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter); - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - internal WarpingMomentOfInertia ToBaseUnit() - { - var baseUnitValue = GetValueInBaseUnit(); - return new WarpingMomentOfInertia(baseUnitValue, BaseUnit); - } + /// + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); private double GetValueAs(WarpingMomentOfInertiaUnit unit) { - if(Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - switch(unit) - { - case WarpingMomentOfInertiaUnit.CentimeterToTheSixth: return baseUnitValue*1e12; - case WarpingMomentOfInertiaUnit.DecimeterToTheSixth: return baseUnitValue*1e6; - case WarpingMomentOfInertiaUnit.FootToTheSixth: return baseUnitValue/Math.Pow(0.3048, 6); - case WarpingMomentOfInertiaUnit.InchToTheSixth: return baseUnitValue/Math.Pow(2.54e-2, 6); - case WarpingMomentOfInertiaUnit.MeterToTheSixth: return baseUnitValue; - case WarpingMomentOfInertiaUnit.MillimeterToTheSixth: return baseUnitValue*1e18; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } + var converted = ToUnit(unit); + return (double)converted.Value; } #endregion diff --git a/UnitsNet/IQuantity.cs b/UnitsNet/IQuantity.cs index 9146fe083a..f94c031a3c 100644 --- a/UnitsNet/IQuantity.cs +++ b/UnitsNet/IQuantity.cs @@ -56,12 +56,30 @@ public interface IQuantity : IFormattable double Value { get; } /// - /// Converts to a quantity with the given unit representation, which affects things like . + /// Converts this to an in the given . + /// This is equivilent to calling with and + /// the quantity's DefaultConversionFunctions, which are generated by UnitsNet. /// - /// The unit enum value. The unit must be compatible, so for you should provide a value. - /// A new quantity with the given unit. + /// + /// The unit value. The must be compatible with the units of the . + /// For example, if the is a , you should provide a value. + /// + /// Conversion was not possible from this to . + /// A new in the given . IQuantity ToUnit(Enum unit); + /// + /// Converts this to an in the given using the given . + /// + /// + /// The unit value. The must be compatible with the units of the . + /// For example, if the is a , you should provide a value. + /// + /// The to use when converting the . + /// Conversion was not possible from this to . + /// A new in the given . + IQuantity ToUnit(Enum unit, UnitConverter unitConverter); + /// /// Converts to a quantity with a unit determined by the given , which affects things like . /// If multiple units were found for the given , the first match will be used. @@ -120,12 +138,24 @@ public interface IQuantity : IQuantity where TUnitType : Enum new QuantityInfo QuantityInfo { get; } /// - /// Converts to a quantity with the given unit representation, which affects things like . + /// Converts this to an in the given . + /// This is equivilent to calling with and + /// the quantity's DefaultConversionFunctions, which are generated by UnitsNet. /// - /// The unit enum value. - /// A new quantity with the given unit. + /// The unit value. + /// Conversion was not possible from this to . + /// A new in the given . IQuantity ToUnit(TUnitType unit); + /// + /// Converts this to an in the given using the given . + /// + /// The unit value. + /// The to use when converting the . + /// Conversion was not possible from this to . + /// A new in the given . + IQuantity ToUnit(TUnitType unit, UnitConverter unitConverter); + /// /// Converts to a quantity with a unit determined by the given , which affects things like . /// If multiple units were found for the given , the first match will be used. diff --git a/UnitsNet/UnitConverter.cs b/UnitsNet/UnitConverter.cs index e7a949e06a..34e0e834ca 100644 --- a/UnitsNet/UnitConverter.cs +++ b/UnitsNet/UnitConverter.cs @@ -2,7 +2,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Collections.Generic; +using System.Collections.Concurrent; using System.Globalization; using System.Linq; using System.Reflection; @@ -42,8 +42,6 @@ public sealed class UnitConverter /// public static UnitConverter Default { get; } - private readonly Dictionary _conversionFunctions = new Dictionary(); - static UnitConverter() { Default = new UnitConverter(); @@ -51,6 +49,28 @@ static UnitConverter() RegisterDefaultConversions(Default); } + /// + /// Creates a new instance. + /// + public UnitConverter() + { + ConversionFunctions = new ConcurrentDictionary(); + } + + /// + /// Creates a new instance with the copied from . + /// + /// The to copy from. + public UnitConverter(UnitConverter other) + { + ConversionFunctions = new ConcurrentDictionary(other.ConversionFunctions); + } + + private ConcurrentDictionary ConversionFunctions + { + get; + } + /// /// Registers the default conversion functions in the given instance. /// @@ -124,7 +144,7 @@ public void SetConversionFunction(Type fromType, Enum from, Type toType, Enum to /// The quantity conversion function. internal void SetConversionFunction(ConversionFunctionLookupKey lookupKey, ConversionFunction conversionFunction) { - _conversionFunctions[lookupKey] = conversionFunction; + ConversionFunctions[lookupKey] = conversionFunction; } /// @@ -138,7 +158,7 @@ internal void SetConversionFunction(ConversionFunctionLookupKey conve { IQuantity TypelessConversionFunction(IQuantity quantity) => conversionFunction((TQuantity) quantity); - _conversionFunctions[conversionLookup] = TypelessConversionFunction; + ConversionFunctions[conversionLookup] = TypelessConversionFunction; } /// @@ -194,7 +214,7 @@ internal ConversionFunction GetConversionFunction(ConversionFunctionLookupKey lo if (lookupKey.Item1 == lookupKey.Item3 && Equals(lookupKey.Item2, lookupKey.Item4)) return EchoFunction; - return _conversionFunctions[lookupKey]; + return ConversionFunctions[lookupKey]; } /// @@ -249,7 +269,7 @@ public bool TryGetConversionFunction(Type fromType, Enum from, Type toType, Enum /// true if set; otherwise, false. public bool TryGetConversionFunction(ConversionFunctionLookupKey lookupKey, out ConversionFunction conversionFunction) { - return _conversionFunctions.TryGetValue(lookupKey, out conversionFunction); + return ConversionFunctions.TryGetValue(lookupKey, out conversionFunction); } ///