diff --git a/Build/build-functions.psm1 b/Build/build-functions.psm1 index 398b3dae35..dfc0361483 100644 --- a/Build/build-functions.psm1 +++ b/Build/build-functions.psm1 @@ -63,8 +63,7 @@ function Start-Tests { $projectPaths = @( "UnitsNet.Tests\UnitsNet.Tests.csproj", "UnitsNet.NumberExtensions.Tests\UnitsNet.NumberExtensions.Tests.csproj", - "UnitsNet.Serialization.JsonNet.Tests\UnitsNet.Serialization.JsonNet.Tests.csproj", - "UnitsNet.Serialization.JsonNet.CompatibilityTests\UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj" + "UnitsNet.Serialization.JsonNet.Tests\UnitsNet.Serialization.JsonNet.Tests.csproj" ) # Parent dir must exist before xunit tries to write files to it diff --git a/CodeGen/CodeGen.csproj b/CodeGen/CodeGen.csproj index 8e71a7f710..091df14572 100644 --- a/CodeGen/CodeGen.csproj +++ b/CodeGen/CodeGen.csproj @@ -11,7 +11,7 @@ - + diff --git a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs index cf48ef7b4d..edebcc1281 100644 --- a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs @@ -25,7 +25,7 @@ public QuantityGenerator(Quantity quantity) throw new ArgumentException($"No unit found with SingularName equal to BaseUnit [{_quantity.BaseUnit}]. This unit must be defined.", nameof(quantity)); - _valueType = quantity.ValueType; + _valueType = "QuantityValue";// quantity.ValueType; _unitEnumName = $"{quantity.Name}Unit"; BaseDimensions baseDimensions = quantity.BaseDimensions; @@ -77,14 +77,14 @@ public partial struct {_quantity.Name} : IQuantity<{_unitEnumName}>, "); Writer.W("IDecimalQuantity, "); } - Writer.WL($"IComparable, IComparable<{_quantity.Name}>, IConvertible, IFormattable"); + Writer.WL($"IEquatable<{_quantity.Name}>, IComparable, IComparable<{_quantity.Name}>, IConvertible, IFormattable"); Writer.WL($@" {{ /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = ""Value"", Order = 0)] - private readonly {_quantity.ValueType} _value; + private readonly {_valueType} _value; /// /// The unit this quantity was constructed with. @@ -176,9 +176,9 @@ private void GenerateInstanceConstructors() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public {_quantity.Name}({_quantity.ValueType} value, {_unitEnumName} unit) + public {_quantity.Name}({_valueType} value, {_unitEnumName} unit) {{"); - Writer.WL(_quantity.ValueType == "double" + Writer.WL(_valueType == "double" ? @" _value = Guard.EnsureValidNumber(value, nameof(value));" : @" @@ -203,7 +203,7 @@ private void GenerateInstanceConstructors() var firstUnitInfo = unitInfos.FirstOrDefault(); "); - Writer.WL(_quantity.ValueType == "double" + Writer.WL(_valueType == "double" ? @" _value = Guard.EnsureValidNumber(value, nameof(value));" : @" @@ -262,15 +262,15 @@ private void GenerateProperties() public {_valueType} Value => _value; "); - // Need to provide explicit interface implementation for decimal quantities like Information - if (_quantity.ValueType != "double") - Writer.WL(@" - double IQuantity.Value => (double) _value; + Writer.WL($@" + /// + {_valueType} IQuantity.Value => _value; "); + // Need to provide explicit interface implementation for decimal quantities like Information if (_quantity.ValueType == "decimal") Writer.WL(@" /// - decimal IDecimalQuantity.Value => _value; + decimal IDecimalQuantity.Value => (decimal)_value; "); Writer.WL($@" @@ -306,11 +306,11 @@ private void GenerateConversionProperties() Writer.WL($@" /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// "); Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); Writer.WL($@" - public double {unit.PluralName} => As({_unitEnumName}.{unit.SingularName}); + public {_valueType} {unit.PluralName} => As({_unitEnumName}.{unit.SingularName}); "); } @@ -426,7 +426,7 @@ private void GenerateStaticFactoryMethods() /// If value is NaN or Infinity."); Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); Writer.WL($@" - public static {_quantity.Name} From{unit.PluralName}(QuantityValue {valueParamName}) + public static {_quantity.Name} From{unit.PluralName}({_valueType} {valueParamName}) {{ {_valueType} value = ({_valueType}) {valueParamName}; return new {_quantity.Name}(value, {_unitEnumName}.{unit.SingularName}); @@ -651,7 +651,7 @@ private void GenerateArithmeticOperators() }} /// Get ratio value from dividing by . - public static double operator /({_quantity.Name} left, {_quantity.Name} right) + public static {_valueType} operator /({_quantity.Name} left, {_quantity.Name} right) {{ return left.{_baseUnit.PluralName} / right.{_baseUnit.PluralName}; }} @@ -679,7 +679,7 @@ private void GenerateLogarithmicArithmeticOperators() {{ // Logarithmic addition // Formula: {x} * log10(10^(x/{x}) + 10^(y/{x})) - return new {_quantity.Name}({x} * Math.Log10(Math.Pow(10, left.Value/{x}) + Math.Pow(10, right.GetValueAs(left.Unit)/{x})), left.Unit); + return new {_quantity.Name}({x} * Math.Log10(Math.Pow(10, (double)left.Value/{x}) + Math.Pow(10, (double)right.GetValueAs(left.Unit)/{x})), left.Unit); }} /// Get from logarithmic subtraction of two . @@ -687,7 +687,7 @@ private void GenerateLogarithmicArithmeticOperators() {{ // Logarithmic subtraction // Formula: {x} * log10(10^(x/{x}) - 10^(y/{x})) - return new {_quantity.Name}({x} * Math.Log10(Math.Pow(10, left.Value/{x}) - Math.Pow(10, right.GetValueAs(left.Unit)/{x})), left.Unit); + return new {_quantity.Name}({x} * Math.Log10(Math.Pow(10, (double)left.Value/{x}) - Math.Pow(10, (double)right.GetValueAs(left.Unit)/{x})), left.Unit); }} /// Get from logarithmic multiplication of value and . @@ -751,6 +751,19 @@ private void GenerateEqualityAndComparison() return left.Value > right.GetValueAs(left.Unit); }} + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==({_quantity.Name} left, {_quantity.Name} right) + {{ + return left.Equals(right); + }} + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=({_quantity.Name} left, {_quantity.Name} right) + {{ + return !(left == right); + }} + /// public int CompareTo(object obj) {{ @@ -763,7 +776,29 @@ public int CompareTo(object obj) /// public int CompareTo({_quantity.Name} other) {{ - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + }} + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + {{ + if (obj is null || !(obj is {_quantity.Name} obj{_quantity.Name})) + return false; + return Equals(obj{_quantity.Name}); + }} + + /// + /// Consider using for safely comparing floating point values. + public bool Equals({_quantity.Name} other) + {{ + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); }} /// @@ -806,13 +841,13 @@ public int CompareTo({_quantity.Name} other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals({_quantity.Name} other, double tolerance, ComparisonType comparisonType) + public bool Equals({_quantity.Name} other, {_valueType} tolerance, ComparisonType comparisonType) {{ if (tolerance < 0) throw new ArgumentOutOfRangeException(""tolerance"", ""Tolerance must be greater than or equal to 0.""); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + {_valueType} thisValue = this.Value; + {_valueType} otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); }} @@ -823,7 +858,7 @@ public bool Equals({_quantity.Name} other, double tolerance, ComparisonType comp /// A hash code for the current {_quantity.Name}. public override int GetHashCode() {{ - return new {{ Info.Name, Value, Unit }}.GetHashCode(); + return Info.Name.GetHashCode(); }} #endregion @@ -839,17 +874,30 @@ private void GenerateConversionMethods() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As({_unitEnumName} unit) + public {_valueType} As({_unitEnumName} unit) {{ - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); }} +"); + + if (_valueType == "decimal") + { + Writer.WL($@" + + {_valueType} IQuantity<{_unitEnumName}>.As({_unitEnumName} unit) + {{ + return ({_valueType})As(unit); + }} +"); + } + + Writer.WL($@" /// - public double As(UnitSystem unitSystem) + public {_valueType} As(UnitSystem unitSystem) {{ if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -862,14 +910,27 @@ public double As(UnitSystem unitSystem) return As(firstUnitInfo.Value); }} +"); + + if (_valueType == "decimal") + { + Writer.WL($@" + /// + {_valueType} IQuantity.As(UnitSystem unitSystem) + {{ + return ({_valueType})As(unitSystem); + }} +"); + } + Writer.WL($@" /// - double IQuantity.As(Enum unit) + {_valueType} IQuantity.As(Enum unit) {{ - if (!(unit is {_unitEnumName} unitAs{_unitEnumName})) + if (!(unit is {_unitEnumName} typedUnit)) throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit)); - return As(unitAs{_unitEnumName}); + return ({_valueType})As(typedUnit); }} /// @@ -901,7 +962,7 @@ double IQuantity.As(Enum unit) var converted = conversionFunction(this); return ({_quantity.Name})converted; }} - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof({_unitEnumName}), unit)) {{ // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -909,17 +970,17 @@ double IQuantity.As(Enum unit) }} else {{ - throw new NotImplementedException($""Can not convert {{Unit}} to {{unit}}.""); + throw new NotSupportedException($""Can not convert {{Unit}} to {{unit}}.""); }} }} /// IQuantity IQuantity.ToUnit(Enum unit) {{ - if (!(unit is {_unitEnumName} unitAs{_unitEnumName})) + if (!(unit is {_unitEnumName} typedUnit)) throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit)); - return ToUnit(unitAs{_unitEnumName}, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); }} /// diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs index b9a4f2db68..2c7d1a3d8a 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs @@ -102,7 +102,7 @@ public abstract partial class {_quantity.Name}TestsBase : QuantityTestsBase continue; Writer.WL($@" - protected abstract double {unit.PluralName}InOne{_baseUnit.SingularName} {{ get; }}"); + protected abstract {_quantity.ValueType} {unit.PluralName}InOne{_baseUnit.SingularName} {{ get; }}"); } Writer.WL(""); @@ -114,12 +114,12 @@ public abstract partial class {_quantity.Name}TestsBase : QuantityTestsBase continue; Writer.WL($@" - protected virtual double {unit.PluralName}Tolerance {{ get {{ return 1e-5; }} }}"); + protected virtual {_quantity.ValueType} {unit.PluralName}Tolerance {{ get {{ return { (_quantity.ValueType == "decimal" ? "1E-9m" : "1E-5") }; }} }}"); } Writer.WL($@" // ReSharper restore VirtualMemberNeverOverriden.Global - protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor({_unitEnumName} unit) + protected ({_quantity.ValueType} UnitsInBaseUnit, {_quantity.ValueType} Tolerence) GetConversionFactor({_unitEnumName} unit) {{ return unit switch {{"); @@ -260,7 +260,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) {{ - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); }} else @@ -351,14 +351,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit({_unitEnumName} unit) {{ - var inBaseUnits = {_quantity.Name}.From(1.0, {_quantity.Name}.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = {_quantity.Name}.From(1.0, {_quantity.Name}.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); }} + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + {{ + var inBaseUnit = {_quantity.Name}.From(1.0, {_quantity.Name}.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default({_unitEnumName}))); + }} + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual({_unitEnumName} unit) @@ -368,12 +375,12 @@ public void ToUnit_WithSameUnits_AreEqual({_unitEnumName} unit) Assert.Equal(quantity, toUnitWithSameUnit); }} - [Theory] + [Theory{(_quantity.Units.Length == 1 ? "(Skip = \"Multiple units required\")" : string.Empty)}] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit({_unitEnumName} unit) {{ - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = {_quantity.Name}.Units.Where(u => u != {_quantity.Name}.BaseUnit).DefaultIfEmpty({_quantity.Name}.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = {_quantity.Name}.Units.First(u => u != {_quantity.Name}.BaseUnit); var quantity = {_quantity.Name}.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -612,8 +619,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); }} [Fact] @@ -647,36 +655,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); }} [Fact] public void Convert_ToInt32_EqualsValueAsSameType() {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); }} [Fact] public void Convert_ToInt64_EqualsValueAsSameType() {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); }} [Fact] public void Convert_ToSByte_EqualsValueAsSameType() {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); }} [Fact] public void Convert_ToSingle_EqualsValueAsSameType() {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); }} [Fact] @@ -689,22 +702,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); }} [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); }} [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); }} [Fact] @@ -746,7 +762,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() {{ var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal(new {{{_quantity.Name}.Info.Name, quantity.Value, quantity.Unit}}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal({_quantity.Name}.Info.Name.GetHashCode(), quantity.GetHashCode()); }} "); diff --git a/Common/UnitDefinitions/Angle.json b/Common/UnitDefinitions/Angle.json index 1f7b908af1..2b240f025d 100644 --- a/Common/UnitDefinitions/Angle.json +++ b/Common/UnitDefinitions/Angle.json @@ -108,8 +108,8 @@ { "SingularName": "Tilt", "PluralName": "Tilt", - "FromUnitToBaseFunc": "Math.Asin({x}) * 180 / Math.PI", - "FromBaseToUnitFunc": "Math.Sin({x} / 180 * Math.PI)", + "FromUnitToBaseFunc": "Math.Asin((double){x}) * 180 / Math.PI", + "FromBaseToUnitFunc": "Math.Sin((double){x} / 180 * Math.PI)", "Localization": [ { "Culture": "en-US", diff --git a/Common/UnitDefinitions/Frequency.json b/Common/UnitDefinitions/Frequency.json index 400a4f7f87..eb901b4740 100644 --- a/Common/UnitDefinitions/Frequency.json +++ b/Common/UnitDefinitions/Frequency.json @@ -95,7 +95,7 @@ { "SingularName": "BUnit", "PluralName": "BUnits", - "FromUnitToBaseFunc": "Math.Sqrt({x} * 1e3)", + "FromUnitToBaseFunc": "Math.Sqrt((double){x} * 1e3)", "FromBaseToUnitFunc": "{x} * {x} * 1e-3", "Localization": [ { diff --git a/Common/UnitDefinitions/Power.json b/Common/UnitDefinitions/Power.json index 89f98458eb..ce491fa507 100644 --- a/Common/UnitDefinitions/Power.json +++ b/Common/UnitDefinitions/Power.json @@ -85,8 +85,8 @@ { "SingularName": "BritishThermalUnitPerHour", "PluralName": "BritishThermalUnitsPerHour", - "FromUnitToBaseFunc": "{x} * 0.293071m", - "FromBaseToUnitFunc": "{x} / 0.293071m", + "FromUnitToBaseFunc": "{x} * 0.29307107017m", + "FromBaseToUnitFunc": "{x} / 0.29307107017m", "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { diff --git a/Common/UnitDefinitions/Pressure.json b/Common/UnitDefinitions/Pressure.json index 89b22e4e3c..86f5bd3018 100644 --- a/Common/UnitDefinitions/Pressure.json +++ b/Common/UnitDefinitions/Pressure.json @@ -380,8 +380,8 @@ { "SingularName": "MeterOfElevation", "PluralName": "MetersOfElevation", - "FromUnitToBaseFunc": "Math.Pow(1.0 - ({x} / 44307.69396), 5.2553026003237266401799415610351) * 101325.0", - "FromBaseToUnitFunc": "(1.0 - Math.Pow({x} / 101325.0, 0.190284)) * 44307.69396", + "FromUnitToBaseFunc": "Math.Pow(1.0 - ((double){x} / 44307.69396), 5.2553026003237266401799415610351) * 101325.0", + "FromBaseToUnitFunc": "(1.0 - Math.Pow((double){x} / 101325.0, 0.190284)) * 44307.69396", "Localization": [ { "Culture": "en-US", @@ -392,8 +392,8 @@ { "SingularName": "FootOfElevation", "PluralName": "FeetOfElevation", - "FromUnitToBaseFunc": "Math.Pow(1.0 - ({x} / 145366.45), 5.2553026003237266401799415610351) * 101325.0", - "FromBaseToUnitFunc": "(1.0 - Math.Pow({x} / 101325.0, 0.190284)) * 145366.45", + "FromUnitToBaseFunc": "Math.Pow(1.0 - ((double){x} / 145366.45), 5.2553026003237266401799415610351) * 101325.0", + "FromBaseToUnitFunc": "(1.0 - Math.Pow((double){x} / 101325.0, 0.190284)) * 145366.45", "Localization": [ { "Culture": "en-US", diff --git a/Common/UnitDefinitions/PressureChangeRate.json b/Common/UnitDefinitions/PressureChangeRate.json index befcc49275..6f60ee8d25 100644 --- a/Common/UnitDefinitions/PressureChangeRate.json +++ b/Common/UnitDefinitions/PressureChangeRate.json @@ -50,11 +50,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mmHg/s" ], + "Abbreviations": [ "mmHg/s" ] }, { "Culture": "ru-RU", - "Abbreviations": [ "mmHg/с" ], + "Abbreviations": [ "mmHg/с" ] } ] }, diff --git a/UnitsNet.Benchmark/Program.cs b/UnitsNet.Benchmark/Program.cs index 25d32af6e7..7cbd986157 100644 --- a/UnitsNet.Benchmark/Program.cs +++ b/UnitsNet.Benchmark/Program.cs @@ -24,15 +24,15 @@ public class UnitsNetBenchmarks [Benchmark] [BenchmarkCategory("Transformation")] - public double ToProperty() => _length.Centimeters; + public QuantityValue ToProperty() => _length.Centimeters; [Benchmark] [BenchmarkCategory("Transformation, Value")] - public double As() => _length.As(LengthUnit.Centimeter); + public QuantityValue As() => _length.As(LengthUnit.Centimeter); [Benchmark] [BenchmarkCategory("Transformation, Value")] - public double As_SI() => _length.As(UnitSystem.SI); + public QuantityValue As_SI() => _length.As(UnitSystem.SI); [Benchmark] [BenchmarkCategory("Transformation, Quantity")] @@ -64,11 +64,11 @@ public class UnitsNetBenchmarks [Benchmark] [BenchmarkCategory("Transformation, Value")] - public double IQuantity_As() => _lengthIQuantity.As(LengthUnit.Centimeter); + public QuantityValue IQuantity_As() => _lengthIQuantity.As(LengthUnit.Centimeter); [Benchmark] [BenchmarkCategory("Transformation, Value")] - public double IQuantity_As_SI() => _lengthIQuantity.As(UnitSystem.SI); + public QuantityValue IQuantity_As_SI() => _lengthIQuantity.As(UnitSystem.SI); [Benchmark] [BenchmarkCategory("Transformation, Quantity")] diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Angle.g.cs index 1305cad4f6..07fcb9af0b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Angle.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Angle.g.cs @@ -314,7 +314,7 @@ private double GetValueInBaseUnit() AngleUnit.NatoMil => _value * 9 / 160, AngleUnit.Radian => _value * 180 / 3.1415926535897931, AngleUnit.Revolution => _value * 360, - AngleUnit.Tilt => Math.Asin(_value) * 180 / 3.1415926535897931, + AngleUnit.Tilt => Math.Asin((double)_value) * 180 / 3.1415926535897931, _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") }; } @@ -343,7 +343,7 @@ private double GetValueAs(AngleUnit unit) AngleUnit.NatoMil => baseUnitValue * 160 / 9, AngleUnit.Radian => baseUnitValue / 180 * 3.1415926535897931, AngleUnit.Revolution => baseUnitValue / 360, - AngleUnit.Tilt => Math.Sin(baseUnitValue / 180 * 3.1415926535897931), + AngleUnit.Tilt => Math.Sin((double)baseUnitValue / 180 * 3.1415926535897931), _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") }; } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Frequency.g.cs index 735e48489b..805a01cbe5 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Frequency.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Frequency.g.cs @@ -245,7 +245,7 @@ private double GetValueInBaseUnit() return Unit switch { FrequencyUnit.BeatPerMinute => _value / 60, - FrequencyUnit.BUnit => Math.Sqrt(_value * 1e3), + FrequencyUnit.BUnit => Math.Sqrt((double)_value * 1e3), FrequencyUnit.CyclePerHour => _value / 3600, FrequencyUnit.CyclePerMinute => _value / 60, FrequencyUnit.Gigahertz => (_value) * 1e9d, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Power.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Power.g.cs index 5c25292799..e10cb3d208 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Power.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Power.g.cs @@ -410,7 +410,7 @@ private double GetValueInBaseUnit() return Unit switch { PowerUnit.BoilerHorsepower => _value * 9812.5d, - PowerUnit.BritishThermalUnitPerHour => _value * 0.293071d, + PowerUnit.BritishThermalUnitPerHour => _value * 0.29307107017d, PowerUnit.Decawatt => (_value) * 1e1d, PowerUnit.Deciwatt => (_value) * 1e-1d, PowerUnit.ElectricalHorsepower => _value * 746d, @@ -419,11 +419,11 @@ private double GetValueInBaseUnit() PowerUnit.Gigawatt => (_value) * 1e9d, PowerUnit.HydraulicHorsepower => _value * 745.69988145d, PowerUnit.JoulePerHour => _value / 3600d, - PowerUnit.KilobritishThermalUnitPerHour => (_value * 0.293071d) * 1e3d, + PowerUnit.KilobritishThermalUnitPerHour => (_value * 0.29307107017d) * 1e3d, PowerUnit.KilojoulePerHour => (_value / 3600d) * 1e3d, PowerUnit.Kilowatt => (_value) * 1e3d, PowerUnit.MechanicalHorsepower => _value * 745.69d, - PowerUnit.MegabritishThermalUnitPerHour => (_value * 0.293071d) * 1e6d, + PowerUnit.MegabritishThermalUnitPerHour => (_value * 0.29307107017d) * 1e6d, PowerUnit.MegajoulePerHour => (_value / 3600d) * 1e6d, PowerUnit.Megawatt => (_value) * 1e6d, PowerUnit.MetricHorsepower => _value * 735.49875d, @@ -449,7 +449,7 @@ private double GetValueAs(PowerUnit unit) return unit switch { PowerUnit.BoilerHorsepower => baseUnitValue / 9812.5d, - PowerUnit.BritishThermalUnitPerHour => baseUnitValue / 0.293071d, + PowerUnit.BritishThermalUnitPerHour => baseUnitValue / 0.29307107017d, PowerUnit.Decawatt => (baseUnitValue) / 1e1d, PowerUnit.Deciwatt => (baseUnitValue) / 1e-1d, PowerUnit.ElectricalHorsepower => baseUnitValue / 746d, @@ -458,11 +458,11 @@ private double GetValueAs(PowerUnit unit) PowerUnit.Gigawatt => (baseUnitValue) / 1e9d, PowerUnit.HydraulicHorsepower => baseUnitValue / 745.69988145d, PowerUnit.JoulePerHour => baseUnitValue * 3600d, - PowerUnit.KilobritishThermalUnitPerHour => (baseUnitValue / 0.293071d) / 1e3d, + PowerUnit.KilobritishThermalUnitPerHour => (baseUnitValue / 0.29307107017d) / 1e3d, PowerUnit.KilojoulePerHour => (baseUnitValue * 3600d) / 1e3d, PowerUnit.Kilowatt => (baseUnitValue) / 1e3d, PowerUnit.MechanicalHorsepower => baseUnitValue / 745.69d, - PowerUnit.MegabritishThermalUnitPerHour => (baseUnitValue / 0.293071d) / 1e6d, + PowerUnit.MegabritishThermalUnitPerHour => (baseUnitValue / 0.29307107017d) / 1e6d, PowerUnit.MegajoulePerHour => (baseUnitValue * 3600d) / 1e6d, PowerUnit.Megawatt => (baseUnitValue) / 1e6d, PowerUnit.MetricHorsepower => baseUnitValue / 735.49875d, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Pressure.g.cs index fe89149b52..2e773ff8a1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Pressure.g.cs @@ -646,7 +646,7 @@ private double GetValueInBaseUnit() PressureUnit.Decapascal => (_value) * 1e1d, PressureUnit.Decibar => (_value * 1e5) * 1e-1d, PressureUnit.DynePerSquareCentimeter => _value * 1.0e-1, - PressureUnit.FootOfElevation => Math.Pow(1.0 - (_value / 145366.45), 5.2553026003237266401799415610351) * 101325.0, + PressureUnit.FootOfElevation => Math.Pow(1.0 - ((double)_value / 145366.45), 5.2553026003237266401799415610351) * 101325.0, PressureUnit.FootOfHead => _value * 2989.0669, PressureUnit.Gigapascal => (_value) * 1e9d, PressureUnit.Hectopascal => (_value) * 1e2d, @@ -666,7 +666,7 @@ private double GetValueInBaseUnit() PressureUnit.Megabar => (_value * 1e5) * 1e6d, PressureUnit.MeganewtonPerSquareMeter => (_value) * 1e6d, PressureUnit.Megapascal => (_value) * 1e6d, - PressureUnit.MeterOfElevation => Math.Pow(1.0 - (_value / 44307.69396), 5.2553026003237266401799415610351) * 101325.0, + PressureUnit.MeterOfElevation => Math.Pow(1.0 - ((double)_value / 44307.69396), 5.2553026003237266401799415610351) * 101325.0, PressureUnit.MeterOfHead => _value * 9804.139432, PressureUnit.Microbar => (_value * 1e5) * 1e-6d, PressureUnit.Micropascal => (_value) * 1e-6d, @@ -706,7 +706,7 @@ private double GetValueAs(PressureUnit unit) PressureUnit.Decapascal => (baseUnitValue) / 1e1d, PressureUnit.Decibar => (baseUnitValue / 1e5) / 1e-1d, PressureUnit.DynePerSquareCentimeter => baseUnitValue / 1.0e-1, - PressureUnit.FootOfElevation => (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 145366.45, + PressureUnit.FootOfElevation => (1.0 - Math.Pow((double)baseUnitValue / 101325.0, 0.190284)) * 145366.45, PressureUnit.FootOfHead => baseUnitValue * 0.000334552565551, PressureUnit.Gigapascal => (baseUnitValue) / 1e9d, PressureUnit.Hectopascal => (baseUnitValue) / 1e2d, @@ -726,7 +726,7 @@ private double GetValueAs(PressureUnit unit) PressureUnit.Megabar => (baseUnitValue / 1e5) / 1e6d, PressureUnit.MeganewtonPerSquareMeter => (baseUnitValue) / 1e6d, PressureUnit.Megapascal => (baseUnitValue) / 1e6d, - PressureUnit.MeterOfElevation => (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 44307.69396, + PressureUnit.MeterOfElevation => (1.0 - Math.Pow((double)baseUnitValue / 101325.0, 0.190284)) * 44307.69396, PressureUnit.MeterOfHead => baseUnitValue * 0.0001019977334, PressureUnit.Microbar => (baseUnitValue / 1e5) / 1e-6d, PressureUnit.Micropascal => (baseUnitValue) / 1e-6d, diff --git a/UnitsNet.NumberExtensions.Tests/UnitsNet.NumberExtensions.Tests.csproj b/UnitsNet.NumberExtensions.Tests/UnitsNet.NumberExtensions.Tests.csproj index 0d09ca57fd..f0c5f3c1d4 100644 --- a/UnitsNet.NumberExtensions.Tests/UnitsNet.NumberExtensions.Tests.csproj +++ b/UnitsNet.NumberExtensions.Tests/UnitsNet.NumberExtensions.Tests.csproj @@ -25,8 +25,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj deleted file mode 100644 index 8bcee805f8..0000000000 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - net6.0 - UnitsNet.Serialization.JsonNet.CompatibilityTests - latest - true - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs deleted file mode 100644 index 6775d8769d..0000000000 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs +++ /dev/null @@ -1,464 +0,0 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace UnitsNet.Serialization.JsonNet.CompatibilityTests -{ - public class UnitsNetJsonConverterTests - { - private readonly JsonSerializerSettings _jsonSerializerSettings; - - protected UnitsNetJsonConverterTests() - { - _jsonSerializerSettings = new JsonSerializerSettings {Formatting = Formatting.Indented}; - _jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); - } - - private string SerializeObject(object obj) - { - return JsonConvert.SerializeObject(obj, _jsonSerializerSettings).Replace("\r\n", "\n"); - } - - private T DeserializeObject(string json) - { - return JsonConvert.DeserializeObject(json, _jsonSerializerSettings); - } - - public class Serialize : UnitsNetJsonConverterTests - { - [Fact] - public void Information_CanSerializeVeryLargeValues() - { - Information i = Information.FromExabytes(1E+9); - var expectedJson = "{\n \"Unit\": \"InformationUnit.Exabyte\",\n \"Value\": 1000000000.0\n}"; - - string json = SerializeObject(i); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void Mass_ExpectConstructedValueAndUnit() - { - Mass mass = Mass.FromPounds(200); - var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; - - string json = SerializeObject(mass); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void Information_ExpectConstructedValueAndUnit() - { - Information quantity = Information.FromKilobytes(54); - var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; - - string json = SerializeObject(quantity); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void NonNullNullableValue_ExpectJsonUnaffected() - { - Mass? nullableMass = Mass.FromKilograms(10); - var expectedJson = "{\n \"Unit\": \"MassUnit.Kilogram\",\n \"Value\": 10.0\n}"; - - string json = SerializeObject(nullableMass); - - // There shouldn't be any change in the JSON for the non-null nullable value. - Assert.Equal(expectedJson, json); - } - - [Fact] - public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() - { - var testObj = new TestObj - { - NullableFrequency = Frequency.FromHertz(10), - NonNullableFrequency = Frequency.FromHertz(10) - }; - // Ugly manually formatted JSON string is used because string literals with newlines are rendered differently - // on the build server (i.e. the build server uses '\r' instead of '\n') - string expectedJson = "{\n" + - " \"NullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " \"NonNullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "}"; - - string json = SerializeObject(testObj); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void NullValue_ExpectJsonContainsNullString() - { - string json = SerializeObject(null); - Assert.Equal("null", json); - } - - [Fact] - public void Ratio_ExpectDecimalFractionsUsedAsBaseValueAndUnit() - { - Ratio ratio = Ratio.FromPartsPerThousand(250); - var expectedJson = "{\n \"Unit\": \"RatioUnit.PartPerThousand\",\n \"Value\": 250.0\n}"; - - string json = SerializeObject(ratio); - - Assert.Equal(expectedJson, json); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void ArrayValue_ExpectJsonArray() - { - Frequency[] testObj = new Frequency[] { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - - string expectedJson = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; - - string json = SerializeObject(testObj); - - Assert.Equal(expectedJson, json); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void EmptyArrayValue_ExpectJsonArray() - { - Frequency[] testObj = { }; - - string expectedJson = "[]"; - - string json = SerializeObject(testObj); - Assert.Equal(expectedJson, json); - } - } - - public class Deserialize : UnitsNetJsonConverterTests - { - [Fact] - public void Information_CanDeserializeVeryLargeValues() - { - Information original = Information.FromExabytes(1E+9); - string json = SerializeObject(original); - var deserialized = DeserializeObject(json); - - Assert.Equal(original, deserialized); - } - - [Fact] - public void Mass_ExpectJsonCorrectlyDeserialized() - { - Mass originalMass = Mass.FromKilograms(33.33); - string json = SerializeObject(originalMass); - - var deserializedMass = DeserializeObject(json); - - Assert.Equal(originalMass, deserializedMass); - } - - [Fact] - public void NonNullNullableValue_ExpectValueDeserializedCorrectly() - { - Mass? nullableMass = Mass.FromKilograms(10); - string json = SerializeObject(nullableMass); - - Mass? deserializedNullableMass = DeserializeObject(json); - - Assert.Equal(nullableMass.Value, deserializedNullableMass); - } - - [Fact] - public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly() - { - var testObj = new TestObj - { - NullableFrequency = Frequency.FromHertz(10), - NonNullableFrequency = Frequency.FromHertz(10) - }; - string json = SerializeObject(testObj); - - var deserializedTestObj = DeserializeObject(json); - - Assert.Equal(testObj.NullableFrequency, deserializedTestObj.NullableFrequency); - } - - [Fact] - public void NullValue_ExpectNullReturned() - { - string json = SerializeObject(null); - var deserializedNullMass = DeserializeObject(json); - - Assert.Null(deserializedNullMass); - } - - [Fact] - public void NullValueNestedInObject_ExpectValueDeserializedToNullCorrectly() - { - var testObj = new TestObj - { - NullableFrequency = null, - NonNullableFrequency = Frequency.FromHertz(10) - }; - string json = SerializeObject(testObj); - - var deserializedTestObj = DeserializeObject(json); - - Assert.Null(deserializedTestObj.NullableFrequency); - } - - [Fact] - public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() - { - Mass originalMass = Mass.FromKilograms(33.33); - string json = SerializeObject(originalMass); - // Someone manually changed the serialized JSON string to 1000 grams. - json = json.Replace("33.33", "1000"); - json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); - - var deserializedMass = DeserializeObject(json); - - // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is - // still deserializable, and the correct value of 1000 g is obtained. - Assert.Equal(1000, deserializedMass.Grams); - } - - [Fact] - public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = Power.FromWatts(10) - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - - var deserializedTestObject = JsonConvert.DeserializeObject(json,jsonSerializerSettings); - - Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); - Assert.Equal(Power.FromWatts(10), (Power)deserializedTestObject.Value); - } - - [Fact] - public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = 10.0 - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, (double)deserializedTestObject.Value); - } - - [Fact] - public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = new ComparableClass() { Value = 10 } - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); - } - - [Fact] - public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() - { - TestObjWithValueAndUnit testObjWithValueAndUnit = new TestObjWithValueAndUnit() - { - Value = 5, - Unit = "Test", - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); - TestObjWithValueAndUnit deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); - Assert.Equal(5d, deserializedTestObject.Value); - Assert.Equal("Test", deserializedTestObject.Unit); - } - - [Fact] - public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeserialized() - { - TestObjWithThreeIComparable testObjWithIComparable = new TestObjWithThreeIComparable() - { - Value1 = 10.0, - Value2 = Power.FromWatts(19), - Value3 = new ComparableClass() { Value = 10 }, - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(double), deserializedTestObject.Value1.GetType()); - Assert.Equal(10d, deserializedTestObject.Value1); - Assert.Equal(typeof(Power), deserializedTestObject.Value2.GetType()); - Assert.Equal(Power.FromWatts(19), deserializedTestObject.Value2); - Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value3.GetType()); - Assert.Equal(testObjWithIComparable.Value3, deserializedTestObject.Value3); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void ArrayOfUnits_ExpectCorrectlyDeserialized() - { - Frequency[] expected = new Frequency[] { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - - string json = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; - - Frequency[] result = DeserializeObject(json); - - Assert.Equal(expected, result); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void MultiDimArrayOfUnits_ExpectCorrectlyDeserialized() - { - Frequency[,] expected = { { Frequency.FromHertz(10), Frequency.FromHertz(10) }, { Frequency.FromHertz(10), Frequency.FromHertz(10) } }; - - string json = "[\n" + - " [\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - " ],\n" + - " [\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - " ]\n" + - "]"; - - Frequency[,] result = DeserializeObject(json); - - Assert.Equal(expected, result); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void EmptyArray_ExpectCorrectlyDeserialized() - { - string json = "[]"; - - Frequency[] result = DeserializeObject(json); - - Assert.Empty(result); - } - - private static JsonSerializerSettings CreateJsonSerializerSettings() - { - var jsonSerializerSettings = new JsonSerializerSettings() - { - Formatting = Formatting.Indented, - TypeNameHandling = TypeNameHandling.Auto - }; - jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); - return jsonSerializerSettings; - } - } - - private class TestObj - { - public Frequency? NullableFrequency { get; set; } - public Frequency NonNullableFrequency { get; set; } - } - - private class TestObjWithValueAndUnit : IComparable - { - public double Value { get; set; } - public string Unit { get; set; } - - public int CompareTo(object obj) - { - return ((IComparable)Value).CompareTo(obj); - } - } - - private class ComparableClass : IComparable - { - public int Value { get; set; } - public int CompareTo(object obj) - { - return ((IComparable)Value).CompareTo(obj); - } - - // Needed for virfying that the deserialized object is the same, should not affect the serilization code - public override bool Equals(object obj) - { - if (obj == null || GetType() != obj.GetType()) - { - return false; - } - return Value.Equals(((ComparableClass)obj).Value); - } - - public override int GetHashCode() - { - return Value.GetHashCode(); - } - } - - private class TestObjWithIComparable - { - public IComparable Value { get; set; } - } - - private class TestObjWithThreeIComparable - { - public IComparable Value1 { get; set; } - - public IComparable Value2 { get; set; } - - public IComparable Value3 { get; set; } - } - } -} diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj index 8dbc78c305..b9176c0e6b 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj @@ -14,8 +14,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs index 9aa3d59239..76e82be109 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs @@ -54,7 +54,7 @@ public void UnitsNetBaseJsonConverter_ConvertValueUnit_works_as_expected() Assert.NotNull(result); Assert.IsType(result); - Assert.True(Power.FromWatts(10.2365m).Equals((Power)result, 1E-5, ComparisonType.Absolute)); + Assert.True(Power.FromWatts(10.2365m).Equals((Power)result, 1E-5m, ComparisonType.Absolute)); } diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs index f8053607da..bbe5522852 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs @@ -117,7 +117,7 @@ public void UnitsNetIComparableJsonConverter_ReadJson_works_as_expected() Assert.NotNull(result); Assert.IsType(result); - Assert.Equal(120D, ((Power)result).Watts); + Assert.Equal(120M, ((Power)result).Watts); } } } diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs index ea87af940d..8ed7de7c29 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs @@ -135,7 +135,7 @@ public void UnitsNetIQuantityJsonConverter_ReadJson_works_as_expected() Assert.NotNull(result); Assert.IsType(result); - Assert.Equal(10.3654D, ((Power)result).Watts); + Assert.Equal(10.3654M, ((Power)result).Watts); } } } diff --git a/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs b/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs index b7a150b944..2b89bee8df 100644 --- a/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs +++ b/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs @@ -85,7 +85,7 @@ public override void WriteJson(JsonWriter writer, IQuantity? quantity, JsonSeria } else { - writer.WriteValue(quantity.Value); + writer.WriteValue((double)quantity.Value); } // write the 'Unit' abbreviation diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs index 2e804182c7..3373b27b26 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs @@ -186,13 +186,14 @@ protected ValueUnit ConvertIQuantity(IQuantity quantity) return new ExtendedValueUnit { Unit = $"{quantity.QuantityInfo.UnitType.Name}.{quantity.Unit}", - Value = quantity.Value, + // The type of "Value" is still double + Value = (double)quantity.Value, ValueString = d.Value.ToString(CultureInfo.InvariantCulture), ValueType = "decimal" }; } - return new ValueUnit {Value = quantity.Value, Unit = $"{quantity.QuantityInfo.UnitType.Name}.{quantity.Unit}"}; + return new ValueUnit {Value = (double)quantity.Value, Unit = $"{quantity.QuantityInfo.UnitType.Name}.{quantity.Unit}"}; } /// diff --git a/UnitsNet.Tests/AssertEx.cs b/UnitsNet.Tests/AssertEx.cs index d052adfeec..34f270251c 100644 --- a/UnitsNet.Tests/AssertEx.cs +++ b/UnitsNet.Tests/AssertEx.cs @@ -25,5 +25,35 @@ public static void EqualTolerance(double expected, double actual, double toleran Assert.True( areEqual, $"Values are not equal within absolute tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}" ); } } + + public static void EqualTolerance(decimal expected, decimal actual, decimal tolerance, ComparisonType comparisonType = ComparisonType.Relative) + { + if (comparisonType == ComparisonType.Relative) + { + bool areEqual = Comparison.EqualsRelative(expected, actual, tolerance); + + decimal difference = Math.Abs(expected - actual); + decimal relativeDifference = difference / expected; + + Assert.True(areEqual, $"Values are not equal within relative tolerance: {tolerance:P4}\nExpected: {expected}\nActual: {actual}\nDiff: {relativeDifference:P4}"); + } + else if (comparisonType == ComparisonType.Absolute) + { + bool areEqual = Comparison.EqualsAbsolute(expected, actual, tolerance); + Assert.True(areEqual, $"Values are not equal within absolute tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}"); + } + } + + public static void EqualTolerance(QuantityValue expected, QuantityValue actual, double tolerance, + ComparisonType comparisonType = ComparisonType.Relative) + { + EqualTolerance((double)expected, (double)actual, tolerance, comparisonType); + } + + public static void EqualTolerance(QuantityValue expected, QuantityValue actual, decimal tolerance, + ComparisonType comparisonType = ComparisonType.Relative) + { + EqualTolerance((decimal)expected, (decimal)actual, tolerance, comparisonType); + } } } diff --git a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs index 726457cbe1..92960b547a 100644 --- a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs @@ -51,7 +51,7 @@ public void ExpectVoltageConvertedToAmplitudeRatioCorrectly(double voltage, doub // Amplitude ratio increases linearly by 20 dBV with power-of-10 increases of voltage. ElectricPotential v = ElectricPotential.FromVolts(voltage); - double actual = AmplitudeRatio.FromElectricPotential(v).DecibelVolts; + double actual = (double)AmplitudeRatio.FromElectricPotential(v).DecibelVolts; Assert.Equal(expected, actual); } @@ -61,12 +61,12 @@ public void ExpectVoltageConvertedToAmplitudeRatioCorrectly(double voltage, doub [InlineData(0, 1)] [InlineData(20, 10)] [InlineData(40, 100)] - public void ExpectAmplitudeRatioConvertedToVoltageCorrectly(double amplitudeRatio, double expected) + public void ExpectAmplitudeRatioConvertedToVoltageCorrectly(QuantityValue amplitudeRatio, QuantityValue expected) { // Voltage increases by powers of 10 for every 20 dBV increase in amplitude ratio. AmplitudeRatio ar = AmplitudeRatio.FromDecibelVolts(amplitudeRatio); - double actual = ar.ToElectricPotential().Volts; + QuantityValue actual = ar.ToElectricPotential().Volts; Assert.Equal(expected, actual); } @@ -81,7 +81,7 @@ public void AmplitudeRatioToPowerRatio_50OhmImpedance(double dBmV, double expect { AmplitudeRatio ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); - double actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(50)).DecibelMilliwatts, 2); + double actual = Math.Round((double)ampRatio.ToPowerRatio(ElectricResistance.FromOhms(50)).DecibelMilliwatts, 2); Assert.Equal(expected, actual); } @@ -94,7 +94,7 @@ public void AmplitudeRatioToPowerRatio_75OhmImpedance(double dBmV, double expect { AmplitudeRatio ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); - double actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(75)).DecibelMilliwatts, 2); + double actual = Math.Round((double)ampRatio.ToPowerRatio(ElectricResistance.FromOhms(75)).DecibelMilliwatts, 2); Assert.Equal(expected, actual); } } diff --git a/UnitsNet.Tests/CustomCode/AreaTests.cs b/UnitsNet.Tests/CustomCode/AreaTests.cs index 5cea83c962..966fc50aca 100644 --- a/UnitsNet.Tests/CustomCode/AreaTests.cs +++ b/UnitsNet.Tests/CustomCode/AreaTests.cs @@ -68,7 +68,7 @@ public void AreaFromCicleDiameterCalculatedCorrectly(double diameterMeters, doub { Length diameter = Length.FromMeters(diameterMeters); - double actual = Area.FromCircleDiameter(diameter).SquareMeters; + double actual = (double)Area.FromCircleDiameter(diameter).SquareMeters; Assert.Equal(expected, actual); } @@ -82,7 +82,7 @@ public void AreaFromCicleRadiusCalculatedCorrectly(double radiusMeters, double e { Length radius = Length.FromMeters(radiusMeters); - double actual = Area.FromCircleRadius(radius).SquareMeters; + double actual = (double)Area.FromCircleRadius(radius).SquareMeters; Assert.Equal(expected, actual); } diff --git a/UnitsNet.Tests/CustomCode/BitRateTests.cs b/UnitsNet.Tests/CustomCode/BitRateTests.cs index 2afe11ae27..5e49dc8ad3 100644 --- a/UnitsNet.Tests/CustomCode/BitRateTests.cs +++ b/UnitsNet.Tests/CustomCode/BitRateTests.cs @@ -29,37 +29,37 @@ public class BitRateTests : BitRateTestsBase { protected override bool SupportsSIUnitSystem => false; - protected override double BitsPerSecondInOneBitPerSecond => 1d; - protected override double BytesPerSecondInOneBitPerSecond => 1.25E-1d; + protected override decimal BitsPerSecondInOneBitPerSecond => 1m; + protected override decimal BytesPerSecondInOneBitPerSecond => 1.25E-1m; - protected override double KilobitsPerSecondInOneBitPerSecond => 1E-3d; - protected override double KilobytesPerSecondInOneBitPerSecond => 1.25E-4d; - protected override double KibibitsPerSecondInOneBitPerSecond => 0.0009765625d; - protected override double KibibytesPerSecondInOneBitPerSecond => 0.0001220703125d; + protected override decimal KilobitsPerSecondInOneBitPerSecond => 1E-3m; + protected override decimal KilobytesPerSecondInOneBitPerSecond => 1.25E-4m; + protected override decimal KibibitsPerSecondInOneBitPerSecond => 0.0009765625m; + protected override decimal KibibytesPerSecondInOneBitPerSecond => 0.0001220703125m; - protected override double MegabitsPerSecondInOneBitPerSecond => 1E-6d; - protected override double MegabytesPerSecondInOneBitPerSecond => 1.25E-07d; - protected override double MebibitsPerSecondInOneBitPerSecond => 9.5367431640625E-07d; - protected override double MebibytesPerSecondInOneBitPerSecond => 1.19209289550781E-07d; + protected override decimal MegabitsPerSecondInOneBitPerSecond => 1E-6m; + protected override decimal MegabytesPerSecondInOneBitPerSecond => 1.25E-07m; + protected override decimal MebibitsPerSecondInOneBitPerSecond => 9.5367431640625E-07m; + protected override decimal MebibytesPerSecondInOneBitPerSecond => 1.19209289550781E-07m; - protected override double GigabitsPerSecondInOneBitPerSecond => 1E-9d; - protected override double GigabytesPerSecondInOneBitPerSecond => 1.25E-10d; - protected override double GibibitsPerSecondInOneBitPerSecond => 9.31322574615479E-10d; - protected override double GibibytesPerSecondInOneBitPerSecond => 1.16415321826935E-10d; + protected override decimal GigabitsPerSecondInOneBitPerSecond => 1E-9m; + protected override decimal GigabytesPerSecondInOneBitPerSecond => 1.25E-10m; + protected override decimal GibibitsPerSecondInOneBitPerSecond => 9.31322574615479E-10m; + protected override decimal GibibytesPerSecondInOneBitPerSecond => 1.16415321826935E-10m; - protected override double TerabitsPerSecondInOneBitPerSecond => 1E-12d; - protected override double TerabytesPerSecondInOneBitPerSecond => 1.25E-13d; - protected override double TebibitsPerSecondInOneBitPerSecond => 9.09494701772928E-13d; - protected override double TebibytesPerSecondInOneBitPerSecond => 1.13686837721616E-13d; + protected override decimal TerabitsPerSecondInOneBitPerSecond => 1E-12m; + protected override decimal TerabytesPerSecondInOneBitPerSecond => 1.25E-13m; + protected override decimal TebibitsPerSecondInOneBitPerSecond => 9.09494701772928E-13m; + protected override decimal TebibytesPerSecondInOneBitPerSecond => 1.13686837721616E-13m; - protected override double PetabitsPerSecondInOneBitPerSecond => 1E-15d; - protected override double PetabytesPerSecondInOneBitPerSecond => 1.25E-16d; - protected override double PebibitsPerSecondInOneBitPerSecond => 8.88178419700125E-16d; - protected override double PebibytesPerSecondInOneBitPerSecond => 1.11022302462516E-16d; + protected override decimal PetabitsPerSecondInOneBitPerSecond => 1E-15m; + protected override decimal PetabytesPerSecondInOneBitPerSecond => 1.25E-16m; + protected override decimal PebibitsPerSecondInOneBitPerSecond => 8.88178419700125E-16m; + protected override decimal PebibytesPerSecondInOneBitPerSecond => 1.11022302462516E-16m; - protected override double ExabitsPerSecondInOneBitPerSecond => 1E-18d; - protected override double ExabytesPerSecondInOneBitPerSecond => 1.25E-19d; - protected override double ExbibitsPerSecondInOneBitPerSecond => 8.67361738E-19d; - protected override double ExbibytesPerSecondInOneBitPerSecond => 1.0842021724855E-19d; + protected override decimal ExabitsPerSecondInOneBitPerSecond => 1E-18m; + protected override decimal ExabytesPerSecondInOneBitPerSecond => 1.25E-19m; + protected override decimal ExbibitsPerSecondInOneBitPerSecond => 8.67361738E-19m; + protected override decimal ExbibytesPerSecondInOneBitPerSecond => 1.0842021724855E-19m; } } diff --git a/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs b/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs index 3079c5d0d6..77ec95385c 100644 --- a/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs +++ b/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs @@ -33,8 +33,8 @@ public void DoubleDividedByBrakeSpecificFuelConsumptionEqualsSpecificEnergy() [Fact] public void BrakeSpecificFuelConsumptionTimesSpecificEnergyEqualsEnergy() { - double value = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); - Assert.Equal(200.0, value); + decimal value = (decimal)(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0)); + Assert.Equal(200.0m, value); } } } diff --git a/UnitsNet.Tests/CustomCode/InformationTests.cs b/UnitsNet.Tests/CustomCode/InformationTests.cs index dc0dbfd879..4e2b1fa474 100644 --- a/UnitsNet.Tests/CustomCode/InformationTests.cs +++ b/UnitsNet.Tests/CustomCode/InformationTests.cs @@ -9,57 +9,57 @@ namespace UnitsNet.Tests.CustomCode public class InformationTests : InformationTestsBase { protected override bool SupportsSIUnitSystem => false; - protected override double BitsInOneBit => 1d; + protected override decimal BitsInOneBit => 1m; - protected override double BytesInOneBit => 0.125d; + protected override decimal BytesInOneBit => 0.125m; - protected override double ExabitsInOneBit => 1e-18d; + protected override decimal ExabitsInOneBit => 1e-18m; - protected override double ExabytesInOneBit => 0.125d*1e-18d; + protected override decimal ExabytesInOneBit => 0.125m*1e-18m; - protected override double ExbibitsInOneBit => 1d/Math.Pow(1024, 6); + protected override decimal ExbibitsInOneBit => 1m/(decimal)Math.Pow(1024, 6); - protected override double ExbibytesInOneBit => 1/8d/Math.Pow(1024, 6); + protected override decimal ExbibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 6); - protected override double GibibitsInOneBit => 1d/Math.Pow(1024, 3); + protected override decimal GibibitsInOneBit => 1m/(decimal)Math.Pow(1024, 3); - protected override double GibibytesInOneBit => 1d/8/Math.Pow(1024, 3); + protected override decimal GibibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 3); - protected override double GigabitsInOneBit => 1e-9d; + protected override decimal GigabitsInOneBit => 1e-9m; - protected override double GigabytesInOneBit => 0.125d*1e-9d; + protected override decimal GigabytesInOneBit => 0.125m*1e-9m; - protected override double KibibitsInOneBit => 1d/1024d; + protected override decimal KibibitsInOneBit => 1m/1024m; - protected override double KibibytesInOneBit => 1d/8/1024d; + protected override decimal KibibytesInOneBit => 1m/8/1024m; - protected override double KilobitsInOneBit => 0.001d; + protected override decimal KilobitsInOneBit => 0.001m; - protected override double KilobytesInOneBit => 0.000125d; + protected override decimal KilobytesInOneBit => 0.000125m; - protected override double MebibitsInOneBit => 1d/Math.Pow(1024, 2); + protected override decimal MebibitsInOneBit => 1m/(decimal)Math.Pow(1024, 2); - protected override double MebibytesInOneBit => 1d/8/Math.Pow(1024, 2); + protected override decimal MebibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 2); - protected override double MegabitsInOneBit => 1e-6d; + protected override decimal MegabitsInOneBit => 1e-6m; - protected override double MegabytesInOneBit => 0.125d*1e-6d; + protected override decimal MegabytesInOneBit => 0.125m*1e-6m; - protected override double PebibitsInOneBit => 1d/Math.Pow(1024, 5); + protected override decimal PebibitsInOneBit => 1m/(decimal)Math.Pow(1024, 5); - protected override double PebibytesInOneBit => 1d/8/Math.Pow(1024, 5); + protected override decimal PebibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 5); - protected override double PetabitsInOneBit => 1e-15d; + protected override decimal PetabitsInOneBit => 1e-15m; - protected override double PetabytesInOneBit => 0.125d*1e-15d; + protected override decimal PetabytesInOneBit => 0.125m*1e-15m; - protected override double TebibitsInOneBit => 1d/Math.Pow(1024, 4); + protected override decimal TebibitsInOneBit => 1m/(decimal)Math.Pow(1024, 4); - protected override double TebibytesInOneBit => 1d/8/Math.Pow(1024, 4); + protected override decimal TebibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 4); - protected override double TerabitsInOneBit => 1e-12d; + protected override decimal TerabitsInOneBit => 1e-12m; - protected override double TerabytesInOneBit => 0.125d*1e-12d; + protected override decimal TerabytesInOneBit => 0.125m*1e-12m; [Fact] public void OneKBHas1000Bytes() diff --git a/UnitsNet.Tests/CustomCode/MassFlowTests.cs b/UnitsNet.Tests/CustomCode/MassFlowTests.cs index 9d7cb97f2d..711f82b28d 100644 --- a/UnitsNet.Tests/CustomCode/MassFlowTests.cs +++ b/UnitsNet.Tests/CustomCode/MassFlowTests.cs @@ -108,7 +108,7 @@ public void TimeSpanTimesMassFlowEqualsMass() public void MassFlowDividedByBrakeSpecificFuelConsumptionEqualsPower() { Power power = MassFlow.FromTonnesPerDay(20) / BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); - Assert.Equal(20.0 / 24.0 * 1e6 / 180.0, power.Kilowatts); + AssertEx.EqualTolerance(20.0m / 24.0m * 1e6m / 180.0m, power.Kilowatts, 1E-11m); } [Fact] diff --git a/UnitsNet.Tests/CustomCode/ParseTests.cs b/UnitsNet.Tests/CustomCode/ParseTests.cs index 06a1f7cdc9..ccf4c2ec56 100644 --- a/UnitsNet.Tests/CustomCode/ParseTests.cs +++ b/UnitsNet.Tests/CustomCode/ParseTests.cs @@ -25,10 +25,10 @@ public class ParseTests [InlineData("1e-3 km", 1)] [InlineData("5.5 m", 5.5)] [InlineData("500,005 m", 500005)] - public void ParseLengthToMetersUsEnglish(string s, double expected) + public void ParseLengthToMetersUsEnglish(string s, QuantityValue expected) { CultureInfo usEnglish = new CultureInfo("en-US"); - double actual = Length.Parse(s, usEnglish).Meters; + QuantityValue actual = Length.Parse(s, usEnglish).Meters; Assert.Equal(expected, actual); } @@ -50,7 +50,7 @@ public void ParseLength_InvalidString_USEnglish_ThrowsException(string s, Type e [InlineData("5.5 m", 5.5)] [InlineData("500 005 m", 500005)] // quantity doesn't match number format - public void ParseWithCultureUsingSpaceAsThousandSeparators(string s, double expected) + public void ParseWithCultureUsingSpaceAsThousandSeparators(string s, QuantityValue expected) { var numberFormat = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone(); numberFormat.NumberGroupSeparator = " "; @@ -58,7 +58,7 @@ public void ParseWithCultureUsingSpaceAsThousandSeparators(string s, double expe numberFormat.NumberDecimalSeparator = "."; numberFormat.CurrencyDecimalSeparator = "."; - double actual = Length.Parse(s, numberFormat).Meters; + QuantityValue actual = Length.Parse(s, numberFormat).Meters; Assert.Equal(expected, actual); } @@ -81,7 +81,7 @@ public void ParseWithCultureUsingSpaceAsThousandSeparators_ThrowsExceptionOnInva [InlineData("5,5 m", 5.5)] [InlineData("500.005.050,001 m", 500005050.001)] [InlineData("5.555 m", 5555)] // Dot is group separator not decimal - public void ParseWithCultureUsingDotAsThousandSeparators(string s, double expected) + public void ParseWithCultureUsingDotAsThousandSeparators(string s, QuantityValue expected) { var numberFormat = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone(); numberFormat.NumberGroupSeparator = "."; @@ -89,7 +89,7 @@ public void ParseWithCultureUsingDotAsThousandSeparators(string s, double expect numberFormat.NumberDecimalSeparator = ","; numberFormat.CurrencyDecimalSeparator = ","; - double actual = Length.Parse(s, numberFormat).Meters; + QuantityValue actual = Length.Parse(s, numberFormat).Meters; Assert.Equal(expected, actual); } diff --git a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs index e6820ea023..f34ed66db4 100644 --- a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs @@ -41,11 +41,12 @@ public void InvalidPower_ExpectArgumentOutOfRangeException(double power) public void ExpectPowerConvertedCorrectly(double power, double expected) { Power p = Power.FromWatts(power); - double actual = PowerRatio.FromPower(p).DecibelWatts; + double actual = (double)PowerRatio.FromPower(p).DecibelWatts; Assert.Equal(expected, actual); } [Theory] + // Note: Attribute arguments cannot be of type decimal. [InlineData(-20, 0.01)] [InlineData(-10, 0.1)] [InlineData(0, 1)] @@ -54,8 +55,8 @@ public void ExpectPowerConvertedCorrectly(double power, double expected) public void ExpectPowerRatioConvertedCorrectly(double powerRatio, double expected) { PowerRatio pr = PowerRatio.FromDecibelWatts(powerRatio); - double actual = pr.ToPower().Watts; - Assert.Equal(expected, actual); + decimal actual = (decimal)pr.ToPower().Watts; + Assert.Equal((decimal)expected, actual); } // http://www.maximintegrated.com/en/app-notes/index.mvp/id/808 @@ -69,7 +70,7 @@ public void PowerRatioToAmplitudeRatio_50OhmImpedance(double dBmW, double expect { PowerRatio powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); - double actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(50)).DecibelMillivolts, 2); + double actual = Math.Round((double)powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(50)).DecibelMillivolts, 2); Assert.Equal(expected, actual); } @@ -82,7 +83,7 @@ public void PowerRatioToAmplitudeRatio_75OhmImpedance(double dBmW, double expect { PowerRatio powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); - double actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(75)).DecibelMillivolts, 2); + double actual = Math.Round((double)powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(75)).DecibelMillivolts, 2); Assert.Equal(expected, actual); } } diff --git a/UnitsNet.Tests/CustomCode/PowerTests.cs b/UnitsNet.Tests/CustomCode/PowerTests.cs index b965e8fa83..8161a50849 100644 --- a/UnitsNet.Tests/CustomCode/PowerTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerTests.cs @@ -9,57 +9,57 @@ namespace UnitsNet.Tests.CustomCode public class PowerTests : PowerTestsBase { protected override bool SupportsSIUnitSystem => false; - protected override double FemtowattsInOneWatt => 1e15; + protected override decimal FemtowattsInOneWatt => 1e15m; - protected override double GigajoulesPerHourInOneWatt => 3600e-9; + protected override decimal GigajoulesPerHourInOneWatt => 3600e-9m; - protected override double PicowattsInOneWatt => 1e12; + protected override decimal PicowattsInOneWatt => 1e12m; - protected override double NanowattsInOneWatt => 1e9; + protected override decimal NanowattsInOneWatt => 1e9m; - protected override double MicrowattsInOneWatt => 1e6; + protected override decimal MicrowattsInOneWatt => 1e6m; - protected override double MillijoulesPerHourInOneWatt => 3600e3; + protected override decimal MillijoulesPerHourInOneWatt => 3600e3m; - protected override double MilliwattsInOneWatt => 1e3; + protected override decimal MilliwattsInOneWatt => 1e3m; - protected override double DeciwattsInOneWatt => 1e1; + protected override decimal DeciwattsInOneWatt => 1e1m; - protected override double WattsInOneWatt => 1; + protected override decimal WattsInOneWatt => 1; - protected override double DecawattsInOneWatt => 1e-1; + protected override decimal DecawattsInOneWatt => 1e-1m; - protected override double KilojoulesPerHourInOneWatt => 3600e-3; + protected override decimal KilojoulesPerHourInOneWatt => 3600e-3m; - protected override double KilowattsInOneWatt => 1e-3; + protected override decimal KilowattsInOneWatt => 1e-3m; - protected override double MegajoulesPerHourInOneWatt => 3600e-6; + protected override decimal MegajoulesPerHourInOneWatt => 3600e-6m; - protected override double MegawattsInOneWatt => 1e-6; + protected override decimal MegawattsInOneWatt => 1e-6m; - protected override double GigawattsInOneWatt => 1e-9; + protected override decimal GigawattsInOneWatt => 1e-9m; - protected override double TerawattsInOneWatt => 1e-12; + protected override decimal TerawattsInOneWatt => 1e-12m; - protected override double PetawattsInOneWatt => 1e-15; + protected override decimal PetawattsInOneWatt => 1e-15m; - protected override double JoulesPerHourInOneWatt => 3600; + protected override decimal JoulesPerHourInOneWatt => 3600; - protected override double KilobritishThermalUnitsPerHourInOneWatt => 3.412141633e-3; + protected override decimal KilobritishThermalUnitsPerHourInOneWatt => 3.412141633e-3m; - protected override double MegabritishThermalUnitsPerHourInOneWatt => 3.412141633e-6; + protected override decimal BoilerHorsepowerInOneWatt => 1.0191082802547770700636942675159e-4m; - protected override double BoilerHorsepowerInOneWatt => 1.0191082802547770700636942675159e-4; + protected override decimal MegabritishThermalUnitsPerHourInOneWatt => 3.412141633e-6m; - protected override double BritishThermalUnitsPerHourInOneWatt => 3.412141633; + protected override decimal BritishThermalUnitsPerHourInOneWatt => 3.412141633m; - protected override double ElectricalHorsepowerInOneWatt => 0.00134048257372654155495978552279; + protected override decimal ElectricalHorsepowerInOneWatt => 0.00134048257372654155495978552279m; - protected override double HydraulicHorsepowerInOneWatt => 0.00134102207184949258114167291719; + protected override decimal HydraulicHorsepowerInOneWatt => 0.00134102207184949258114167291719m; - protected override double MechanicalHorsepowerInOneWatt => 0.00134103984229371454625916935992; + protected override decimal MechanicalHorsepowerInOneWatt => 0.00134103984229371454625916935992m; - protected override double MetricHorsepowerInOneWatt => 0.00135962161730390432342679032425; + protected override decimal MetricHorsepowerInOneWatt => 0.00135962161730390432342679032425m; [Fact] public void DurationTimesPowerEqualsEnergy() diff --git a/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs b/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs index 15fb16bb45..4da3858304 100644 --- a/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs @@ -70,13 +70,13 @@ public void DoubleDividedBySpecificEnergyEqualsBrakeSpecificFuelConsumption() public void SpecificEnergyTimesMassFlowEqualsPower() { Power power = SpecificEnergy.FromJoulesPerKilogram(10.0) * MassFlow.FromKilogramsPerSecond(20.0); - Assert.Equal(200d, power.Watts); + Assert.Equal(200m, power.Watts); } [Fact] public void SpecificEnergyTimesBrakeSpecificFuelConsumptionEqualsEnergy() { - double value = SpecificEnergy.FromJoulesPerKilogram(10.0) * BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0); + double value = (double)(SpecificEnergy.FromJoulesPerKilogram(10.0) * BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0)); Assert.Equal(200d, value); } } diff --git a/UnitsNet.Tests/CustomQuantities/HowMuch.cs b/UnitsNet.Tests/CustomQuantities/HowMuch.cs index cafdfc75ae..c64a1af059 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuch.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuch.cs @@ -17,7 +17,7 @@ public HowMuch(double value, HowMuchUnit unit) Enum IQuantity.Unit => Unit; public HowMuchUnit Unit { get; } - public double Value { get; } + public QuantityValue Value { get; } #region IQuantity @@ -38,13 +38,13 @@ public HowMuch(double value, HowMuchUnit unit) Zero, BaseDimensions.Dimensionless); - public double As(Enum unit) => Convert.ToDouble(unit); + public QuantityValue As(Enum unit) => Convert.ToDouble(unit); - public double As(UnitSystem unitSystem) => throw new NotImplementedException(); + public QuantityValue As(UnitSystem unitSystem) => throw new NotImplementedException(); public IQuantity ToUnit(Enum unit) { - if (unit is HowMuchUnit howMuchUnit) return new HowMuch(As(unit), howMuchUnit); + if (unit is HowMuchUnit howMuchUnit) return new HowMuch((double)As(unit), howMuchUnit); throw new ArgumentException("Must be of type HowMuchUnit.", nameof(unit)); } diff --git a/UnitsNet.Tests/DecimalOverloadTests.cs b/UnitsNet.Tests/DecimalOverloadTests.cs index 841c9b162b..6b9842d0aa 100644 --- a/UnitsNet.Tests/DecimalOverloadTests.cs +++ b/UnitsNet.Tests/DecimalOverloadTests.cs @@ -18,7 +18,7 @@ public static void CreatingQuantityWithDoubleBackingFieldFromDecimalReturnsCorre public static void CreatingQuantityWithDecimalBackingFieldFromDecimalReturnsCorrectValue() { Power power = Power.FromWatts(1m); - Assert.Equal(1.0, power.Watts); + Assert.Equal(1.0m, power.Watts); } } } diff --git a/UnitsNet.Tests/DummyIQuantity.cs b/UnitsNet.Tests/DummyIQuantity.cs index cda0f506b1..95bebe55e5 100644 --- a/UnitsNet.Tests/DummyIQuantity.cs +++ b/UnitsNet.Tests/DummyIQuantity.cs @@ -11,11 +11,11 @@ internal class DummyIQuantity : IQuantity public Enum Unit => throw new NotImplementedException(); - public double Value => throw new NotImplementedException(); + public QuantityValue Value => throw new NotImplementedException(); - public double As(Enum unit ) => throw new NotImplementedException(); + public QuantityValue As(Enum unit ) => throw new NotImplementedException(); - public double As(UnitSystem unitSystem ) => throw new NotImplementedException(); + public QuantityValue As(UnitSystem unitSystem ) => throw new NotImplementedException(); public string ToString(IFormatProvider? provider) => throw new NotImplementedException(); diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs index f70180cba6..a525d6afba 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs @@ -54,20 +54,20 @@ public abstract partial class AccelerationTestsBase : QuantityTestsBase protected abstract double StandardGravityInOneMeterPerSecondSquared { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimetersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double DecimetersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double FeetPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double InchesPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double KilometersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double KnotsPerHourTolerance { get { return 1e-5; } } - protected virtual double KnotsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double KnotsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MetersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double MicrometersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double MillimetersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double MillistandardGravityTolerance { get { return 1e-5; } } - protected virtual double NanometersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double StandardGravityTolerance { get { return 1e-5; } } + protected virtual double CentimetersPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double DecimetersPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double FeetPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double InchesPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double KilometersPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double KnotsPerHourTolerance { get { return 1E-5; } } + protected virtual double KnotsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double KnotsPerSecondTolerance { get { return 1E-5; } } + protected virtual double MetersPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double MicrometersPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double MillimetersPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double MillistandardGravityTolerance { get { return 1E-5; } } + protected virtual double NanometersPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double StandardGravityTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AccelerationUnit unit) @@ -288,7 +288,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -993,14 +993,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(AccelerationUnit unit) { - var inBaseUnits = Acceleration.From(1.0, Acceleration.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Acceleration.From(1.0, Acceleration.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Acceleration.From(1.0, Acceleration.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(AccelerationUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(AccelerationUnit unit) @@ -1014,8 +1021,8 @@ public void ToUnit_WithSameUnits_AreEqual(AccelerationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AccelerationUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Acceleration.Units.Where(u => u != Acceleration.BaseUnit).DefaultIfEmpty(Acceleration.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Acceleration.Units.First(u => u != Acceleration.BaseUnit); var quantity = Acceleration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1249,8 +1256,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Acceleration.FromMetersPerSecondSquared(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1284,36 +1292,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Acceleration.FromMetersPerSecondSquared(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Acceleration.FromMetersPerSecondSquared(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Acceleration.FromMetersPerSecondSquared(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Acceleration.FromMetersPerSecondSquared(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Acceleration.FromMetersPerSecondSquared(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1326,22 +1339,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Acceleration.FromMetersPerSecondSquared(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Acceleration.FromMetersPerSecondSquared(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Acceleration.FromMetersPerSecondSquared(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1383,7 +1399,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(new {Acceleration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Acceleration.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs index 52cc5fa708..5d469e8a46 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs @@ -55,21 +55,21 @@ public abstract partial class AmountOfSubstanceTestsBase : QuantityTestsBase protected abstract double PoundMolesInOneMole { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimolesTolerance { get { return 1e-5; } } - protected virtual double CentipoundMolesTolerance { get { return 1e-5; } } - protected virtual double DecimolesTolerance { get { return 1e-5; } } - protected virtual double DecipoundMolesTolerance { get { return 1e-5; } } - protected virtual double KilomolesTolerance { get { return 1e-5; } } - protected virtual double KilopoundMolesTolerance { get { return 1e-5; } } - protected virtual double MegamolesTolerance { get { return 1e-5; } } - protected virtual double MicromolesTolerance { get { return 1e-5; } } - protected virtual double MicropoundMolesTolerance { get { return 1e-5; } } - protected virtual double MillimolesTolerance { get { return 1e-5; } } - protected virtual double MillipoundMolesTolerance { get { return 1e-5; } } - protected virtual double MolesTolerance { get { return 1e-5; } } - protected virtual double NanomolesTolerance { get { return 1e-5; } } - protected virtual double NanopoundMolesTolerance { get { return 1e-5; } } - protected virtual double PoundMolesTolerance { get { return 1e-5; } } + protected virtual double CentimolesTolerance { get { return 1E-5; } } + protected virtual double CentipoundMolesTolerance { get { return 1E-5; } } + protected virtual double DecimolesTolerance { get { return 1E-5; } } + protected virtual double DecipoundMolesTolerance { get { return 1E-5; } } + protected virtual double KilomolesTolerance { get { return 1E-5; } } + protected virtual double KilopoundMolesTolerance { get { return 1E-5; } } + protected virtual double MegamolesTolerance { get { return 1E-5; } } + protected virtual double MicromolesTolerance { get { return 1E-5; } } + protected virtual double MicropoundMolesTolerance { get { return 1E-5; } } + protected virtual double MillimolesTolerance { get { return 1E-5; } } + protected virtual double MillipoundMolesTolerance { get { return 1E-5; } } + protected virtual double MolesTolerance { get { return 1E-5; } } + protected virtual double NanomolesTolerance { get { return 1E-5; } } + protected virtual double NanopoundMolesTolerance { get { return 1E-5; } } + protected virtual double PoundMolesTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AmountOfSubstanceUnit unit) @@ -298,7 +298,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -669,14 +669,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(AmountOfSubstanceUnit unit) { - var inBaseUnits = AmountOfSubstance.From(1.0, AmountOfSubstance.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = AmountOfSubstance.From(1.0, AmountOfSubstance.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = AmountOfSubstance.From(1.0, AmountOfSubstance.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(AmountOfSubstanceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(AmountOfSubstanceUnit unit) @@ -690,8 +697,8 @@ public void ToUnit_WithSameUnits_AreEqual(AmountOfSubstanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AmountOfSubstanceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = AmountOfSubstance.Units.Where(u => u != AmountOfSubstance.BaseUnit).DefaultIfEmpty(AmountOfSubstance.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = AmountOfSubstance.Units.First(u => u != AmountOfSubstance.BaseUnit); var quantity = AmountOfSubstance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -928,8 +935,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = AmountOfSubstance.FromMoles(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -963,36 +971,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = AmountOfSubstance.FromMoles(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = AmountOfSubstance.FromMoles(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = AmountOfSubstance.FromMoles(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = AmountOfSubstance.FromMoles(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = AmountOfSubstance.FromMoles(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1005,22 +1018,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = AmountOfSubstance.FromMoles(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = AmountOfSubstance.FromMoles(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = AmountOfSubstance.FromMoles(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1062,7 +1078,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(new {AmountOfSubstance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(AmountOfSubstance.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs index 53181b282b..20d580e082 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class AmplitudeRatioTestsBase : QuantityTestsBase protected abstract double DecibelVoltsInOneDecibelVolt { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecibelMicrovoltsTolerance { get { return 1e-5; } } - protected virtual double DecibelMillivoltsTolerance { get { return 1e-5; } } - protected virtual double DecibelsUnloadedTolerance { get { return 1e-5; } } - protected virtual double DecibelVoltsTolerance { get { return 1e-5; } } + protected virtual double DecibelMicrovoltsTolerance { get { return 1E-5; } } + protected virtual double DecibelMillivoltsTolerance { get { return 1E-5; } } + protected virtual double DecibelsUnloadedTolerance { get { return 1E-5; } } + protected virtual double DecibelVoltsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AmplitudeRatioUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -317,14 +317,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(AmplitudeRatioUnit unit) { - var inBaseUnits = AmplitudeRatio.From(1.0, AmplitudeRatio.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = AmplitudeRatio.From(1.0, AmplitudeRatio.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = AmplitudeRatio.From(1.0, AmplitudeRatio.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(AmplitudeRatioUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(AmplitudeRatioUnit unit) @@ -338,8 +345,8 @@ public void ToUnit_WithSameUnits_AreEqual(AmplitudeRatioUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AmplitudeRatioUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = AmplitudeRatio.Units.Where(u => u != AmplitudeRatio.BaseUnit).DefaultIfEmpty(AmplitudeRatio.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = AmplitudeRatio.Units.First(u => u != AmplitudeRatio.BaseUnit); var quantity = AmplitudeRatio.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -547,8 +554,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = AmplitudeRatio.FromDecibelVolts(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -582,36 +590,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = AmplitudeRatio.FromDecibelVolts(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = AmplitudeRatio.FromDecibelVolts(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = AmplitudeRatio.FromDecibelVolts(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = AmplitudeRatio.FromDecibelVolts(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = AmplitudeRatio.FromDecibelVolts(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -624,22 +637,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = AmplitudeRatio.FromDecibelVolts(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = AmplitudeRatio.FromDecibelVolts(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = AmplitudeRatio.FromDecibelVolts(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -681,7 +697,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(new {AmplitudeRatio.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(AmplitudeRatio.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs index b6f83dd254..8d1a7c53f7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs @@ -56,22 +56,22 @@ public abstract partial class AngleTestsBase : QuantityTestsBase protected abstract double TiltInOneDegree { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double ArcminutesTolerance { get { return 1e-5; } } - protected virtual double ArcsecondsTolerance { get { return 1e-5; } } - protected virtual double CentiradiansTolerance { get { return 1e-5; } } - protected virtual double DeciradiansTolerance { get { return 1e-5; } } - protected virtual double DegreesTolerance { get { return 1e-5; } } - protected virtual double GradiansTolerance { get { return 1e-5; } } - protected virtual double MicrodegreesTolerance { get { return 1e-5; } } - protected virtual double MicroradiansTolerance { get { return 1e-5; } } - protected virtual double MillidegreesTolerance { get { return 1e-5; } } - protected virtual double MilliradiansTolerance { get { return 1e-5; } } - protected virtual double NanodegreesTolerance { get { return 1e-5; } } - protected virtual double NanoradiansTolerance { get { return 1e-5; } } - protected virtual double NatoMilsTolerance { get { return 1e-5; } } - protected virtual double RadiansTolerance { get { return 1e-5; } } - protected virtual double RevolutionsTolerance { get { return 1e-5; } } - protected virtual double TiltTolerance { get { return 1e-5; } } + protected virtual double ArcminutesTolerance { get { return 1E-5; } } + protected virtual double ArcsecondsTolerance { get { return 1E-5; } } + protected virtual double CentiradiansTolerance { get { return 1E-5; } } + protected virtual double DeciradiansTolerance { get { return 1E-5; } } + protected virtual double DegreesTolerance { get { return 1E-5; } } + protected virtual double GradiansTolerance { get { return 1E-5; } } + protected virtual double MicrodegreesTolerance { get { return 1E-5; } } + protected virtual double MicroradiansTolerance { get { return 1E-5; } } + protected virtual double MillidegreesTolerance { get { return 1E-5; } } + protected virtual double MilliradiansTolerance { get { return 1E-5; } } + protected virtual double NanodegreesTolerance { get { return 1E-5; } } + protected virtual double NanoradiansTolerance { get { return 1E-5; } } + protected virtual double NatoMilsTolerance { get { return 1E-5; } } + protected virtual double RadiansTolerance { get { return 1E-5; } } + protected virtual double RevolutionsTolerance { get { return 1E-5; } } + protected virtual double TiltTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AngleUnit unit) @@ -308,7 +308,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1253,14 +1253,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(AngleUnit unit) { - var inBaseUnits = Angle.From(1.0, Angle.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Angle.From(1.0, Angle.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Angle.From(1.0, Angle.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(AngleUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(AngleUnit unit) @@ -1274,8 +1281,8 @@ public void ToUnit_WithSameUnits_AreEqual(AngleUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AngleUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Angle.Units.Where(u => u != Angle.BaseUnit).DefaultIfEmpty(Angle.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Angle.Units.First(u => u != Angle.BaseUnit); var quantity = Angle.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1515,8 +1522,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Angle.FromDegrees(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1550,36 +1558,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Angle.FromDegrees(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Angle.FromDegrees(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Angle.FromDegrees(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Angle.FromDegrees(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Angle.FromDegrees(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1592,22 +1605,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Angle.FromDegrees(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Angle.FromDegrees(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Angle.FromDegrees(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1649,7 +1665,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Angle.FromDegrees(1.0); - Assert.Equal(new {Angle.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Angle.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs index e84c7b0aad..14687f0e3a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class ApparentEnergyTestsBase : QuantityTestsBase protected abstract double VoltampereHoursInOneVoltampereHour { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltampereHoursTolerance { get { return 1e-5; } } - protected virtual double MegavoltampereHoursTolerance { get { return 1e-5; } } - protected virtual double VoltampereHoursTolerance { get { return 1e-5; } } + protected virtual double KilovoltampereHoursTolerance { get { return 1E-5; } } + protected virtual double MegavoltampereHoursTolerance { get { return 1E-5; } } + protected virtual double VoltampereHoursTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ApparentEnergyUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ApparentEnergyUnit unit) { - var inBaseUnits = ApparentEnergy.From(1.0, ApparentEnergy.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ApparentEnergy.From(1.0, ApparentEnergy.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ApparentEnergy.From(1.0, ApparentEnergy.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ApparentEnergyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ApparentEnergyUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(ApparentEnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ApparentEnergyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ApparentEnergy.Units.Where(u => u != ApparentEnergy.BaseUnit).DefaultIfEmpty(ApparentEnergy.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ApparentEnergy.Units.First(u => u != ApparentEnergy.BaseUnit); var quantity = ApparentEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ApparentEnergy.FromVoltampereHours(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ApparentEnergy.FromVoltampereHours(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ApparentEnergy.FromVoltampereHours(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ApparentEnergy.FromVoltampereHours(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ApparentEnergy.FromVoltampereHours(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ApparentEnergy.FromVoltampereHours(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ApparentEnergy.FromVoltampereHours(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ApparentEnergy.FromVoltampereHours(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ApparentEnergy.FromVoltampereHours(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(new {ApparentEnergy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ApparentEnergy.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs index b650b9bcd9..38ce76774c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class ApparentPowerTestsBase : QuantityTestsBase protected abstract double VoltamperesInOneVoltampere { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GigavoltamperesTolerance { get { return 1e-5; } } - protected virtual double KilovoltamperesTolerance { get { return 1e-5; } } - protected virtual double MegavoltamperesTolerance { get { return 1e-5; } } - protected virtual double VoltamperesTolerance { get { return 1e-5; } } + protected virtual double GigavoltamperesTolerance { get { return 1E-5; } } + protected virtual double KilovoltamperesTolerance { get { return 1E-5; } } + protected virtual double MegavoltamperesTolerance { get { return 1E-5; } } + protected virtual double VoltamperesTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ApparentPowerUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -317,14 +317,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ApparentPowerUnit unit) { - var inBaseUnits = ApparentPower.From(1.0, ApparentPower.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ApparentPower.From(1.0, ApparentPower.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ApparentPower.From(1.0, ApparentPower.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ApparentPowerUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ApparentPowerUnit unit) @@ -338,8 +345,8 @@ public void ToUnit_WithSameUnits_AreEqual(ApparentPowerUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ApparentPowerUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ApparentPower.Units.Where(u => u != ApparentPower.BaseUnit).DefaultIfEmpty(ApparentPower.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ApparentPower.Units.First(u => u != ApparentPower.BaseUnit); var quantity = ApparentPower.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -543,8 +550,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ApparentPower.FromVoltamperes(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -578,36 +586,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ApparentPower.FromVoltamperes(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ApparentPower.FromVoltamperes(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ApparentPower.FromVoltamperes(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ApparentPower.FromVoltamperes(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ApparentPower.FromVoltamperes(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -620,22 +633,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ApparentPower.FromVoltamperes(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ApparentPower.FromVoltamperes(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ApparentPower.FromVoltamperes(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -677,7 +693,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal(new {ApparentPower.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ApparentPower.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs index a9585c99c0..6dcc5c0bc3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class AreaDensityTestsBase : QuantityTestsBase protected abstract double KilogramsPerSquareMeterInOneKilogramPerSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilogramsPerSquareMeterTolerance { get { return 1e-5; } } + protected virtual double KilogramsPerSquareMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AreaDensityUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(AreaDensityUnit unit) { - var inBaseUnits = AreaDensity.From(1.0, AreaDensity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = AreaDensity.From(1.0, AreaDensity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = AreaDensity.From(1.0, AreaDensity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(AreaDensityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(AreaDensityUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(AreaDensityUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaDensityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = AreaDensity.Units.Where(u => u != AreaDensity.BaseUnit).DefaultIfEmpty(AreaDensity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = AreaDensity.Units.First(u => u != AreaDensity.BaseUnit); var quantity = AreaDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = AreaDensity.FromKilogramsPerSquareMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = AreaDensity.FromKilogramsPerSquareMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = AreaDensity.FromKilogramsPerSquareMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = AreaDensity.FromKilogramsPerSquareMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = AreaDensity.FromKilogramsPerSquareMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = AreaDensity.FromKilogramsPerSquareMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = AreaDensity.FromKilogramsPerSquareMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = AreaDensity.FromKilogramsPerSquareMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = AreaDensity.FromKilogramsPerSquareMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(new {AreaDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(AreaDensity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs index 2321a0aadf..e511ec6831 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs @@ -46,12 +46,12 @@ public abstract partial class AreaMomentOfInertiaTestsBase : QuantityTestsBase protected abstract double MillimetersToTheFourthInOneMeterToTheFourth { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimetersToTheFourthTolerance { get { return 1e-5; } } - protected virtual double DecimetersToTheFourthTolerance { get { return 1e-5; } } - protected virtual double FeetToTheFourthTolerance { get { return 1e-5; } } - protected virtual double InchesToTheFourthTolerance { get { return 1e-5; } } - protected virtual double MetersToTheFourthTolerance { get { return 1e-5; } } - protected virtual double MillimetersToTheFourthTolerance { get { return 1e-5; } } + protected virtual double CentimetersToTheFourthTolerance { get { return 1E-5; } } + protected virtual double DecimetersToTheFourthTolerance { get { return 1E-5; } } + protected virtual double FeetToTheFourthTolerance { get { return 1E-5; } } + protected virtual double InchesToTheFourthTolerance { get { return 1E-5; } } + protected virtual double MetersToTheFourthTolerance { get { return 1E-5; } } + protected virtual double MillimetersToTheFourthTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AreaMomentOfInertiaUnit unit) @@ -208,7 +208,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -529,14 +529,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(AreaMomentOfInertiaUnit unit) { - var inBaseUnits = AreaMomentOfInertia.From(1.0, AreaMomentOfInertia.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = AreaMomentOfInertia.From(1.0, AreaMomentOfInertia.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = AreaMomentOfInertia.From(1.0, AreaMomentOfInertia.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(AreaMomentOfInertiaUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(AreaMomentOfInertiaUnit unit) @@ -550,8 +557,8 @@ public void ToUnit_WithSameUnits_AreEqual(AreaMomentOfInertiaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaMomentOfInertiaUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = AreaMomentOfInertia.Units.Where(u => u != AreaMomentOfInertia.BaseUnit).DefaultIfEmpty(AreaMomentOfInertia.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = AreaMomentOfInertia.Units.First(u => u != AreaMomentOfInertia.BaseUnit); var quantity = AreaMomentOfInertia.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -761,8 +768,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -796,36 +804,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -838,22 +851,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -895,7 +911,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(new {AreaMomentOfInertia.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(AreaMomentOfInertia.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs index 39bffa73de..5d06c6612e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs @@ -54,20 +54,20 @@ public abstract partial class AreaTestsBase : QuantityTestsBase protected abstract double UsSurveySquareFeetInOneSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AcresTolerance { get { return 1e-5; } } - protected virtual double HectaresTolerance { get { return 1e-5; } } - protected virtual double SquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double SquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double SquareFeetTolerance { get { return 1e-5; } } - protected virtual double SquareInchesTolerance { get { return 1e-5; } } - protected virtual double SquareKilometersTolerance { get { return 1e-5; } } - protected virtual double SquareMetersTolerance { get { return 1e-5; } } - protected virtual double SquareMicrometersTolerance { get { return 1e-5; } } - protected virtual double SquareMilesTolerance { get { return 1e-5; } } - protected virtual double SquareMillimetersTolerance { get { return 1e-5; } } - protected virtual double SquareNauticalMilesTolerance { get { return 1e-5; } } - protected virtual double SquareYardsTolerance { get { return 1e-5; } } - protected virtual double UsSurveySquareFeetTolerance { get { return 1e-5; } } + protected virtual double AcresTolerance { get { return 1E-5; } } + protected virtual double HectaresTolerance { get { return 1E-5; } } + protected virtual double SquareCentimetersTolerance { get { return 1E-5; } } + protected virtual double SquareDecimetersTolerance { get { return 1E-5; } } + protected virtual double SquareFeetTolerance { get { return 1E-5; } } + protected virtual double SquareInchesTolerance { get { return 1E-5; } } + protected virtual double SquareKilometersTolerance { get { return 1E-5; } } + protected virtual double SquareMetersTolerance { get { return 1E-5; } } + protected virtual double SquareMicrometersTolerance { get { return 1E-5; } } + protected virtual double SquareMilesTolerance { get { return 1E-5; } } + protected virtual double SquareMillimetersTolerance { get { return 1E-5; } } + protected virtual double SquareNauticalMilesTolerance { get { return 1E-5; } } + protected virtual double SquareYardsTolerance { get { return 1E-5; } } + protected virtual double UsSurveySquareFeetTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(AreaUnit unit) @@ -288,7 +288,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1283,14 +1283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(AreaUnit unit) { - var inBaseUnits = Area.From(1.0, Area.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Area.From(1.0, Area.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Area.From(1.0, Area.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(AreaUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(AreaUnit unit) @@ -1304,8 +1311,8 @@ public void ToUnit_WithSameUnits_AreEqual(AreaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Area.Units.Where(u => u != Area.BaseUnit).DefaultIfEmpty(Area.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Area.Units.First(u => u != Area.BaseUnit); var quantity = Area.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1539,8 +1546,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Area.FromSquareMeters(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1574,36 +1582,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Area.FromSquareMeters(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Area.FromSquareMeters(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Area.FromSquareMeters(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Area.FromSquareMeters(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Area.FromSquareMeters(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1616,22 +1629,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Area.FromSquareMeters(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Area.FromSquareMeters(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Area.FromSquareMeters(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1673,7 +1689,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(new {Area.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Area.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs index a26e942ea8..756eab3893 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs @@ -38,63 +38,63 @@ namespace UnitsNet.Tests // ReSharper disable once PartialTypeWithSinglePart public abstract partial class BitRateTestsBase : QuantityTestsBase { - protected abstract double BitsPerSecondInOneBitPerSecond { get; } - protected abstract double BytesPerSecondInOneBitPerSecond { get; } - protected abstract double ExabitsPerSecondInOneBitPerSecond { get; } - protected abstract double ExabytesPerSecondInOneBitPerSecond { get; } - protected abstract double ExbibitsPerSecondInOneBitPerSecond { get; } - protected abstract double ExbibytesPerSecondInOneBitPerSecond { get; } - protected abstract double GibibitsPerSecondInOneBitPerSecond { get; } - protected abstract double GibibytesPerSecondInOneBitPerSecond { get; } - protected abstract double GigabitsPerSecondInOneBitPerSecond { get; } - protected abstract double GigabytesPerSecondInOneBitPerSecond { get; } - protected abstract double KibibitsPerSecondInOneBitPerSecond { get; } - protected abstract double KibibytesPerSecondInOneBitPerSecond { get; } - protected abstract double KilobitsPerSecondInOneBitPerSecond { get; } - protected abstract double KilobytesPerSecondInOneBitPerSecond { get; } - protected abstract double MebibitsPerSecondInOneBitPerSecond { get; } - protected abstract double MebibytesPerSecondInOneBitPerSecond { get; } - protected abstract double MegabitsPerSecondInOneBitPerSecond { get; } - protected abstract double MegabytesPerSecondInOneBitPerSecond { get; } - protected abstract double PebibitsPerSecondInOneBitPerSecond { get; } - protected abstract double PebibytesPerSecondInOneBitPerSecond { get; } - protected abstract double PetabitsPerSecondInOneBitPerSecond { get; } - protected abstract double PetabytesPerSecondInOneBitPerSecond { get; } - protected abstract double TebibitsPerSecondInOneBitPerSecond { get; } - protected abstract double TebibytesPerSecondInOneBitPerSecond { get; } - protected abstract double TerabitsPerSecondInOneBitPerSecond { get; } - protected abstract double TerabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal BitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal BytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal ExabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal ExabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal ExbibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal ExbibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal GibibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal GibibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal GigabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal GigabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal KibibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal KibibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal KilobitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal KilobytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal MebibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal MebibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal MegabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal MegabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal PebibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal PebibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal PetabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal PetabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal TebibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal TebibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal TerabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal TerabytesPerSecondInOneBitPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double BytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double ExabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double ExabytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double ExbibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double ExbibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double GibibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double GibibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double GigabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double GigabytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double KibibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double KibibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilobitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilobytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MebibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MebibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MegabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MegabytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double PebibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double PebibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double PetabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double PetabytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double TebibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double TebibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double TerabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double TerabytesPerSecondTolerance { get { return 1e-5; } } + protected virtual decimal BitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal BytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal ExabitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal ExabytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal ExbibitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal ExbibytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal GibibitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal GibibytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal GigabitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal GigabytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal KibibitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal KibibytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal KilobitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal KilobytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal MebibitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal MebibytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal MegabitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal MegabytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal PebibitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal PebibytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal PetabitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal PetabytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal TebibitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal TebibytesPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal TerabitsPerSecondTolerance { get { return 1E-9m; } } + protected virtual decimal TerabytesPerSecondTolerance { get { return 1E-9m; } } // ReSharper restore VirtualMemberNeverOverriden.Global - protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(BitRateUnit unit) + protected (decimal UnitsInBaseUnit, decimal Tolerence) GetConversionFactor(BitRateUnit unit) { return unit switch { @@ -383,7 +383,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1352,14 +1352,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(BitRateUnit unit) { - var inBaseUnits = BitRate.From(1.0, BitRate.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = BitRate.From(1.0, BitRate.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = BitRate.From(1.0, BitRate.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(BitRateUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(BitRateUnit unit) @@ -1373,8 +1380,8 @@ public void ToUnit_WithSameUnits_AreEqual(BitRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(BitRateUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = BitRate.Units.Where(u => u != BitRate.BaseUnit).DefaultIfEmpty(BitRate.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = BitRate.Units.First(u => u != BitRate.BaseUnit); var quantity = BitRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1644,8 +1651,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = BitRate.FromBitsPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1679,36 +1687,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = BitRate.FromBitsPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = BitRate.FromBitsPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = BitRate.FromBitsPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = BitRate.FromBitsPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = BitRate.FromBitsPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1721,22 +1734,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = BitRate.FromBitsPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = BitRate.FromBitsPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = BitRate.FromBitsPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1778,7 +1794,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(new {BitRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(BitRate.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs index 6e1bc6b653..3a3de29b37 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class BrakeSpecificFuelConsumptionTestsBase : QuantityTe protected abstract double PoundsPerMechanicalHorsepowerHourInOneKilogramPerJoule { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramsPerKiloWattHourTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerJouleTolerance { get { return 1e-5; } } - protected virtual double PoundsPerMechanicalHorsepowerHourTolerance { get { return 1e-5; } } + protected virtual double GramsPerKiloWattHourTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerJouleTolerance { get { return 1E-5; } } + protected virtual double PoundsPerMechanicalHorsepowerHourTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(BrakeSpecificFuelConsumptionUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(BrakeSpecificFuelConsumptionUnit unit) { - var inBaseUnits = BrakeSpecificFuelConsumption.From(1.0, BrakeSpecificFuelConsumption.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = BrakeSpecificFuelConsumption.From(1.0, BrakeSpecificFuelConsumption.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = BrakeSpecificFuelConsumption.From(1.0, BrakeSpecificFuelConsumption.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(BrakeSpecificFuelConsumptionUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(BrakeSpecificFuelConsumptionUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(BrakeSpecificFuelConsumptionUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(BrakeSpecificFuelConsumptionUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = BrakeSpecificFuelConsumption.Units.Where(u => u != BrakeSpecificFuelConsumption.BaseUnit).DefaultIfEmpty(BrakeSpecificFuelConsumption.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = BrakeSpecificFuelConsumption.Units.First(u => u != BrakeSpecificFuelConsumption.BaseUnit); var quantity = BrakeSpecificFuelConsumption.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(new {BrakeSpecificFuelConsumption.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(BrakeSpecificFuelConsumption.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs index e6d03a76dc..f3e59bbd3b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs @@ -47,13 +47,13 @@ public abstract partial class CapacitanceTestsBase : QuantityTestsBase protected abstract double PicofaradsInOneFarad { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double FaradsTolerance { get { return 1e-5; } } - protected virtual double KilofaradsTolerance { get { return 1e-5; } } - protected virtual double MegafaradsTolerance { get { return 1e-5; } } - protected virtual double MicrofaradsTolerance { get { return 1e-5; } } - protected virtual double MillifaradsTolerance { get { return 1e-5; } } - protected virtual double NanofaradsTolerance { get { return 1e-5; } } - protected virtual double PicofaradsTolerance { get { return 1e-5; } } + protected virtual double FaradsTolerance { get { return 1E-5; } } + protected virtual double KilofaradsTolerance { get { return 1E-5; } } + protected virtual double MegafaradsTolerance { get { return 1E-5; } } + protected virtual double MicrofaradsTolerance { get { return 1E-5; } } + protected virtual double MillifaradsTolerance { get { return 1E-5; } } + protected virtual double NanofaradsTolerance { get { return 1E-5; } } + protected virtual double PicofaradsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(CapacitanceUnit unit) @@ -218,7 +218,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -397,14 +397,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(CapacitanceUnit unit) { - var inBaseUnits = Capacitance.From(1.0, Capacitance.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Capacitance.From(1.0, Capacitance.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Capacitance.From(1.0, Capacitance.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(CapacitanceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(CapacitanceUnit unit) @@ -418,8 +425,8 @@ public void ToUnit_WithSameUnits_AreEqual(CapacitanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CapacitanceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Capacitance.Units.Where(u => u != Capacitance.BaseUnit).DefaultIfEmpty(Capacitance.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Capacitance.Units.First(u => u != Capacitance.BaseUnit); var quantity = Capacitance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -632,8 +639,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Capacitance.FromFarads(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -667,36 +675,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Capacitance.FromFarads(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Capacitance.FromFarads(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Capacitance.FromFarads(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Capacitance.FromFarads(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Capacitance.FromFarads(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -709,22 +722,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Capacitance.FromFarads(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Capacitance.FromFarads(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Capacitance.FromFarads(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -766,7 +782,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Capacitance.FromFarads(1.0); - Assert.Equal(new {Capacitance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Capacitance.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs index 01b59f24d5..8cb26ee1e6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class CoefficientOfThermalExpansionTestsBase : QuantityT protected abstract double InverseKelvinInOneInverseKelvin { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double InverseDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double InverseDegreeFahrenheitTolerance { get { return 1e-5; } } - protected virtual double InverseKelvinTolerance { get { return 1e-5; } } + protected virtual double InverseDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double InverseDegreeFahrenheitTolerance { get { return 1E-5; } } + protected virtual double InverseKelvinTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(CoefficientOfThermalExpansionUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -355,14 +355,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(CoefficientOfThermalExpansionUnit unit) { - var inBaseUnits = CoefficientOfThermalExpansion.From(1.0, CoefficientOfThermalExpansion.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = CoefficientOfThermalExpansion.From(1.0, CoefficientOfThermalExpansion.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = CoefficientOfThermalExpansion.From(1.0, CoefficientOfThermalExpansion.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(CoefficientOfThermalExpansionUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(CoefficientOfThermalExpansionUnit unit) @@ -376,8 +383,8 @@ public void ToUnit_WithSameUnits_AreEqual(CoefficientOfThermalExpansionUnit unit [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CoefficientOfThermalExpansionUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = CoefficientOfThermalExpansion.Units.Where(u => u != CoefficientOfThermalExpansion.BaseUnit).DefaultIfEmpty(CoefficientOfThermalExpansion.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = CoefficientOfThermalExpansion.Units.First(u => u != CoefficientOfThermalExpansion.BaseUnit); var quantity = CoefficientOfThermalExpansion.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -578,8 +585,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -613,36 +621,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -655,22 +668,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -712,7 +728,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal(new {CoefficientOfThermalExpansion.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(CoefficientOfThermalExpansion.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs index aaf1331202..32d816d194 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs @@ -47,13 +47,13 @@ public abstract partial class CompressibilityTestsBase : QuantityTestsBase protected abstract double InversePoundsForcePerSquareInchInOneInversePascal { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double InverseAtmospheresTolerance { get { return 1e-5; } } - protected virtual double InverseBarsTolerance { get { return 1e-5; } } - protected virtual double InverseKilopascalsTolerance { get { return 1e-5; } } - protected virtual double InverseMegapascalsTolerance { get { return 1e-5; } } - protected virtual double InverseMillibarsTolerance { get { return 1e-5; } } - protected virtual double InversePascalsTolerance { get { return 1e-5; } } - protected virtual double InversePoundsForcePerSquareInchTolerance { get { return 1e-5; } } + protected virtual double InverseAtmospheresTolerance { get { return 1E-5; } } + protected virtual double InverseBarsTolerance { get { return 1E-5; } } + protected virtual double InverseKilopascalsTolerance { get { return 1E-5; } } + protected virtual double InverseMegapascalsTolerance { get { return 1E-5; } } + protected virtual double InverseMillibarsTolerance { get { return 1E-5; } } + protected virtual double InversePascalsTolerance { get { return 1E-5; } } + protected virtual double InversePoundsForcePerSquareInchTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(CompressibilityUnit unit) @@ -218,7 +218,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -587,14 +587,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(CompressibilityUnit unit) { - var inBaseUnits = Compressibility.From(1.0, Compressibility.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Compressibility.From(1.0, Compressibility.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Compressibility.From(1.0, Compressibility.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(CompressibilityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(CompressibilityUnit unit) @@ -608,8 +615,8 @@ public void ToUnit_WithSameUnits_AreEqual(CompressibilityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CompressibilityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Compressibility.Units.Where(u => u != Compressibility.BaseUnit).DefaultIfEmpty(Compressibility.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Compressibility.Units.First(u => u != Compressibility.BaseUnit); var quantity = Compressibility.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -822,8 +829,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Compressibility.FromInversePascals(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -857,36 +865,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Compressibility.FromInversePascals(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Compressibility.FromInversePascals(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Compressibility.FromInversePascals(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Compressibility.FromInversePascals(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Compressibility.FromInversePascals(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -899,22 +912,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Compressibility.FromInversePascals(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Compressibility.FromInversePascals(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Compressibility.FromInversePascals(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -956,7 +972,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(new {Compressibility.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Compressibility.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs index a37f498d85..4533308beb 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs @@ -91,57 +91,57 @@ public abstract partial class DensityTestsBase : QuantityTestsBase protected abstract double TonnesPerCubicMillimeterInOneKilogramPerCubicMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentigramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double CentigramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double CentigramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double GramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double GramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double KilopoundsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double KilopoundsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double PoundsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double PoundsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double PoundsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double PoundsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double PoundsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double PoundsPerImperialGallonTolerance { get { return 1e-5; } } - protected virtual double PoundsPerUSGallonTolerance { get { return 1e-5; } } - protected virtual double SlugsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double SlugsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double SlugsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double SlugsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double SlugsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicMillimeterTolerance { get { return 1e-5; } } + protected virtual double CentigramsPerDeciLiterTolerance { get { return 1E-5; } } + protected virtual double CentigramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double CentigramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerDeciLiterTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double GramsPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double GramsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double GramsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerCubicMillimeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerDeciLiterTolerance { get { return 1E-5; } } + protected virtual double GramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double GramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerCubicMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double KilopoundsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double KilopoundsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerDeciLiterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerDeciLiterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerDeciLiterTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double PicogramsPerDeciLiterTolerance { get { return 1E-5; } } + protected virtual double PicogramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double PicogramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double PoundsPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double PoundsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double PoundsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double PoundsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double PoundsPerCubicMillimeterTolerance { get { return 1E-5; } } + protected virtual double PoundsPerImperialGallonTolerance { get { return 1E-5; } } + protected virtual double PoundsPerUSGallonTolerance { get { return 1E-5; } } + protected virtual double SlugsPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double SlugsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double SlugsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double SlugsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double SlugsPerCubicMillimeterTolerance { get { return 1E-5; } } + protected virtual double TonnesPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double TonnesPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double TonnesPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double TonnesPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double TonnesPerCubicMillimeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(DensityUnit unit) @@ -658,7 +658,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -2011,14 +2011,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(DensityUnit unit) { - var inBaseUnits = Density.From(1.0, Density.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Density.From(1.0, Density.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Density.From(1.0, Density.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(DensityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(DensityUnit unit) @@ -2032,8 +2039,8 @@ public void ToUnit_WithSameUnits_AreEqual(DensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DensityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Density.Units.Where(u => u != Density.BaseUnit).DefaultIfEmpty(Density.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Density.Units.First(u => u != Density.BaseUnit); var quantity = Density.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2378,8 +2385,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Density.FromKilogramsPerCubicMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -2413,36 +2421,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Density.FromKilogramsPerCubicMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Density.FromKilogramsPerCubicMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Density.FromKilogramsPerCubicMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Density.FromKilogramsPerCubicMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Density.FromKilogramsPerCubicMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -2455,22 +2468,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Density.FromKilogramsPerCubicMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Density.FromKilogramsPerCubicMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Density.FromKilogramsPerCubicMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -2512,7 +2528,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(new {Density.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Density.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs index 528fb07f8f..3868ee2b75 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs @@ -51,17 +51,17 @@ public abstract partial class DurationTestsBase : QuantityTestsBase protected abstract double Years365InOneSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DaysTolerance { get { return 1e-5; } } - protected virtual double HoursTolerance { get { return 1e-5; } } - protected virtual double JulianYearsTolerance { get { return 1e-5; } } - protected virtual double MicrosecondsTolerance { get { return 1e-5; } } - protected virtual double MillisecondsTolerance { get { return 1e-5; } } - protected virtual double MinutesTolerance { get { return 1e-5; } } - protected virtual double Months30Tolerance { get { return 1e-5; } } - protected virtual double NanosecondsTolerance { get { return 1e-5; } } - protected virtual double SecondsTolerance { get { return 1e-5; } } - protected virtual double WeeksTolerance { get { return 1e-5; } } - protected virtual double Years365Tolerance { get { return 1e-5; } } + protected virtual double DaysTolerance { get { return 1E-5; } } + protected virtual double HoursTolerance { get { return 1E-5; } } + protected virtual double JulianYearsTolerance { get { return 1E-5; } } + protected virtual double MicrosecondsTolerance { get { return 1E-5; } } + protected virtual double MillisecondsTolerance { get { return 1E-5; } } + protected virtual double MinutesTolerance { get { return 1E-5; } } + protected virtual double Months30Tolerance { get { return 1E-5; } } + protected virtual double NanosecondsTolerance { get { return 1E-5; } } + protected virtual double SecondsTolerance { get { return 1E-5; } } + protected virtual double WeeksTolerance { get { return 1E-5; } } + protected virtual double Years365Tolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(DurationUnit unit) @@ -258,7 +258,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1731,14 +1731,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(DurationUnit unit) { - var inBaseUnits = Duration.From(1.0, Duration.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Duration.From(1.0, Duration.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Duration.From(1.0, Duration.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(DurationUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(DurationUnit unit) @@ -1752,8 +1759,8 @@ public void ToUnit_WithSameUnits_AreEqual(DurationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DurationUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Duration.Units.Where(u => u != Duration.BaseUnit).DefaultIfEmpty(Duration.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Duration.Units.First(u => u != Duration.BaseUnit); var quantity = Duration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1978,8 +1985,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Duration.FromSeconds(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -2013,36 +2021,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Duration.FromSeconds(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Duration.FromSeconds(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Duration.FromSeconds(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Duration.FromSeconds(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Duration.FromSeconds(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -2055,22 +2068,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Duration.FromSeconds(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Duration.FromSeconds(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Duration.FromSeconds(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -2112,7 +2128,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Duration.FromSeconds(1.0); - Assert.Equal(new {Duration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Duration.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs index ee6a1a3d95..6cf20a34dc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs @@ -50,16 +50,16 @@ public abstract partial class DynamicViscosityTestsBase : QuantityTestsBase protected abstract double ReynsInOneNewtonSecondPerMeterSquared { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentipoiseTolerance { get { return 1e-5; } } - protected virtual double MicropascalSecondsTolerance { get { return 1e-5; } } - protected virtual double MillipascalSecondsTolerance { get { return 1e-5; } } - protected virtual double NewtonSecondsPerMeterSquaredTolerance { get { return 1e-5; } } - protected virtual double PascalSecondsTolerance { get { return 1e-5; } } - protected virtual double PoiseTolerance { get { return 1e-5; } } - protected virtual double PoundsForceSecondPerSquareFootTolerance { get { return 1e-5; } } - protected virtual double PoundsForceSecondPerSquareInchTolerance { get { return 1e-5; } } - protected virtual double PoundsPerFootSecondTolerance { get { return 1e-5; } } - protected virtual double ReynsTolerance { get { return 1e-5; } } + protected virtual double CentipoiseTolerance { get { return 1E-5; } } + protected virtual double MicropascalSecondsTolerance { get { return 1E-5; } } + protected virtual double MillipascalSecondsTolerance { get { return 1E-5; } } + protected virtual double NewtonSecondsPerMeterSquaredTolerance { get { return 1E-5; } } + protected virtual double PascalSecondsTolerance { get { return 1E-5; } } + protected virtual double PoiseTolerance { get { return 1E-5; } } + protected virtual double PoundsForceSecondPerSquareFootTolerance { get { return 1E-5; } } + protected virtual double PoundsForceSecondPerSquareInchTolerance { get { return 1E-5; } } + protected virtual double PoundsPerFootSecondTolerance { get { return 1E-5; } } + protected virtual double ReynsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(DynamicViscosityUnit unit) @@ -248,7 +248,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -593,14 +593,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(DynamicViscosityUnit unit) { - var inBaseUnits = DynamicViscosity.From(1.0, DynamicViscosity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = DynamicViscosity.From(1.0, DynamicViscosity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = DynamicViscosity.From(1.0, DynamicViscosity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(DynamicViscosityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(DynamicViscosityUnit unit) @@ -614,8 +621,8 @@ public void ToUnit_WithSameUnits_AreEqual(DynamicViscosityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DynamicViscosityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = DynamicViscosity.Units.Where(u => u != DynamicViscosity.BaseUnit).DefaultIfEmpty(DynamicViscosity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = DynamicViscosity.Units.First(u => u != DynamicViscosity.BaseUnit); var quantity = DynamicViscosity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -837,8 +844,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -872,36 +880,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -914,22 +927,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -971,7 +987,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(new {DynamicViscosity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(DynamicViscosity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs index baf2955386..13bcf04bc8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class ElectricAdmittanceTestsBase : QuantityTestsBase protected abstract double SiemensInOneSiemens { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double MicrosiemensTolerance { get { return 1e-5; } } - protected virtual double MillisiemensTolerance { get { return 1e-5; } } - protected virtual double NanosiemensTolerance { get { return 1e-5; } } - protected virtual double SiemensTolerance { get { return 1e-5; } } + protected virtual double MicrosiemensTolerance { get { return 1E-5; } } + protected virtual double MillisiemensTolerance { get { return 1E-5; } } + protected virtual double NanosiemensTolerance { get { return 1E-5; } } + protected virtual double SiemensTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricAdmittanceUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -317,14 +317,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricAdmittanceUnit unit) { - var inBaseUnits = ElectricAdmittance.From(1.0, ElectricAdmittance.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricAdmittance.From(1.0, ElectricAdmittance.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricAdmittance.From(1.0, ElectricAdmittance.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricAdmittanceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricAdmittanceUnit unit) @@ -338,8 +345,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricAdmittanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricAdmittanceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricAdmittance.Units.Where(u => u != ElectricAdmittance.BaseUnit).DefaultIfEmpty(ElectricAdmittance.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricAdmittance.Units.First(u => u != ElectricAdmittance.BaseUnit); var quantity = ElectricAdmittance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -543,8 +550,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricAdmittance.FromSiemens(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -578,36 +586,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricAdmittance.FromSiemens(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricAdmittance.FromSiemens(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricAdmittance.FromSiemens(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricAdmittance.FromSiemens(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricAdmittance.FromSiemens(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -620,22 +633,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricAdmittance.FromSiemens(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricAdmittance.FromSiemens(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricAdmittance.FromSiemens(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -677,7 +693,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(new {ElectricAdmittance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricAdmittance.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs index e5f237ac25..97fc662ca0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class ElectricChargeDensityTestsBase : QuantityTestsBase protected abstract double CoulombsPerCubicMeterInOneCoulombPerCubicMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CoulombsPerCubicMeterTolerance { get { return 1e-5; } } + protected virtual double CoulombsPerCubicMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricChargeDensityUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricChargeDensityUnit unit) { - var inBaseUnits = ElectricChargeDensity.From(1.0, ElectricChargeDensity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricChargeDensity.From(1.0, ElectricChargeDensity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricChargeDensity.From(1.0, ElectricChargeDensity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricChargeDensityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricChargeDensityUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricChargeDensityUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricChargeDensityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricChargeDensity.Units.Where(u => u != ElectricChargeDensity.BaseUnit).DefaultIfEmpty(ElectricChargeDensity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricChargeDensity.Units.First(u => u != ElectricChargeDensity.BaseUnit); var quantity = ElectricChargeDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(new {ElectricChargeDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricChargeDensity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs index ffd6b25293..b1583f9a0e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs @@ -45,11 +45,11 @@ public abstract partial class ElectricChargeTestsBase : QuantityTestsBase protected abstract double MilliampereHoursInOneCoulomb { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmpereHoursTolerance { get { return 1e-5; } } - protected virtual double CoulombsTolerance { get { return 1e-5; } } - protected virtual double KiloampereHoursTolerance { get { return 1e-5; } } - protected virtual double MegaampereHoursTolerance { get { return 1e-5; } } - protected virtual double MilliampereHoursTolerance { get { return 1e-5; } } + protected virtual double AmpereHoursTolerance { get { return 1E-5; } } + protected virtual double CoulombsTolerance { get { return 1E-5; } } + protected virtual double KiloampereHoursTolerance { get { return 1E-5; } } + protected virtual double MegaampereHoursTolerance { get { return 1E-5; } } + protected virtual double MilliampereHoursTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricChargeUnit unit) @@ -198,7 +198,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -403,14 +403,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricChargeUnit unit) { - var inBaseUnits = ElectricCharge.From(1.0, ElectricCharge.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricCharge.From(1.0, ElectricCharge.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricCharge.From(1.0, ElectricCharge.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricChargeUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricChargeUnit unit) @@ -424,8 +431,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricChargeUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricChargeUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricCharge.Units.Where(u => u != ElectricCharge.BaseUnit).DefaultIfEmpty(ElectricCharge.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricCharge.Units.First(u => u != ElectricCharge.BaseUnit); var quantity = ElectricCharge.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -632,8 +639,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricCharge.FromCoulombs(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -667,36 +675,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricCharge.FromCoulombs(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricCharge.FromCoulombs(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricCharge.FromCoulombs(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricCharge.FromCoulombs(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricCharge.FromCoulombs(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -709,22 +722,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricCharge.FromCoulombs(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricCharge.FromCoulombs(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricCharge.FromCoulombs(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -766,7 +782,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(new {ElectricCharge.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricCharge.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs index d7e199bded..45c97940ed 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class ElectricConductanceTestsBase : QuantityTestsBase protected abstract double SiemensInOneSiemens { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double MicrosiemensTolerance { get { return 1e-5; } } - protected virtual double MillisiemensTolerance { get { return 1e-5; } } - protected virtual double SiemensTolerance { get { return 1e-5; } } + protected virtual double MicrosiemensTolerance { get { return 1E-5; } } + protected virtual double MillisiemensTolerance { get { return 1E-5; } } + protected virtual double SiemensTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricConductanceUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricConductanceUnit unit) { - var inBaseUnits = ElectricConductance.From(1.0, ElectricConductance.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricConductance.From(1.0, ElectricConductance.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricConductance.From(1.0, ElectricConductance.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricConductanceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricConductanceUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricConductanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricConductanceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricConductance.Units.Where(u => u != ElectricConductance.BaseUnit).DefaultIfEmpty(ElectricConductance.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricConductance.Units.First(u => u != ElectricConductance.BaseUnit); var quantity = ElectricConductance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricConductance.FromSiemens(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricConductance.FromSiemens(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricConductance.FromSiemens(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricConductance.FromSiemens(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricConductance.FromSiemens(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricConductance.FromSiemens(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricConductance.FromSiemens(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricConductance.FromSiemens(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricConductance.FromSiemens(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(new {ElectricConductance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricConductance.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs index 1819849908..07497ee847 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class ElectricConductivityTestsBase : QuantityTestsBase protected abstract double SiemensPerMeterInOneSiemensPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double SiemensPerFootTolerance { get { return 1e-5; } } - protected virtual double SiemensPerInchTolerance { get { return 1e-5; } } - protected virtual double SiemensPerMeterTolerance { get { return 1e-5; } } + protected virtual double SiemensPerFootTolerance { get { return 1E-5; } } + protected virtual double SiemensPerInchTolerance { get { return 1E-5; } } + protected virtual double SiemensPerMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricConductivityUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricConductivityUnit unit) { - var inBaseUnits = ElectricConductivity.From(1.0, ElectricConductivity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricConductivity.From(1.0, ElectricConductivity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricConductivity.From(1.0, ElectricConductivity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricConductivityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricConductivityUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricConductivityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricConductivityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricConductivity.Units.Where(u => u != ElectricConductivity.BaseUnit).DefaultIfEmpty(ElectricConductivity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricConductivity.Units.First(u => u != ElectricConductivity.BaseUnit); var quantity = ElectricConductivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricConductivity.FromSiemensPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricConductivity.FromSiemensPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricConductivity.FromSiemensPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricConductivity.FromSiemensPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricConductivity.FromSiemensPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricConductivity.FromSiemensPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricConductivity.FromSiemensPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricConductivity.FromSiemensPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricConductivity.FromSiemensPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(new {ElectricConductivity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricConductivity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs index 8269cdcded..23c9af5e3b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class ElectricCurrentDensityTestsBase : QuantityTestsBas protected abstract double AmperesPerSquareMeterInOneAmperePerSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmperesPerSquareFootTolerance { get { return 1e-5; } } - protected virtual double AmperesPerSquareInchTolerance { get { return 1e-5; } } - protected virtual double AmperesPerSquareMeterTolerance { get { return 1e-5; } } + protected virtual double AmperesPerSquareFootTolerance { get { return 1E-5; } } + protected virtual double AmperesPerSquareInchTolerance { get { return 1E-5; } } + protected virtual double AmperesPerSquareMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricCurrentDensityUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricCurrentDensityUnit unit) { - var inBaseUnits = ElectricCurrentDensity.From(1.0, ElectricCurrentDensity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricCurrentDensity.From(1.0, ElectricCurrentDensity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricCurrentDensity.From(1.0, ElectricCurrentDensity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricCurrentDensityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentDensityUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentDensityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricCurrentDensity.Units.Where(u => u != ElectricCurrentDensity.BaseUnit).DefaultIfEmpty(ElectricCurrentDensity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricCurrentDensity.Units.First(u => u != ElectricCurrentDensity.BaseUnit); var quantity = ElectricCurrentDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(new {ElectricCurrentDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricCurrentDensity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs index 415f793b1c..dacad49bc8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class ElectricCurrentGradientTestsBase : QuantityTestsBa protected abstract double AmperesPerSecondInOneAmperePerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmperesPerMicrosecondTolerance { get { return 1e-5; } } - protected virtual double AmperesPerMillisecondTolerance { get { return 1e-5; } } - protected virtual double AmperesPerNanosecondTolerance { get { return 1e-5; } } - protected virtual double AmperesPerSecondTolerance { get { return 1e-5; } } + protected virtual double AmperesPerMicrosecondTolerance { get { return 1E-5; } } + protected virtual double AmperesPerMillisecondTolerance { get { return 1E-5; } } + protected virtual double AmperesPerNanosecondTolerance { get { return 1E-5; } } + protected virtual double AmperesPerSecondTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricCurrentGradientUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -317,14 +317,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricCurrentGradientUnit unit) { - var inBaseUnits = ElectricCurrentGradient.From(1.0, ElectricCurrentGradient.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricCurrentGradient.From(1.0, ElectricCurrentGradient.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricCurrentGradient.From(1.0, ElectricCurrentGradient.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricCurrentGradientUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentGradientUnit unit) @@ -338,8 +345,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentGradientUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentGradientUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricCurrentGradient.Units.Where(u => u != ElectricCurrentGradient.BaseUnit).DefaultIfEmpty(ElectricCurrentGradient.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricCurrentGradient.Units.First(u => u != ElectricCurrentGradient.BaseUnit); var quantity = ElectricCurrentGradient.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -543,8 +550,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -578,36 +586,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -620,22 +633,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -677,7 +693,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(new {ElectricCurrentGradient.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricCurrentGradient.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs index 14be5a3b96..0c602d7e0f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs @@ -48,14 +48,14 @@ public abstract partial class ElectricCurrentTestsBase : QuantityTestsBase protected abstract double PicoamperesInOneAmpere { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmperesTolerance { get { return 1e-5; } } - protected virtual double CentiamperesTolerance { get { return 1e-5; } } - protected virtual double KiloamperesTolerance { get { return 1e-5; } } - protected virtual double MegaamperesTolerance { get { return 1e-5; } } - protected virtual double MicroamperesTolerance { get { return 1e-5; } } - protected virtual double MilliamperesTolerance { get { return 1e-5; } } - protected virtual double NanoamperesTolerance { get { return 1e-5; } } - protected virtual double PicoamperesTolerance { get { return 1e-5; } } + protected virtual double AmperesTolerance { get { return 1E-5; } } + protected virtual double CentiamperesTolerance { get { return 1E-5; } } + protected virtual double KiloamperesTolerance { get { return 1E-5; } } + protected virtual double MegaamperesTolerance { get { return 1E-5; } } + protected virtual double MicroamperesTolerance { get { return 1E-5; } } + protected virtual double MilliamperesTolerance { get { return 1E-5; } } + protected virtual double NanoamperesTolerance { get { return 1E-5; } } + protected virtual double PicoamperesTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricCurrentUnit unit) @@ -228,7 +228,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -431,14 +431,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricCurrentUnit unit) { - var inBaseUnits = ElectricCurrent.From(1.0, ElectricCurrent.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricCurrent.From(1.0, ElectricCurrent.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricCurrent.From(1.0, ElectricCurrent.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricCurrentUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentUnit unit) @@ -452,8 +459,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricCurrent.Units.Where(u => u != ElectricCurrent.BaseUnit).DefaultIfEmpty(ElectricCurrent.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricCurrent.Units.First(u => u != ElectricCurrent.BaseUnit); var quantity = ElectricCurrent.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -669,8 +676,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricCurrent.FromAmperes(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -704,36 +712,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricCurrent.FromAmperes(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricCurrent.FromAmperes(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricCurrent.FromAmperes(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricCurrent.FromAmperes(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricCurrent.FromAmperes(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -746,22 +759,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricCurrent.FromAmperes(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricCurrent.FromAmperes(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricCurrent.FromAmperes(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -803,7 +819,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(new {ElectricCurrent.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricCurrent.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs index e75dc3285b..07ad008f4f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class ElectricFieldTestsBase : QuantityTestsBase protected abstract double VoltsPerMeterInOneVoltPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double VoltsPerMeterTolerance { get { return 1e-5; } } + protected virtual double VoltsPerMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricFieldUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricFieldUnit unit) { - var inBaseUnits = ElectricField.From(1.0, ElectricField.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricField.From(1.0, ElectricField.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricField.From(1.0, ElectricField.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricFieldUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricFieldUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricFieldUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricFieldUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricField.Units.Where(u => u != ElectricField.BaseUnit).DefaultIfEmpty(ElectricField.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricField.Units.First(u => u != ElectricField.BaseUnit); var quantity = ElectricField.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricField.FromVoltsPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricField.FromVoltsPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricField.FromVoltsPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricField.FromVoltsPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricField.FromVoltsPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricField.FromVoltsPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricField.FromVoltsPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricField.FromVoltsPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricField.FromVoltsPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(new {ElectricField.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricField.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs index b436a94c0d..1df0aaa724 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class ElectricInductanceTestsBase : QuantityTestsBase protected abstract double NanohenriesInOneHenry { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double HenriesTolerance { get { return 1e-5; } } - protected virtual double MicrohenriesTolerance { get { return 1e-5; } } - protected virtual double MillihenriesTolerance { get { return 1e-5; } } - protected virtual double NanohenriesTolerance { get { return 1e-5; } } + protected virtual double HenriesTolerance { get { return 1E-5; } } + protected virtual double MicrohenriesTolerance { get { return 1E-5; } } + protected virtual double MillihenriesTolerance { get { return 1E-5; } } + protected virtual double NanohenriesTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricInductanceUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -317,14 +317,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricInductanceUnit unit) { - var inBaseUnits = ElectricInductance.From(1.0, ElectricInductance.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricInductance.From(1.0, ElectricInductance.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricInductance.From(1.0, ElectricInductance.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricInductanceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricInductanceUnit unit) @@ -338,8 +345,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricInductanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricInductanceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricInductance.Units.Where(u => u != ElectricInductance.BaseUnit).DefaultIfEmpty(ElectricInductance.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricInductance.Units.First(u => u != ElectricInductance.BaseUnit); var quantity = ElectricInductance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -543,8 +550,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricInductance.FromHenries(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -578,36 +586,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricInductance.FromHenries(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricInductance.FromHenries(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricInductance.FromHenries(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricInductance.FromHenries(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricInductance.FromHenries(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -620,22 +633,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricInductance.FromHenries(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricInductance.FromHenries(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricInductance.FromHenries(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -677,7 +693,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(new {ElectricInductance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricInductance.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs index 54413cf013..18ff2da9ff 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs @@ -45,11 +45,11 @@ public abstract partial class ElectricPotentialAcTestsBase : QuantityTestsBase protected abstract double VoltsAcInOneVoltAc { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltsAcTolerance { get { return 1e-5; } } - protected virtual double MegavoltsAcTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsAcTolerance { get { return 1e-5; } } - protected virtual double MillivoltsAcTolerance { get { return 1e-5; } } - protected virtual double VoltsAcTolerance { get { return 1e-5; } } + protected virtual double KilovoltsAcTolerance { get { return 1E-5; } } + protected virtual double MegavoltsAcTolerance { get { return 1E-5; } } + protected virtual double MicrovoltsAcTolerance { get { return 1E-5; } } + protected virtual double MillivoltsAcTolerance { get { return 1E-5; } } + protected virtual double VoltsAcTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricPotentialAcUnit unit) @@ -198,7 +198,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -329,14 +329,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricPotentialAcUnit unit) { - var inBaseUnits = ElectricPotentialAc.From(1.0, ElectricPotentialAc.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricPotentialAc.From(1.0, ElectricPotentialAc.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricPotentialAc.From(1.0, ElectricPotentialAc.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricPotentialAcUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialAcUnit unit) @@ -350,8 +357,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialAcUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialAcUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricPotentialAc.Units.Where(u => u != ElectricPotentialAc.BaseUnit).DefaultIfEmpty(ElectricPotentialAc.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricPotentialAc.Units.First(u => u != ElectricPotentialAc.BaseUnit); var quantity = ElectricPotentialAc.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -558,8 +565,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricPotentialAc.FromVoltsAc(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -593,36 +601,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricPotentialAc.FromVoltsAc(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricPotentialAc.FromVoltsAc(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricPotentialAc.FromVoltsAc(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricPotentialAc.FromVoltsAc(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricPotentialAc.FromVoltsAc(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -635,22 +648,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricPotentialAc.FromVoltsAc(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricPotentialAc.FromVoltsAc(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricPotentialAc.FromVoltsAc(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -692,7 +708,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal(new {ElectricPotentialAc.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricPotentialAc.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs index 11f38843a9..90068daab5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs @@ -60,26 +60,26 @@ public abstract partial class ElectricPotentialChangeRateTestsBase : QuantityTes protected abstract double VoltsPerSecondsInOneVoltPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltsPerHoursTolerance { get { return 1e-5; } } - protected virtual double KilovoltsPerMicrosecondsTolerance { get { return 1e-5; } } - protected virtual double KilovoltsPerMinutesTolerance { get { return 1e-5; } } - protected virtual double KilovoltsPerSecondsTolerance { get { return 1e-5; } } - protected virtual double MegavoltsPerHoursTolerance { get { return 1e-5; } } - protected virtual double MegavoltsPerMicrosecondsTolerance { get { return 1e-5; } } - protected virtual double MegavoltsPerMinutesTolerance { get { return 1e-5; } } - protected virtual double MegavoltsPerSecondsTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsPerHoursTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsPerMicrosecondsTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsPerMinutesTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsPerSecondsTolerance { get { return 1e-5; } } - protected virtual double MillivoltsPerHoursTolerance { get { return 1e-5; } } - protected virtual double MillivoltsPerMicrosecondsTolerance { get { return 1e-5; } } - protected virtual double MillivoltsPerMinutesTolerance { get { return 1e-5; } } - protected virtual double MillivoltsPerSecondsTolerance { get { return 1e-5; } } - protected virtual double VoltsPerHoursTolerance { get { return 1e-5; } } - protected virtual double VoltsPerMicrosecondsTolerance { get { return 1e-5; } } - protected virtual double VoltsPerMinutesTolerance { get { return 1e-5; } } - protected virtual double VoltsPerSecondsTolerance { get { return 1e-5; } } + protected virtual double KilovoltsPerHoursTolerance { get { return 1E-5; } } + protected virtual double KilovoltsPerMicrosecondsTolerance { get { return 1E-5; } } + protected virtual double KilovoltsPerMinutesTolerance { get { return 1E-5; } } + protected virtual double KilovoltsPerSecondsTolerance { get { return 1E-5; } } + protected virtual double MegavoltsPerHoursTolerance { get { return 1E-5; } } + protected virtual double MegavoltsPerMicrosecondsTolerance { get { return 1E-5; } } + protected virtual double MegavoltsPerMinutesTolerance { get { return 1E-5; } } + protected virtual double MegavoltsPerSecondsTolerance { get { return 1E-5; } } + protected virtual double MicrovoltsPerHoursTolerance { get { return 1E-5; } } + protected virtual double MicrovoltsPerMicrosecondsTolerance { get { return 1E-5; } } + protected virtual double MicrovoltsPerMinutesTolerance { get { return 1E-5; } } + protected virtual double MicrovoltsPerSecondsTolerance { get { return 1E-5; } } + protected virtual double MillivoltsPerHoursTolerance { get { return 1E-5; } } + protected virtual double MillivoltsPerMicrosecondsTolerance { get { return 1E-5; } } + protected virtual double MillivoltsPerMinutesTolerance { get { return 1E-5; } } + protected virtual double MillivoltsPerSecondsTolerance { get { return 1E-5; } } + protected virtual double VoltsPerHoursTolerance { get { return 1E-5; } } + protected virtual double VoltsPerMicrosecondsTolerance { get { return 1E-5; } } + protected virtual double VoltsPerMinutesTolerance { get { return 1E-5; } } + protected virtual double VoltsPerSecondsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricPotentialChangeRateUnit unit) @@ -348,7 +348,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -773,14 +773,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricPotentialChangeRateUnit unit) { - var inBaseUnits = ElectricPotentialChangeRate.From(1.0, ElectricPotentialChangeRate.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricPotentialChangeRate.From(1.0, ElectricPotentialChangeRate.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricPotentialChangeRate.From(1.0, ElectricPotentialChangeRate.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricPotentialChangeRateUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialChangeRateUnit unit) @@ -794,8 +801,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialChangeRateUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricPotentialChangeRate.Units.Where(u => u != ElectricPotentialChangeRate.BaseUnit).DefaultIfEmpty(ElectricPotentialChangeRate.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricPotentialChangeRate.Units.First(u => u != ElectricPotentialChangeRate.BaseUnit); var quantity = ElectricPotentialChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1047,8 +1054,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1082,36 +1090,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1124,22 +1137,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1181,7 +1197,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal(new {ElectricPotentialChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricPotentialChangeRate.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs index d7b84a15dc..f2b5dfedca 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs @@ -45,11 +45,11 @@ public abstract partial class ElectricPotentialDcTestsBase : QuantityTestsBase protected abstract double VoltsDcInOneVoltDc { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltsDcTolerance { get { return 1e-5; } } - protected virtual double MegavoltsDcTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsDcTolerance { get { return 1e-5; } } - protected virtual double MillivoltsDcTolerance { get { return 1e-5; } } - protected virtual double VoltsDcTolerance { get { return 1e-5; } } + protected virtual double KilovoltsDcTolerance { get { return 1E-5; } } + protected virtual double MegavoltsDcTolerance { get { return 1E-5; } } + protected virtual double MicrovoltsDcTolerance { get { return 1E-5; } } + protected virtual double MillivoltsDcTolerance { get { return 1E-5; } } + protected virtual double VoltsDcTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricPotentialDcUnit unit) @@ -198,7 +198,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -329,14 +329,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricPotentialDcUnit unit) { - var inBaseUnits = ElectricPotentialDc.From(1.0, ElectricPotentialDc.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricPotentialDc.From(1.0, ElectricPotentialDc.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricPotentialDc.From(1.0, ElectricPotentialDc.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricPotentialDcUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialDcUnit unit) @@ -350,8 +357,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialDcUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialDcUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricPotentialDc.Units.Where(u => u != ElectricPotentialDc.BaseUnit).DefaultIfEmpty(ElectricPotentialDc.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricPotentialDc.Units.First(u => u != ElectricPotentialDc.BaseUnit); var quantity = ElectricPotentialDc.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -558,8 +565,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricPotentialDc.FromVoltsDc(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -593,36 +601,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricPotentialDc.FromVoltsDc(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricPotentialDc.FromVoltsDc(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricPotentialDc.FromVoltsDc(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricPotentialDc.FromVoltsDc(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricPotentialDc.FromVoltsDc(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -635,22 +648,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricPotentialDc.FromVoltsDc(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricPotentialDc.FromVoltsDc(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricPotentialDc.FromVoltsDc(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -692,7 +708,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal(new {ElectricPotentialDc.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricPotentialDc.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs index 85c888287a..c9ad5757af 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs @@ -45,11 +45,11 @@ public abstract partial class ElectricPotentialTestsBase : QuantityTestsBase protected abstract double VoltsInOneVolt { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltsTolerance { get { return 1e-5; } } - protected virtual double MegavoltsTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsTolerance { get { return 1e-5; } } - protected virtual double MillivoltsTolerance { get { return 1e-5; } } - protected virtual double VoltsTolerance { get { return 1e-5; } } + protected virtual double KilovoltsTolerance { get { return 1E-5; } } + protected virtual double MegavoltsTolerance { get { return 1E-5; } } + protected virtual double MicrovoltsTolerance { get { return 1E-5; } } + protected virtual double MillivoltsTolerance { get { return 1E-5; } } + protected virtual double VoltsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricPotentialUnit unit) @@ -198,7 +198,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -427,14 +427,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricPotentialUnit unit) { - var inBaseUnits = ElectricPotential.From(1.0, ElectricPotential.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricPotential.From(1.0, ElectricPotential.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricPotential.From(1.0, ElectricPotential.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricPotentialUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialUnit unit) @@ -448,8 +455,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricPotential.Units.Where(u => u != ElectricPotential.BaseUnit).DefaultIfEmpty(ElectricPotential.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricPotential.Units.First(u => u != ElectricPotential.BaseUnit); var quantity = ElectricPotential.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -656,8 +663,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricPotential.FromVolts(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -691,36 +699,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricPotential.FromVolts(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricPotential.FromVolts(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricPotential.FromVolts(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricPotential.FromVolts(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricPotential.FromVolts(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -733,22 +746,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricPotential.FromVolts(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricPotential.FromVolts(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricPotential.FromVolts(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -790,7 +806,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(new {ElectricPotential.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricPotential.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs index 2f5ab2b600..bb80d8cfb3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs @@ -46,12 +46,12 @@ public abstract partial class ElectricResistanceTestsBase : QuantityTestsBase protected abstract double OhmsInOneOhm { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GigaohmsTolerance { get { return 1e-5; } } - protected virtual double KiloohmsTolerance { get { return 1e-5; } } - protected virtual double MegaohmsTolerance { get { return 1e-5; } } - protected virtual double MicroohmsTolerance { get { return 1e-5; } } - protected virtual double MilliohmsTolerance { get { return 1e-5; } } - protected virtual double OhmsTolerance { get { return 1e-5; } } + protected virtual double GigaohmsTolerance { get { return 1E-5; } } + protected virtual double KiloohmsTolerance { get { return 1E-5; } } + protected virtual double MegaohmsTolerance { get { return 1E-5; } } + protected virtual double MicroohmsTolerance { get { return 1E-5; } } + protected virtual double MilliohmsTolerance { get { return 1E-5; } } + protected virtual double OhmsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricResistanceUnit unit) @@ -208,7 +208,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -363,14 +363,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricResistanceUnit unit) { - var inBaseUnits = ElectricResistance.From(1.0, ElectricResistance.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricResistance.From(1.0, ElectricResistance.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricResistance.From(1.0, ElectricResistance.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricResistanceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricResistanceUnit unit) @@ -384,8 +391,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricResistanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricResistanceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricResistance.Units.Where(u => u != ElectricResistance.BaseUnit).DefaultIfEmpty(ElectricResistance.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricResistance.Units.First(u => u != ElectricResistance.BaseUnit); var quantity = ElectricResistance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -595,8 +602,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricResistance.FromOhms(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -630,36 +638,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricResistance.FromOhms(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricResistance.FromOhms(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricResistance.FromOhms(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricResistance.FromOhms(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricResistance.FromOhms(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -672,22 +685,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricResistance.FromOhms(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricResistance.FromOhms(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricResistance.FromOhms(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -729,7 +745,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(new {ElectricResistance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricResistance.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs index 061188ed83..e6c2c14fab 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs @@ -54,20 +54,20 @@ public abstract partial class ElectricResistivityTestsBase : QuantityTestsBase protected abstract double PicoohmMetersInOneOhmMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KiloohmsCentimeterTolerance { get { return 1e-5; } } - protected virtual double KiloohmMetersTolerance { get { return 1e-5; } } - protected virtual double MegaohmsCentimeterTolerance { get { return 1e-5; } } - protected virtual double MegaohmMetersTolerance { get { return 1e-5; } } - protected virtual double MicroohmsCentimeterTolerance { get { return 1e-5; } } - protected virtual double MicroohmMetersTolerance { get { return 1e-5; } } - protected virtual double MilliohmsCentimeterTolerance { get { return 1e-5; } } - protected virtual double MilliohmMetersTolerance { get { return 1e-5; } } - protected virtual double NanoohmsCentimeterTolerance { get { return 1e-5; } } - protected virtual double NanoohmMetersTolerance { get { return 1e-5; } } - protected virtual double OhmsCentimeterTolerance { get { return 1e-5; } } - protected virtual double OhmMetersTolerance { get { return 1e-5; } } - protected virtual double PicoohmsCentimeterTolerance { get { return 1e-5; } } - protected virtual double PicoohmMetersTolerance { get { return 1e-5; } } + protected virtual double KiloohmsCentimeterTolerance { get { return 1E-5; } } + protected virtual double KiloohmMetersTolerance { get { return 1E-5; } } + protected virtual double MegaohmsCentimeterTolerance { get { return 1E-5; } } + protected virtual double MegaohmMetersTolerance { get { return 1E-5; } } + protected virtual double MicroohmsCentimeterTolerance { get { return 1E-5; } } + protected virtual double MicroohmMetersTolerance { get { return 1E-5; } } + protected virtual double MilliohmsCentimeterTolerance { get { return 1E-5; } } + protected virtual double MilliohmMetersTolerance { get { return 1E-5; } } + protected virtual double NanoohmsCentimeterTolerance { get { return 1E-5; } } + protected virtual double NanoohmMetersTolerance { get { return 1E-5; } } + protected virtual double OhmsCentimeterTolerance { get { return 1E-5; } } + protected virtual double OhmMetersTolerance { get { return 1E-5; } } + protected virtual double PicoohmsCentimeterTolerance { get { return 1E-5; } } + protected virtual double PicoohmMetersTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricResistivityUnit unit) @@ -288,7 +288,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -613,14 +613,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricResistivityUnit unit) { - var inBaseUnits = ElectricResistivity.From(1.0, ElectricResistivity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricResistivity.From(1.0, ElectricResistivity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricResistivity.From(1.0, ElectricResistivity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricResistivityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricResistivityUnit unit) @@ -634,8 +641,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricResistivityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricResistivityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricResistivity.Units.Where(u => u != ElectricResistivity.BaseUnit).DefaultIfEmpty(ElectricResistivity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricResistivity.Units.First(u => u != ElectricResistivity.BaseUnit); var quantity = ElectricResistivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -869,8 +876,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricResistivity.FromOhmMeters(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -904,36 +912,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricResistivity.FromOhmMeters(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricResistivity.FromOhmMeters(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricResistivity.FromOhmMeters(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricResistivity.FromOhmMeters(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricResistivity.FromOhmMeters(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -946,22 +959,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricResistivity.FromOhmMeters(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricResistivity.FromOhmMeters(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricResistivity.FromOhmMeters(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1003,7 +1019,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(new {ElectricResistivity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricResistivity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs index 50650f67de..ffd7ee2f84 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class ElectricSurfaceChargeDensityTestsBase : QuantityTe protected abstract double CoulombsPerSquareMeterInOneCoulombPerSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CoulombsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double CoulombsPerSquareInchTolerance { get { return 1e-5; } } - protected virtual double CoulombsPerSquareMeterTolerance { get { return 1e-5; } } + protected virtual double CoulombsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double CoulombsPerSquareInchTolerance { get { return 1E-5; } } + protected virtual double CoulombsPerSquareMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ElectricSurfaceChargeDensityUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricSurfaceChargeDensityUnit unit) { - var inBaseUnits = ElectricSurfaceChargeDensity.From(1.0, ElectricSurfaceChargeDensity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ElectricSurfaceChargeDensity.From(1.0, ElectricSurfaceChargeDensity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ElectricSurfaceChargeDensity.From(1.0, ElectricSurfaceChargeDensity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ElectricSurfaceChargeDensityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ElectricSurfaceChargeDensityUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricSurfaceChargeDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricSurfaceChargeDensityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ElectricSurfaceChargeDensity.Units.Where(u => u != ElectricSurfaceChargeDensity.BaseUnit).DefaultIfEmpty(ElectricSurfaceChargeDensity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ElectricSurfaceChargeDensity.Units.First(u => u != ElectricSurfaceChargeDensity.BaseUnit); var quantity = ElectricSurfaceChargeDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(new {ElectricSurfaceChargeDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ElectricSurfaceChargeDensity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs index 22b563d859..37c8e3730f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs @@ -76,42 +76,42 @@ public abstract partial class EnergyTestsBase : QuantityTestsBase protected abstract double WattHoursInOneJoule { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BritishThermalUnitsTolerance { get { return 1e-5; } } - protected virtual double CaloriesTolerance { get { return 1e-5; } } - protected virtual double DecathermsEcTolerance { get { return 1e-5; } } - protected virtual double DecathermsImperialTolerance { get { return 1e-5; } } - protected virtual double DecathermsUsTolerance { get { return 1e-5; } } - protected virtual double ElectronVoltsTolerance { get { return 1e-5; } } - protected virtual double ErgsTolerance { get { return 1e-5; } } - protected virtual double FootPoundsTolerance { get { return 1e-5; } } - protected virtual double GigabritishThermalUnitsTolerance { get { return 1e-5; } } - protected virtual double GigaelectronVoltsTolerance { get { return 1e-5; } } - protected virtual double GigajoulesTolerance { get { return 1e-5; } } - protected virtual double GigawattDaysTolerance { get { return 1e-5; } } - protected virtual double GigawattHoursTolerance { get { return 1e-5; } } - protected virtual double HorsepowerHoursTolerance { get { return 1e-5; } } - protected virtual double JoulesTolerance { get { return 1e-5; } } - protected virtual double KilobritishThermalUnitsTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesTolerance { get { return 1e-5; } } - protected virtual double KiloelectronVoltsTolerance { get { return 1e-5; } } - protected virtual double KilojoulesTolerance { get { return 1e-5; } } - protected virtual double KilowattDaysTolerance { get { return 1e-5; } } - protected virtual double KilowattHoursTolerance { get { return 1e-5; } } - protected virtual double MegabritishThermalUnitsTolerance { get { return 1e-5; } } - protected virtual double MegacaloriesTolerance { get { return 1e-5; } } - protected virtual double MegaelectronVoltsTolerance { get { return 1e-5; } } - protected virtual double MegajoulesTolerance { get { return 1e-5; } } - protected virtual double MegawattDaysTolerance { get { return 1e-5; } } - protected virtual double MegawattHoursTolerance { get { return 1e-5; } } - protected virtual double MillijoulesTolerance { get { return 1e-5; } } - protected virtual double TeraelectronVoltsTolerance { get { return 1e-5; } } - protected virtual double TerawattDaysTolerance { get { return 1e-5; } } - protected virtual double TerawattHoursTolerance { get { return 1e-5; } } - protected virtual double ThermsEcTolerance { get { return 1e-5; } } - protected virtual double ThermsImperialTolerance { get { return 1e-5; } } - protected virtual double ThermsUsTolerance { get { return 1e-5; } } - protected virtual double WattDaysTolerance { get { return 1e-5; } } - protected virtual double WattHoursTolerance { get { return 1e-5; } } + protected virtual double BritishThermalUnitsTolerance { get { return 1E-5; } } + protected virtual double CaloriesTolerance { get { return 1E-5; } } + protected virtual double DecathermsEcTolerance { get { return 1E-5; } } + protected virtual double DecathermsImperialTolerance { get { return 1E-5; } } + protected virtual double DecathermsUsTolerance { get { return 1E-5; } } + protected virtual double ElectronVoltsTolerance { get { return 1E-5; } } + protected virtual double ErgsTolerance { get { return 1E-5; } } + protected virtual double FootPoundsTolerance { get { return 1E-5; } } + protected virtual double GigabritishThermalUnitsTolerance { get { return 1E-5; } } + protected virtual double GigaelectronVoltsTolerance { get { return 1E-5; } } + protected virtual double GigajoulesTolerance { get { return 1E-5; } } + protected virtual double GigawattDaysTolerance { get { return 1E-5; } } + protected virtual double GigawattHoursTolerance { get { return 1E-5; } } + protected virtual double HorsepowerHoursTolerance { get { return 1E-5; } } + protected virtual double JoulesTolerance { get { return 1E-5; } } + protected virtual double KilobritishThermalUnitsTolerance { get { return 1E-5; } } + protected virtual double KilocaloriesTolerance { get { return 1E-5; } } + protected virtual double KiloelectronVoltsTolerance { get { return 1E-5; } } + protected virtual double KilojoulesTolerance { get { return 1E-5; } } + protected virtual double KilowattDaysTolerance { get { return 1E-5; } } + protected virtual double KilowattHoursTolerance { get { return 1E-5; } } + protected virtual double MegabritishThermalUnitsTolerance { get { return 1E-5; } } + protected virtual double MegacaloriesTolerance { get { return 1E-5; } } + protected virtual double MegaelectronVoltsTolerance { get { return 1E-5; } } + protected virtual double MegajoulesTolerance { get { return 1E-5; } } + protected virtual double MegawattDaysTolerance { get { return 1E-5; } } + protected virtual double MegawattHoursTolerance { get { return 1E-5; } } + protected virtual double MillijoulesTolerance { get { return 1E-5; } } + protected virtual double TeraelectronVoltsTolerance { get { return 1E-5; } } + protected virtual double TerawattDaysTolerance { get { return 1E-5; } } + protected virtual double TerawattHoursTolerance { get { return 1E-5; } } + protected virtual double ThermsEcTolerance { get { return 1E-5; } } + protected virtual double ThermsImperialTolerance { get { return 1E-5; } } + protected virtual double ThermsUsTolerance { get { return 1E-5; } } + protected virtual double WattDaysTolerance { get { return 1E-5; } } + protected virtual double WattHoursTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(EnergyUnit unit) @@ -508,7 +508,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1887,14 +1887,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(EnergyUnit unit) { - var inBaseUnits = Energy.From(1.0, Energy.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Energy.From(1.0, Energy.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Energy.From(1.0, Energy.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(EnergyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(EnergyUnit unit) @@ -1908,8 +1915,8 @@ public void ToUnit_WithSameUnits_AreEqual(EnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EnergyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Energy.Units.Where(u => u != Energy.BaseUnit).DefaultIfEmpty(Energy.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Energy.Units.First(u => u != Energy.BaseUnit); var quantity = Energy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2209,8 +2216,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Energy.FromJoules(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -2244,36 +2252,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Energy.FromJoules(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Energy.FromJoules(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Energy.FromJoules(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Energy.FromJoules(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Energy.FromJoules(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -2286,22 +2299,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Energy.FromJoules(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Energy.FromJoules(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Energy.FromJoules(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -2343,7 +2359,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Energy.FromJoules(1.0); - Assert.Equal(new {Energy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Energy.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs index 06ae0fd4e5..acfce61703 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs @@ -47,13 +47,13 @@ public abstract partial class EntropyTestsBase : QuantityTestsBase protected abstract double MegajoulesPerKelvinInOneJoulePerKelvin { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CaloriesPerKelvinTolerance { get { return 1e-5; } } - protected virtual double JoulesPerDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double JoulesPerKelvinTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerKelvinTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerKelvinTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerKelvinTolerance { get { return 1e-5; } } + protected virtual double CaloriesPerKelvinTolerance { get { return 1E-5; } } + protected virtual double JoulesPerDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double JoulesPerKelvinTolerance { get { return 1E-5; } } + protected virtual double KilocaloriesPerKelvinTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerKelvinTolerance { get { return 1E-5; } } + protected virtual double MegajoulesPerKelvinTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(EntropyUnit unit) @@ -218,7 +218,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -419,14 +419,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(EntropyUnit unit) { - var inBaseUnits = Entropy.From(1.0, Entropy.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Entropy.From(1.0, Entropy.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Entropy.From(1.0, Entropy.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(EntropyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(EntropyUnit unit) @@ -440,8 +447,8 @@ public void ToUnit_WithSameUnits_AreEqual(EntropyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EntropyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Entropy.Units.Where(u => u != Entropy.BaseUnit).DefaultIfEmpty(Entropy.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Entropy.Units.First(u => u != Entropy.BaseUnit); var quantity = Entropy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -654,8 +661,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Entropy.FromJoulesPerKelvin(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -689,36 +697,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Entropy.FromJoulesPerKelvin(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Entropy.FromJoulesPerKelvin(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Entropy.FromJoulesPerKelvin(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Entropy.FromJoulesPerKelvin(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Entropy.FromJoulesPerKelvin(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -731,22 +744,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Entropy.FromJoulesPerKelvin(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Entropy.FromJoulesPerKelvin(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Entropy.FromJoulesPerKelvin(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -788,7 +804,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(new {Entropy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Entropy.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs index 6e46e12a28..e0e2d9473f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs @@ -55,21 +55,21 @@ public abstract partial class ForceChangeRateTestsBase : QuantityTestsBase protected abstract double PoundsForcePerSecondInOneNewtonPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentinewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecanewtonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double DecanewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecinewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerMinuteTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerSecondTolerance { get { return 1e-5; } } - protected virtual double MicronewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MillinewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanonewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerMinuteTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerSecondTolerance { get { return 1e-5; } } + protected virtual double CentinewtonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double DecanewtonsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double DecanewtonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double DecinewtonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerMinuteTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerSecondTolerance { get { return 1E-5; } } + protected virtual double MicronewtonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double MillinewtonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double NanonewtonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerMinuteTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerSecondTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ForceChangeRateUnit unit) @@ -298,7 +298,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -787,14 +787,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ForceChangeRateUnit unit) { - var inBaseUnits = ForceChangeRate.From(1.0, ForceChangeRate.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ForceChangeRate.From(1.0, ForceChangeRate.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ForceChangeRate.From(1.0, ForceChangeRate.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ForceChangeRateUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ForceChangeRateUnit unit) @@ -808,8 +815,8 @@ public void ToUnit_WithSameUnits_AreEqual(ForceChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForceChangeRateUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ForceChangeRate.Units.Where(u => u != ForceChangeRate.BaseUnit).DefaultIfEmpty(ForceChangeRate.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ForceChangeRate.Units.First(u => u != ForceChangeRate.BaseUnit); var quantity = ForceChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1046,8 +1053,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ForceChangeRate.FromNewtonsPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1081,36 +1089,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ForceChangeRate.FromNewtonsPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ForceChangeRate.FromNewtonsPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ForceChangeRate.FromNewtonsPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ForceChangeRate.FromNewtonsPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ForceChangeRate.FromNewtonsPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1123,22 +1136,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ForceChangeRate.FromNewtonsPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ForceChangeRate.FromNewtonsPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ForceChangeRate.FromNewtonsPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1180,7 +1196,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(new {ForceChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ForceChangeRate.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs index c9979db3cf..2b2a3554ad 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs @@ -78,44 +78,44 @@ public abstract partial class ForcePerLengthTestsBase : QuantityTestsBase protected abstract double TonnesForcePerMillimeterInOneNewtonPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentinewtonsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double CentinewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double CentinewtonsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double DecanewtonsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double DecanewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double DecanewtonsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double DecinewtonsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double DecinewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double DecinewtonsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerFootTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerInchTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double MicronewtonsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double MicronewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MicronewtonsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double MillinewtonsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double MillinewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MillinewtonsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double NanonewtonsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double NanonewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double NanonewtonsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerFootTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerInchTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerYardTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerCentimeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerMeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerMillimeterTolerance { get { return 1e-5; } } + protected virtual double CentinewtonsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double CentinewtonsPerMeterTolerance { get { return 1E-5; } } + protected virtual double CentinewtonsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double DecanewtonsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double DecanewtonsPerMeterTolerance { get { return 1E-5; } } + protected virtual double DecanewtonsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double DecinewtonsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double DecinewtonsPerMeterTolerance { get { return 1E-5; } } + protected virtual double DecinewtonsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsForcePerCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsForcePerMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsForcePerMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerFootTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerInchTolerance { get { return 1E-5; } } + protected virtual double MeganewtonsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double MeganewtonsPerMeterTolerance { get { return 1E-5; } } + protected virtual double MeganewtonsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double MicronewtonsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double MicronewtonsPerMeterTolerance { get { return 1E-5; } } + protected virtual double MicronewtonsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double MillinewtonsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double MillinewtonsPerMeterTolerance { get { return 1E-5; } } + protected virtual double MillinewtonsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double NanonewtonsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double NanonewtonsPerMeterTolerance { get { return 1E-5; } } + protected virtual double NanonewtonsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerMeterTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerFootTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerInchTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerYardTolerance { get { return 1E-5; } } + protected virtual double TonnesForcePerCentimeterTolerance { get { return 1E-5; } } + protected virtual double TonnesForcePerMeterTolerance { get { return 1E-5; } } + protected virtual double TonnesForcePerMillimeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ForcePerLengthUnit unit) @@ -528,7 +528,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1647,14 +1647,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ForcePerLengthUnit unit) { - var inBaseUnits = ForcePerLength.From(1.0, ForcePerLength.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ForcePerLength.From(1.0, ForcePerLength.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ForcePerLength.From(1.0, ForcePerLength.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ForcePerLengthUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ForcePerLengthUnit unit) @@ -1668,8 +1675,8 @@ public void ToUnit_WithSameUnits_AreEqual(ForcePerLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForcePerLengthUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ForcePerLength.Units.Where(u => u != ForcePerLength.BaseUnit).DefaultIfEmpty(ForcePerLength.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ForcePerLength.Units.First(u => u != ForcePerLength.BaseUnit); var quantity = ForcePerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1975,8 +1982,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ForcePerLength.FromNewtonsPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -2010,36 +2018,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ForcePerLength.FromNewtonsPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ForcePerLength.FromNewtonsPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ForcePerLength.FromNewtonsPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ForcePerLength.FromNewtonsPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ForcePerLength.FromNewtonsPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -2052,22 +2065,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ForcePerLength.FromNewtonsPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ForcePerLength.FromNewtonsPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ForcePerLength.FromNewtonsPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -2109,7 +2125,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(new {ForcePerLength.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ForcePerLength.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs index 28a015c7a7..cd8251764d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs @@ -55,21 +55,21 @@ public abstract partial class ForceTestsBase : QuantityTestsBase protected abstract double TonnesForceInOneNewton { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecanewtonsTolerance { get { return 1e-5; } } - protected virtual double DyneTolerance { get { return 1e-5; } } - protected virtual double KilogramsForceTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsTolerance { get { return 1e-5; } } - protected virtual double KiloPondsTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForceTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsTolerance { get { return 1e-5; } } - protected virtual double MicronewtonsTolerance { get { return 1e-5; } } - protected virtual double MillinewtonsTolerance { get { return 1e-5; } } - protected virtual double NewtonsTolerance { get { return 1e-5; } } - protected virtual double OunceForceTolerance { get { return 1e-5; } } - protected virtual double PoundalsTolerance { get { return 1e-5; } } - protected virtual double PoundsForceTolerance { get { return 1e-5; } } - protected virtual double ShortTonsForceTolerance { get { return 1e-5; } } - protected virtual double TonnesForceTolerance { get { return 1e-5; } } + protected virtual double DecanewtonsTolerance { get { return 1E-5; } } + protected virtual double DyneTolerance { get { return 1E-5; } } + protected virtual double KilogramsForceTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsTolerance { get { return 1E-5; } } + protected virtual double KiloPondsTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForceTolerance { get { return 1E-5; } } + protected virtual double MeganewtonsTolerance { get { return 1E-5; } } + protected virtual double MicronewtonsTolerance { get { return 1E-5; } } + protected virtual double MillinewtonsTolerance { get { return 1E-5; } } + protected virtual double NewtonsTolerance { get { return 1E-5; } } + protected virtual double OunceForceTolerance { get { return 1E-5; } } + protected virtual double PoundalsTolerance { get { return 1E-5; } } + protected virtual double PoundsForceTolerance { get { return 1E-5; } } + protected virtual double ShortTonsForceTolerance { get { return 1E-5; } } + protected virtual double TonnesForceTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ForceUnit unit) @@ -298,7 +298,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1105,14 +1105,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ForceUnit unit) { - var inBaseUnits = Force.From(1.0, Force.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Force.From(1.0, Force.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Force.From(1.0, Force.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ForceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ForceUnit unit) @@ -1126,8 +1133,8 @@ public void ToUnit_WithSameUnits_AreEqual(ForceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Force.Units.Where(u => u != Force.BaseUnit).DefaultIfEmpty(Force.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Force.Units.First(u => u != Force.BaseUnit); var quantity = Force.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1364,8 +1371,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Force.FromNewtons(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1399,36 +1407,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Force.FromNewtons(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Force.FromNewtons(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Force.FromNewtons(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Force.FromNewtons(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Force.FromNewtons(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1441,22 +1454,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Force.FromNewtons(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Force.FromNewtons(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Force.FromNewtons(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1498,7 +1514,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Force.FromNewtons(1.0); - Assert.Equal(new {Force.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Force.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs index 6235036d30..1cd5ef04d7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs @@ -51,17 +51,17 @@ public abstract partial class FrequencyTestsBase : QuantityTestsBase protected abstract double TerahertzInOneHertz { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BeatsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double BUnitsTolerance { get { return 1e-5; } } - protected virtual double CyclesPerHourTolerance { get { return 1e-5; } } - protected virtual double CyclesPerMinuteTolerance { get { return 1e-5; } } - protected virtual double GigahertzTolerance { get { return 1e-5; } } - protected virtual double HertzTolerance { get { return 1e-5; } } - protected virtual double KilohertzTolerance { get { return 1e-5; } } - protected virtual double MegahertzTolerance { get { return 1e-5; } } - protected virtual double PerSecondTolerance { get { return 1e-5; } } - protected virtual double RadiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double TerahertzTolerance { get { return 1e-5; } } + protected virtual double BeatsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double BUnitsTolerance { get { return 1E-5; } } + protected virtual double CyclesPerHourTolerance { get { return 1E-5; } } + protected virtual double CyclesPerMinuteTolerance { get { return 1E-5; } } + protected virtual double GigahertzTolerance { get { return 1E-5; } } + protected virtual double HertzTolerance { get { return 1E-5; } } + protected virtual double KilohertzTolerance { get { return 1E-5; } } + protected virtual double MegahertzTolerance { get { return 1E-5; } } + protected virtual double PerSecondTolerance { get { return 1E-5; } } + protected virtual double RadiansPerSecondTolerance { get { return 1E-5; } } + protected virtual double TerahertzTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(FrequencyUnit unit) @@ -258,7 +258,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -723,14 +723,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(FrequencyUnit unit) { - var inBaseUnits = Frequency.From(1.0, Frequency.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Frequency.From(1.0, Frequency.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Frequency.From(1.0, Frequency.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(FrequencyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(FrequencyUnit unit) @@ -744,8 +751,8 @@ public void ToUnit_WithSameUnits_AreEqual(FrequencyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FrequencyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Frequency.Units.Where(u => u != Frequency.BaseUnit).DefaultIfEmpty(Frequency.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Frequency.Units.First(u => u != Frequency.BaseUnit); var quantity = Frequency.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -970,8 +977,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Frequency.FromHertz(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1005,36 +1013,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Frequency.FromHertz(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Frequency.FromHertz(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Frequency.FromHertz(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Frequency.FromHertz(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Frequency.FromHertz(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1047,22 +1060,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Frequency.FromHertz(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Frequency.FromHertz(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Frequency.FromHertz(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1104,7 +1120,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Frequency.FromHertz(1.0); - Assert.Equal(new {Frequency.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Frequency.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs index 267c73802f..188d454a36 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class FuelEfficiencyTestsBase : QuantityTestsBase protected abstract double MilesPerUsGallonInOneLiterPer100Kilometers { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilometersPerLitersTolerance { get { return 1e-5; } } - protected virtual double LitersPer100KilometersTolerance { get { return 1e-5; } } - protected virtual double MilesPerUkGallonTolerance { get { return 1e-5; } } - protected virtual double MilesPerUsGallonTolerance { get { return 1e-5; } } + protected virtual double KilometersPerLitersTolerance { get { return 1E-5; } } + protected virtual double LitersPer100KilometersTolerance { get { return 1E-5; } } + protected virtual double MilesPerUkGallonTolerance { get { return 1E-5; } } + protected virtual double MilesPerUsGallonTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(FuelEfficiencyUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -317,14 +317,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(FuelEfficiencyUnit unit) { - var inBaseUnits = FuelEfficiency.From(1.0, FuelEfficiency.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = FuelEfficiency.From(1.0, FuelEfficiency.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = FuelEfficiency.From(1.0, FuelEfficiency.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(FuelEfficiencyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(FuelEfficiencyUnit unit) @@ -338,8 +345,8 @@ public void ToUnit_WithSameUnits_AreEqual(FuelEfficiencyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FuelEfficiencyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = FuelEfficiency.Units.Where(u => u != FuelEfficiency.BaseUnit).DefaultIfEmpty(FuelEfficiency.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = FuelEfficiency.Units.First(u => u != FuelEfficiency.BaseUnit); var quantity = FuelEfficiency.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -543,8 +550,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = FuelEfficiency.FromLitersPer100Kilometers(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -578,36 +586,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = FuelEfficiency.FromLitersPer100Kilometers(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = FuelEfficiency.FromLitersPer100Kilometers(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = FuelEfficiency.FromLitersPer100Kilometers(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = FuelEfficiency.FromLitersPer100Kilometers(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = FuelEfficiency.FromLitersPer100Kilometers(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -620,22 +633,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = FuelEfficiency.FromLitersPer100Kilometers(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = FuelEfficiency.FromLitersPer100Kilometers(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = FuelEfficiency.FromLitersPer100Kilometers(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -677,7 +693,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal(new {FuelEfficiency.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(FuelEfficiency.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs index d894f51294..a4d2ec5d11 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs @@ -58,24 +58,24 @@ public abstract partial class HeatFluxTestsBase : QuantityTestsBase protected abstract double WattsPerSquareMeterInOneWattPerSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BtusPerHourSquareFootTolerance { get { return 1e-5; } } - protected virtual double BtusPerMinuteSquareFootTolerance { get { return 1e-5; } } - protected virtual double BtusPerSecondSquareFootTolerance { get { return 1e-5; } } - protected virtual double BtusPerSecondSquareInchTolerance { get { return 1e-5; } } - protected virtual double CaloriesPerSecondSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double CentiwattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerHourSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerSecondSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerFootSecondTolerance { get { return 1e-5; } } - protected virtual double PoundsPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareFootTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareInchTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareMeterTolerance { get { return 1e-5; } } + protected virtual double BtusPerHourSquareFootTolerance { get { return 1E-5; } } + protected virtual double BtusPerMinuteSquareFootTolerance { get { return 1E-5; } } + protected virtual double BtusPerSecondSquareFootTolerance { get { return 1E-5; } } + protected virtual double BtusPerSecondSquareInchTolerance { get { return 1E-5; } } + protected virtual double CaloriesPerSecondSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double CentiwattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double DeciwattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double KilocaloriesPerHourSquareMeterTolerance { get { return 1E-5; } } + protected virtual double KilocaloriesPerSecondSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double MicrowattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double NanowattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerFootSecondTolerance { get { return 1E-5; } } + protected virtual double PoundsPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double WattsPerSquareFootTolerance { get { return 1E-5; } } + protected virtual double WattsPerSquareInchTolerance { get { return 1E-5; } } + protected virtual double WattsPerSquareMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(HeatFluxUnit unit) @@ -328,7 +328,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -817,14 +817,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(HeatFluxUnit unit) { - var inBaseUnits = HeatFlux.From(1.0, HeatFlux.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = HeatFlux.From(1.0, HeatFlux.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = HeatFlux.From(1.0, HeatFlux.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(HeatFluxUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(HeatFluxUnit unit) @@ -838,8 +845,8 @@ public void ToUnit_WithSameUnits_AreEqual(HeatFluxUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(HeatFluxUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = HeatFlux.Units.Where(u => u != HeatFlux.BaseUnit).DefaultIfEmpty(HeatFlux.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = HeatFlux.Units.First(u => u != HeatFlux.BaseUnit); var quantity = HeatFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1085,8 +1092,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = HeatFlux.FromWattsPerSquareMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1120,36 +1128,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = HeatFlux.FromWattsPerSquareMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = HeatFlux.FromWattsPerSquareMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = HeatFlux.FromWattsPerSquareMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = HeatFlux.FromWattsPerSquareMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = HeatFlux.FromWattsPerSquareMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1162,22 +1175,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = HeatFlux.FromWattsPerSquareMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = HeatFlux.FromWattsPerSquareMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = HeatFlux.FromWattsPerSquareMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1219,7 +1235,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(new {HeatFlux.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(HeatFlux.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs index 0050e1ba0e..4c041ee287 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class HeatTransferCoefficientTestsBase : QuantityTestsBa protected abstract double WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BtusPerSquareFootDegreeFahrenheitTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareMeterCelsiusTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareMeterKelvinTolerance { get { return 1e-5; } } + protected virtual double BtusPerSquareFootDegreeFahrenheitTolerance { get { return 1E-5; } } + protected virtual double WattsPerSquareMeterCelsiusTolerance { get { return 1E-5; } } + protected virtual double WattsPerSquareMeterKelvinTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(HeatTransferCoefficientUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(HeatTransferCoefficientUnit unit) { - var inBaseUnits = HeatTransferCoefficient.From(1.0, HeatTransferCoefficient.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = HeatTransferCoefficient.From(1.0, HeatTransferCoefficient.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = HeatTransferCoefficient.From(1.0, HeatTransferCoefficient.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(HeatTransferCoefficientUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(HeatTransferCoefficientUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(HeatTransferCoefficientUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(HeatTransferCoefficientUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = HeatTransferCoefficient.Units.Where(u => u != HeatTransferCoefficient.BaseUnit).DefaultIfEmpty(HeatTransferCoefficient.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = HeatTransferCoefficient.Units.First(u => u != HeatTransferCoefficient.BaseUnit); var quantity = HeatTransferCoefficient.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(new {HeatTransferCoefficient.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(HeatTransferCoefficient.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs index d53ecaf4e4..112256392c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class IlluminanceTestsBase : QuantityTestsBase protected abstract double MilliluxInOneLux { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KiloluxTolerance { get { return 1e-5; } } - protected virtual double LuxTolerance { get { return 1e-5; } } - protected virtual double MegaluxTolerance { get { return 1e-5; } } - protected virtual double MilliluxTolerance { get { return 1e-5; } } + protected virtual double KiloluxTolerance { get { return 1E-5; } } + protected virtual double LuxTolerance { get { return 1E-5; } } + protected virtual double MegaluxTolerance { get { return 1E-5; } } + protected virtual double MilliluxTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(IlluminanceUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -295,14 +295,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(IlluminanceUnit unit) { - var inBaseUnits = Illuminance.From(1.0, Illuminance.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Illuminance.From(1.0, Illuminance.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Illuminance.From(1.0, Illuminance.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(IlluminanceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(IlluminanceUnit unit) @@ -316,8 +323,8 @@ public void ToUnit_WithSameUnits_AreEqual(IlluminanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IlluminanceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Illuminance.Units.Where(u => u != Illuminance.BaseUnit).DefaultIfEmpty(Illuminance.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Illuminance.Units.First(u => u != Illuminance.BaseUnit); var quantity = Illuminance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -521,8 +528,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Illuminance.FromLux(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -556,36 +564,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Illuminance.FromLux(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Illuminance.FromLux(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Illuminance.FromLux(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Illuminance.FromLux(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Illuminance.FromLux(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -598,22 +611,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Illuminance.FromLux(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Illuminance.FromLux(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Illuminance.FromLux(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -655,7 +671,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Illuminance.FromLux(1.0); - Assert.Equal(new {Illuminance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Illuminance.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs index f48c5b7434..4224811b4b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs @@ -38,63 +38,63 @@ namespace UnitsNet.Tests // ReSharper disable once PartialTypeWithSinglePart public abstract partial class InformationTestsBase : QuantityTestsBase { - protected abstract double BitsInOneBit { get; } - protected abstract double BytesInOneBit { get; } - protected abstract double ExabitsInOneBit { get; } - protected abstract double ExabytesInOneBit { get; } - protected abstract double ExbibitsInOneBit { get; } - protected abstract double ExbibytesInOneBit { get; } - protected abstract double GibibitsInOneBit { get; } - protected abstract double GibibytesInOneBit { get; } - protected abstract double GigabitsInOneBit { get; } - protected abstract double GigabytesInOneBit { get; } - protected abstract double KibibitsInOneBit { get; } - protected abstract double KibibytesInOneBit { get; } - protected abstract double KilobitsInOneBit { get; } - protected abstract double KilobytesInOneBit { get; } - protected abstract double MebibitsInOneBit { get; } - protected abstract double MebibytesInOneBit { get; } - protected abstract double MegabitsInOneBit { get; } - protected abstract double MegabytesInOneBit { get; } - protected abstract double PebibitsInOneBit { get; } - protected abstract double PebibytesInOneBit { get; } - protected abstract double PetabitsInOneBit { get; } - protected abstract double PetabytesInOneBit { get; } - protected abstract double TebibitsInOneBit { get; } - protected abstract double TebibytesInOneBit { get; } - protected abstract double TerabitsInOneBit { get; } - protected abstract double TerabytesInOneBit { get; } + protected abstract decimal BitsInOneBit { get; } + protected abstract decimal BytesInOneBit { get; } + protected abstract decimal ExabitsInOneBit { get; } + protected abstract decimal ExabytesInOneBit { get; } + protected abstract decimal ExbibitsInOneBit { get; } + protected abstract decimal ExbibytesInOneBit { get; } + protected abstract decimal GibibitsInOneBit { get; } + protected abstract decimal GibibytesInOneBit { get; } + protected abstract decimal GigabitsInOneBit { get; } + protected abstract decimal GigabytesInOneBit { get; } + protected abstract decimal KibibitsInOneBit { get; } + protected abstract decimal KibibytesInOneBit { get; } + protected abstract decimal KilobitsInOneBit { get; } + protected abstract decimal KilobytesInOneBit { get; } + protected abstract decimal MebibitsInOneBit { get; } + protected abstract decimal MebibytesInOneBit { get; } + protected abstract decimal MegabitsInOneBit { get; } + protected abstract decimal MegabytesInOneBit { get; } + protected abstract decimal PebibitsInOneBit { get; } + protected abstract decimal PebibytesInOneBit { get; } + protected abstract decimal PetabitsInOneBit { get; } + protected abstract decimal PetabytesInOneBit { get; } + protected abstract decimal TebibitsInOneBit { get; } + protected abstract decimal TebibytesInOneBit { get; } + protected abstract decimal TerabitsInOneBit { get; } + protected abstract decimal TerabytesInOneBit { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BitsTolerance { get { return 1e-5; } } - protected virtual double BytesTolerance { get { return 1e-5; } } - protected virtual double ExabitsTolerance { get { return 1e-5; } } - protected virtual double ExabytesTolerance { get { return 1e-5; } } - protected virtual double ExbibitsTolerance { get { return 1e-5; } } - protected virtual double ExbibytesTolerance { get { return 1e-5; } } - protected virtual double GibibitsTolerance { get { return 1e-5; } } - protected virtual double GibibytesTolerance { get { return 1e-5; } } - protected virtual double GigabitsTolerance { get { return 1e-5; } } - protected virtual double GigabytesTolerance { get { return 1e-5; } } - protected virtual double KibibitsTolerance { get { return 1e-5; } } - protected virtual double KibibytesTolerance { get { return 1e-5; } } - protected virtual double KilobitsTolerance { get { return 1e-5; } } - protected virtual double KilobytesTolerance { get { return 1e-5; } } - protected virtual double MebibitsTolerance { get { return 1e-5; } } - protected virtual double MebibytesTolerance { get { return 1e-5; } } - protected virtual double MegabitsTolerance { get { return 1e-5; } } - protected virtual double MegabytesTolerance { get { return 1e-5; } } - protected virtual double PebibitsTolerance { get { return 1e-5; } } - protected virtual double PebibytesTolerance { get { return 1e-5; } } - protected virtual double PetabitsTolerance { get { return 1e-5; } } - protected virtual double PetabytesTolerance { get { return 1e-5; } } - protected virtual double TebibitsTolerance { get { return 1e-5; } } - protected virtual double TebibytesTolerance { get { return 1e-5; } } - protected virtual double TerabitsTolerance { get { return 1e-5; } } - protected virtual double TerabytesTolerance { get { return 1e-5; } } + protected virtual decimal BitsTolerance { get { return 1E-9m; } } + protected virtual decimal BytesTolerance { get { return 1E-9m; } } + protected virtual decimal ExabitsTolerance { get { return 1E-9m; } } + protected virtual decimal ExabytesTolerance { get { return 1E-9m; } } + protected virtual decimal ExbibitsTolerance { get { return 1E-9m; } } + protected virtual decimal ExbibytesTolerance { get { return 1E-9m; } } + protected virtual decimal GibibitsTolerance { get { return 1E-9m; } } + protected virtual decimal GibibytesTolerance { get { return 1E-9m; } } + protected virtual decimal GigabitsTolerance { get { return 1E-9m; } } + protected virtual decimal GigabytesTolerance { get { return 1E-9m; } } + protected virtual decimal KibibitsTolerance { get { return 1E-9m; } } + protected virtual decimal KibibytesTolerance { get { return 1E-9m; } } + protected virtual decimal KilobitsTolerance { get { return 1E-9m; } } + protected virtual decimal KilobytesTolerance { get { return 1E-9m; } } + protected virtual decimal MebibitsTolerance { get { return 1E-9m; } } + protected virtual decimal MebibytesTolerance { get { return 1E-9m; } } + protected virtual decimal MegabitsTolerance { get { return 1E-9m; } } + protected virtual decimal MegabytesTolerance { get { return 1E-9m; } } + protected virtual decimal PebibitsTolerance { get { return 1E-9m; } } + protected virtual decimal PebibytesTolerance { get { return 1E-9m; } } + protected virtual decimal PetabitsTolerance { get { return 1E-9m; } } + protected virtual decimal PetabytesTolerance { get { return 1E-9m; } } + protected virtual decimal TebibitsTolerance { get { return 1E-9m; } } + protected virtual decimal TebibytesTolerance { get { return 1E-9m; } } + protected virtual decimal TerabitsTolerance { get { return 1E-9m; } } + protected virtual decimal TerabytesTolerance { get { return 1E-9m; } } // ReSharper restore VirtualMemberNeverOverriden.Global - protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(InformationUnit unit) + protected (decimal UnitsInBaseUnit, decimal Tolerence) GetConversionFactor(InformationUnit unit) { return unit switch { @@ -383,7 +383,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -754,14 +754,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(InformationUnit unit) { - var inBaseUnits = Information.From(1.0, Information.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Information.From(1.0, Information.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Information.From(1.0, Information.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(InformationUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(InformationUnit unit) @@ -775,8 +782,8 @@ public void ToUnit_WithSameUnits_AreEqual(InformationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(InformationUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Information.Units.Where(u => u != Information.BaseUnit).DefaultIfEmpty(Information.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Information.Units.First(u => u != Information.BaseUnit); var quantity = Information.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1046,8 +1053,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Information.FromBits(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Information.FromBits(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1081,36 +1089,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Information.FromBits(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Information.FromBits(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Information.FromBits(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Information.FromBits(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Information.FromBits(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Information.FromBits(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Information.FromBits(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Information.FromBits(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Information.FromBits(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Information.FromBits(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1123,22 +1136,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Information.FromBits(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Information.FromBits(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Information.FromBits(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Information.FromBits(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Information.FromBits(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Information.FromBits(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1180,7 +1196,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Information.FromBits(1.0); - Assert.Equal(new {Information.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Information.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs index c0d10394f7..48f79afd6c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs @@ -54,20 +54,20 @@ public abstract partial class IrradianceTestsBase : QuantityTestsBase protected abstract double WattsPerSquareMeterInOneWattPerSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilowattsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareMeterTolerance { get { return 1e-5; } } + protected virtual double KilowattsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double MicrowattsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double MicrowattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double NanowattsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double NanowattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double PicowattsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double PicowattsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double WattsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double WattsPerSquareMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(IrradianceUnit unit) @@ -288,7 +288,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -613,14 +613,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(IrradianceUnit unit) { - var inBaseUnits = Irradiance.From(1.0, Irradiance.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Irradiance.From(1.0, Irradiance.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Irradiance.From(1.0, Irradiance.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(IrradianceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(IrradianceUnit unit) @@ -634,8 +641,8 @@ public void ToUnit_WithSameUnits_AreEqual(IrradianceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IrradianceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Irradiance.Units.Where(u => u != Irradiance.BaseUnit).DefaultIfEmpty(Irradiance.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Irradiance.Units.First(u => u != Irradiance.BaseUnit); var quantity = Irradiance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -869,8 +876,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Irradiance.FromWattsPerSquareMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -904,36 +912,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Irradiance.FromWattsPerSquareMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Irradiance.FromWattsPerSquareMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Irradiance.FromWattsPerSquareMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Irradiance.FromWattsPerSquareMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Irradiance.FromWattsPerSquareMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -946,22 +959,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Irradiance.FromWattsPerSquareMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Irradiance.FromWattsPerSquareMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Irradiance.FromWattsPerSquareMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1003,7 +1019,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(new {Irradiance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Irradiance.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs index db173e10e8..63fe8c16a7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs @@ -47,13 +47,13 @@ public abstract partial class IrradiationTestsBase : QuantityTestsBase protected abstract double WattHoursPerSquareMeterInOneJoulePerSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double JoulesPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double JoulesPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double JoulesPerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilowattHoursPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MillijoulesPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double WattHoursPerSquareMeterTolerance { get { return 1e-5; } } + protected virtual double JoulesPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double JoulesPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double JoulesPerSquareMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double KilowattHoursPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double MillijoulesPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double WattHoursPerSquareMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(IrradiationUnit unit) @@ -218,7 +218,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -419,14 +419,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(IrradiationUnit unit) { - var inBaseUnits = Irradiation.From(1.0, Irradiation.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Irradiation.From(1.0, Irradiation.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Irradiation.From(1.0, Irradiation.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(IrradiationUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(IrradiationUnit unit) @@ -440,8 +447,8 @@ public void ToUnit_WithSameUnits_AreEqual(IrradiationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IrradiationUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Irradiation.Units.Where(u => u != Irradiation.BaseUnit).DefaultIfEmpty(Irradiation.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Irradiation.Units.First(u => u != Irradiation.BaseUnit); var quantity = Irradiation.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -654,8 +661,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Irradiation.FromJoulesPerSquareMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -689,36 +697,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Irradiation.FromJoulesPerSquareMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Irradiation.FromJoulesPerSquareMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Irradiation.FromJoulesPerSquareMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Irradiation.FromJoulesPerSquareMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Irradiation.FromJoulesPerSquareMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -731,22 +744,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Irradiation.FromJoulesPerSquareMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Irradiation.FromJoulesPerSquareMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Irradiation.FromJoulesPerSquareMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -788,7 +804,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(new {Irradiation.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Irradiation.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs index 4b8961c1d7..d1d835449e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs @@ -51,17 +51,17 @@ public abstract partial class JerkTestsBase : QuantityTestsBase protected abstract double StandardGravitiesPerSecondInOneMeterPerSecondCubed { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimetersPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double DecimetersPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double FeetPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double InchesPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double KilometersPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double MetersPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double MicrometersPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double MillimetersPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double MillistandardGravitiesPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanometersPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double StandardGravitiesPerSecondTolerance { get { return 1e-5; } } + protected virtual double CentimetersPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double DecimetersPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double FeetPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double InchesPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double KilometersPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double MetersPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double MicrometersPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double MillimetersPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double MillistandardGravitiesPerSecondTolerance { get { return 1E-5; } } + protected virtual double NanometersPerSecondCubedTolerance { get { return 1E-5; } } + protected virtual double StandardGravitiesPerSecondTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(JerkUnit unit) @@ -258,7 +258,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -819,14 +819,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(JerkUnit unit) { - var inBaseUnits = Jerk.From(1.0, Jerk.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Jerk.From(1.0, Jerk.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Jerk.From(1.0, Jerk.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(JerkUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(JerkUnit unit) @@ -840,8 +847,8 @@ public void ToUnit_WithSameUnits_AreEqual(JerkUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(JerkUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Jerk.Units.Where(u => u != Jerk.BaseUnit).DefaultIfEmpty(Jerk.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Jerk.Units.First(u => u != Jerk.BaseUnit); var quantity = Jerk.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1066,8 +1073,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Jerk.FromMetersPerSecondCubed(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1101,36 +1109,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Jerk.FromMetersPerSecondCubed(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Jerk.FromMetersPerSecondCubed(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Jerk.FromMetersPerSecondCubed(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Jerk.FromMetersPerSecondCubed(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Jerk.FromMetersPerSecondCubed(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1143,22 +1156,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Jerk.FromMetersPerSecondCubed(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Jerk.FromMetersPerSecondCubed(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Jerk.FromMetersPerSecondCubed(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1200,7 +1216,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(new {Jerk.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Jerk.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs index aad81609de..113c50e125 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs @@ -49,15 +49,15 @@ public abstract partial class KinematicViscosityTestsBase : QuantityTestsBase protected abstract double StokesInOneSquareMeterPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentistokesTolerance { get { return 1e-5; } } - protected virtual double DecistokesTolerance { get { return 1e-5; } } - protected virtual double KilostokesTolerance { get { return 1e-5; } } - protected virtual double MicrostokesTolerance { get { return 1e-5; } } - protected virtual double MillistokesTolerance { get { return 1e-5; } } - protected virtual double NanostokesTolerance { get { return 1e-5; } } - protected virtual double SquareFeetPerSecondTolerance { get { return 1e-5; } } - protected virtual double SquareMetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double StokesTolerance { get { return 1e-5; } } + protected virtual double CentistokesTolerance { get { return 1E-5; } } + protected virtual double DecistokesTolerance { get { return 1E-5; } } + protected virtual double KilostokesTolerance { get { return 1E-5; } } + protected virtual double MicrostokesTolerance { get { return 1E-5; } } + protected virtual double MillistokesTolerance { get { return 1E-5; } } + protected virtual double NanostokesTolerance { get { return 1E-5; } } + protected virtual double SquareFeetPerSecondTolerance { get { return 1E-5; } } + protected virtual double SquareMetersPerSecondTolerance { get { return 1E-5; } } + protected virtual double StokesTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(KinematicViscosityUnit unit) @@ -238,7 +238,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -679,14 +679,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(KinematicViscosityUnit unit) { - var inBaseUnits = KinematicViscosity.From(1.0, KinematicViscosity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = KinematicViscosity.From(1.0, KinematicViscosity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = KinematicViscosity.From(1.0, KinematicViscosity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(KinematicViscosityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(KinematicViscosityUnit unit) @@ -700,8 +707,8 @@ public void ToUnit_WithSameUnits_AreEqual(KinematicViscosityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(KinematicViscosityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = KinematicViscosity.Units.Where(u => u != KinematicViscosity.BaseUnit).DefaultIfEmpty(KinematicViscosity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = KinematicViscosity.Units.First(u => u != KinematicViscosity.BaseUnit); var quantity = KinematicViscosity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -920,8 +927,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = KinematicViscosity.FromSquareMetersPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -955,36 +963,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = KinematicViscosity.FromSquareMetersPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = KinematicViscosity.FromSquareMetersPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = KinematicViscosity.FromSquareMetersPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = KinematicViscosity.FromSquareMetersPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = KinematicViscosity.FromSquareMetersPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -997,22 +1010,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = KinematicViscosity.FromSquareMetersPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = KinematicViscosity.FromSquareMetersPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = KinematicViscosity.FromSquareMetersPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1054,7 +1070,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(new {KinematicViscosity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(KinematicViscosity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs index 840ff97042..6402bac337 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class LapseRateTestsBase : QuantityTestsBase protected abstract double DegreesCelciusPerKilometerInOneDegreeCelsiusPerKilometer { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DegreesCelciusPerKilometerTolerance { get { return 1e-5; } } + protected virtual double DegreesCelciusPerKilometerTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LapseRateUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(LapseRateUnit unit) { - var inBaseUnits = LapseRate.From(1.0, LapseRate.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = LapseRate.From(1.0, LapseRate.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = LapseRate.From(1.0, LapseRate.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(LapseRateUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(LapseRateUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(LapseRateUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LapseRateUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = LapseRate.Units.Where(u => u != LapseRate.BaseUnit).DefaultIfEmpty(LapseRate.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = LapseRate.Units.First(u => u != LapseRate.BaseUnit); var quantity = LapseRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = LapseRate.FromDegreesCelciusPerKilometer(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = LapseRate.FromDegreesCelciusPerKilometer(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = LapseRate.FromDegreesCelciusPerKilometer(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = LapseRate.FromDegreesCelciusPerKilometer(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = LapseRate.FromDegreesCelciusPerKilometer(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = LapseRate.FromDegreesCelciusPerKilometer(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = LapseRate.FromDegreesCelciusPerKilometer(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = LapseRate.FromDegreesCelciusPerKilometer(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = LapseRate.FromDegreesCelciusPerKilometer(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal(new {LapseRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(LapseRate.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs index b063af3c1d..cd116fb5be 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs @@ -76,42 +76,42 @@ public abstract partial class LengthTestsBase : QuantityTestsBase protected abstract double YardsInOneMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AngstromsTolerance { get { return 1e-5; } } - protected virtual double AstronomicalUnitsTolerance { get { return 1e-5; } } - protected virtual double CentimetersTolerance { get { return 1e-5; } } - protected virtual double ChainsTolerance { get { return 1e-5; } } - protected virtual double DataMilesTolerance { get { return 1e-5; } } - protected virtual double DecametersTolerance { get { return 1e-5; } } - protected virtual double DecimetersTolerance { get { return 1e-5; } } - protected virtual double DtpPicasTolerance { get { return 1e-5; } } - protected virtual double DtpPointsTolerance { get { return 1e-5; } } - protected virtual double FathomsTolerance { get { return 1e-5; } } - protected virtual double FeetTolerance { get { return 1e-5; } } - protected virtual double HandsTolerance { get { return 1e-5; } } - protected virtual double HectometersTolerance { get { return 1e-5; } } - protected virtual double InchesTolerance { get { return 1e-5; } } - protected virtual double KilolightYearsTolerance { get { return 1e-5; } } - protected virtual double KilometersTolerance { get { return 1e-5; } } - protected virtual double KiloparsecsTolerance { get { return 1e-5; } } - protected virtual double LightYearsTolerance { get { return 1e-5; } } - protected virtual double MegalightYearsTolerance { get { return 1e-5; } } - protected virtual double MegaparsecsTolerance { get { return 1e-5; } } - protected virtual double MetersTolerance { get { return 1e-5; } } - protected virtual double MicroinchesTolerance { get { return 1e-5; } } - protected virtual double MicrometersTolerance { get { return 1e-5; } } - protected virtual double MilsTolerance { get { return 1e-5; } } - protected virtual double MilesTolerance { get { return 1e-5; } } - protected virtual double MillimetersTolerance { get { return 1e-5; } } - protected virtual double NanometersTolerance { get { return 1e-5; } } - protected virtual double NauticalMilesTolerance { get { return 1e-5; } } - protected virtual double ParsecsTolerance { get { return 1e-5; } } - protected virtual double PrinterPicasTolerance { get { return 1e-5; } } - protected virtual double PrinterPointsTolerance { get { return 1e-5; } } - protected virtual double ShacklesTolerance { get { return 1e-5; } } - protected virtual double SolarRadiusesTolerance { get { return 1e-5; } } - protected virtual double TwipsTolerance { get { return 1e-5; } } - protected virtual double UsSurveyFeetTolerance { get { return 1e-5; } } - protected virtual double YardsTolerance { get { return 1e-5; } } + protected virtual double AngstromsTolerance { get { return 1E-5; } } + protected virtual double AstronomicalUnitsTolerance { get { return 1E-5; } } + protected virtual double CentimetersTolerance { get { return 1E-5; } } + protected virtual double ChainsTolerance { get { return 1E-5; } } + protected virtual double DataMilesTolerance { get { return 1E-5; } } + protected virtual double DecametersTolerance { get { return 1E-5; } } + protected virtual double DecimetersTolerance { get { return 1E-5; } } + protected virtual double DtpPicasTolerance { get { return 1E-5; } } + protected virtual double DtpPointsTolerance { get { return 1E-5; } } + protected virtual double FathomsTolerance { get { return 1E-5; } } + protected virtual double FeetTolerance { get { return 1E-5; } } + protected virtual double HandsTolerance { get { return 1E-5; } } + protected virtual double HectometersTolerance { get { return 1E-5; } } + protected virtual double InchesTolerance { get { return 1E-5; } } + protected virtual double KilolightYearsTolerance { get { return 1E-5; } } + protected virtual double KilometersTolerance { get { return 1E-5; } } + protected virtual double KiloparsecsTolerance { get { return 1E-5; } } + protected virtual double LightYearsTolerance { get { return 1E-5; } } + protected virtual double MegalightYearsTolerance { get { return 1E-5; } } + protected virtual double MegaparsecsTolerance { get { return 1E-5; } } + protected virtual double MetersTolerance { get { return 1E-5; } } + protected virtual double MicroinchesTolerance { get { return 1E-5; } } + protected virtual double MicrometersTolerance { get { return 1E-5; } } + protected virtual double MilsTolerance { get { return 1E-5; } } + protected virtual double MilesTolerance { get { return 1E-5; } } + protected virtual double MillimetersTolerance { get { return 1E-5; } } + protected virtual double NanometersTolerance { get { return 1E-5; } } + protected virtual double NauticalMilesTolerance { get { return 1E-5; } } + protected virtual double ParsecsTolerance { get { return 1E-5; } } + protected virtual double PrinterPicasTolerance { get { return 1E-5; } } + protected virtual double PrinterPointsTolerance { get { return 1E-5; } } + protected virtual double ShacklesTolerance { get { return 1E-5; } } + protected virtual double SolarRadiusesTolerance { get { return 1E-5; } } + protected virtual double TwipsTolerance { get { return 1E-5; } } + protected virtual double UsSurveyFeetTolerance { get { return 1E-5; } } + protected virtual double YardsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LengthUnit unit) @@ -508,7 +508,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -2209,14 +2209,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(LengthUnit unit) { - var inBaseUnits = Length.From(1.0, Length.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Length.From(1.0, Length.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Length.From(1.0, Length.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(LengthUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(LengthUnit unit) @@ -2230,8 +2237,8 @@ public void ToUnit_WithSameUnits_AreEqual(LengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LengthUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Length.Units.Where(u => u != Length.BaseUnit).DefaultIfEmpty(Length.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Length.Units.First(u => u != Length.BaseUnit); var quantity = Length.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2531,8 +2538,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Length.FromMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Length.FromMeters(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -2566,36 +2574,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Length.FromMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Length.FromMeters(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Length.FromMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Length.FromMeters(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Length.FromMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Length.FromMeters(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Length.FromMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Length.FromMeters(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Length.FromMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Length.FromMeters(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -2608,22 +2621,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Length.FromMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Length.FromMeters(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Length.FromMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Length.FromMeters(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Length.FromMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Length.FromMeters(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -2665,7 +2681,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Length.FromMeters(1.0); - Assert.Equal(new {Length.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Length.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs index aa977dc3e4..db6fd2269e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs @@ -42,8 +42,8 @@ public abstract partial class LevelTestsBase : QuantityTestsBase protected abstract double NepersInOneDecibel { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecibelsTolerance { get { return 1e-5; } } - protected virtual double NepersTolerance { get { return 1e-5; } } + protected virtual double DecibelsTolerance { get { return 1E-5; } } + protected virtual double NepersTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LevelUnit unit) @@ -168,7 +168,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -249,14 +249,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(LevelUnit unit) { - var inBaseUnits = Level.From(1.0, Level.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Level.From(1.0, Level.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Level.From(1.0, Level.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(LevelUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(LevelUnit unit) @@ -270,8 +277,8 @@ public void ToUnit_WithSameUnits_AreEqual(LevelUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LevelUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Level.Units.Where(u => u != Level.BaseUnit).DefaultIfEmpty(Level.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Level.Units.First(u => u != Level.BaseUnit); var quantity = Level.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -473,8 +480,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Level.FromDecibels(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -508,36 +516,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Level.FromDecibels(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Level.FromDecibels(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Level.FromDecibels(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Level.FromDecibels(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Level.FromDecibels(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -550,22 +563,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Level.FromDecibels(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Level.FromDecibels(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Level.FromDecibels(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -607,7 +623,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Level.FromDecibels(1.0); - Assert.Equal(new {Level.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Level.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs index da6d13e43c..dc31e147c1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs @@ -54,20 +54,20 @@ public abstract partial class LinearDensityTestsBase : QuantityTestsBase protected abstract double PoundsPerInchInOneKilogramPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerMeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double PoundsPerFootTolerance { get { return 1e-5; } } - protected virtual double PoundsPerInchTolerance { get { return 1e-5; } } + protected virtual double GramsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerMeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerMeterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerMeterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double PoundsPerFootTolerance { get { return 1E-5; } } + protected virtual double PoundsPerInchTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LinearDensityUnit unit) @@ -288,7 +288,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -657,14 +657,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(LinearDensityUnit unit) { - var inBaseUnits = LinearDensity.From(1.0, LinearDensity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = LinearDensity.From(1.0, LinearDensity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = LinearDensity.From(1.0, LinearDensity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(LinearDensityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(LinearDensityUnit unit) @@ -678,8 +685,8 @@ public void ToUnit_WithSameUnits_AreEqual(LinearDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LinearDensityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = LinearDensity.Units.Where(u => u != LinearDensity.BaseUnit).DefaultIfEmpty(LinearDensity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = LinearDensity.Units.First(u => u != LinearDensity.BaseUnit); var quantity = LinearDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -913,8 +920,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = LinearDensity.FromKilogramsPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -948,36 +956,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = LinearDensity.FromKilogramsPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = LinearDensity.FromKilogramsPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = LinearDensity.FromKilogramsPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = LinearDensity.FromKilogramsPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = LinearDensity.FromKilogramsPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -990,22 +1003,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = LinearDensity.FromKilogramsPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = LinearDensity.FromKilogramsPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = LinearDensity.FromKilogramsPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1047,7 +1063,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(new {LinearDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(LinearDensity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs index 89f251de69..457cb71019 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs @@ -65,31 +65,31 @@ public abstract partial class LinearPowerDensityTestsBase : QuantityTestsBase protected abstract double WattsPerMillimeterInOneWattPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GigawattsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerFootTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerInchTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerMeterTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerFootTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerInchTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerFootTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerInchTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerFootTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerInchTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double WattsPerCentimeterTolerance { get { return 1e-5; } } - protected virtual double WattsPerFootTolerance { get { return 1e-5; } } - protected virtual double WattsPerInchTolerance { get { return 1e-5; } } - protected virtual double WattsPerMeterTolerance { get { return 1e-5; } } - protected virtual double WattsPerMillimeterTolerance { get { return 1e-5; } } + protected virtual double GigawattsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double GigawattsPerFootTolerance { get { return 1E-5; } } + protected virtual double GigawattsPerInchTolerance { get { return 1E-5; } } + protected virtual double GigawattsPerMeterTolerance { get { return 1E-5; } } + protected virtual double GigawattsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerFootTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerInchTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerFootTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerInchTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerMeterTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerFootTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerInchTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerMeterTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double WattsPerCentimeterTolerance { get { return 1E-5; } } + protected virtual double WattsPerFootTolerance { get { return 1E-5; } } + protected virtual double WattsPerInchTolerance { get { return 1E-5; } } + protected virtual double WattsPerMeterTolerance { get { return 1E-5; } } + protected virtual double WattsPerMillimeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LinearPowerDensityUnit unit) @@ -398,7 +398,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -921,14 +921,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(LinearPowerDensityUnit unit) { - var inBaseUnits = LinearPowerDensity.From(1.0, LinearPowerDensity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = LinearPowerDensity.From(1.0, LinearPowerDensity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = LinearPowerDensity.From(1.0, LinearPowerDensity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(LinearPowerDensityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(LinearPowerDensityUnit unit) @@ -942,8 +949,8 @@ public void ToUnit_WithSameUnits_AreEqual(LinearPowerDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LinearPowerDensityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = LinearPowerDensity.Units.Where(u => u != LinearPowerDensity.BaseUnit).DefaultIfEmpty(LinearPowerDensity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = LinearPowerDensity.Units.First(u => u != LinearPowerDensity.BaseUnit); var quantity = LinearPowerDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1210,8 +1217,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = LinearPowerDensity.FromWattsPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1245,36 +1253,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = LinearPowerDensity.FromWattsPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = LinearPowerDensity.FromWattsPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = LinearPowerDensity.FromWattsPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = LinearPowerDensity.FromWattsPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = LinearPowerDensity.FromWattsPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1287,22 +1300,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = LinearPowerDensity.FromWattsPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = LinearPowerDensity.FromWattsPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = LinearPowerDensity.FromWattsPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1344,7 +1360,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(new {LinearPowerDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(LinearPowerDensity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs index 007e99449e..8849176e7d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs @@ -54,20 +54,20 @@ public abstract partial class LuminosityTestsBase : QuantityTestsBase protected abstract double WattsInOneWatt { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecawattsTolerance { get { return 1e-5; } } - protected virtual double DeciwattsTolerance { get { return 1e-5; } } - protected virtual double FemtowattsTolerance { get { return 1e-5; } } - protected virtual double GigawattsTolerance { get { return 1e-5; } } - protected virtual double KilowattsTolerance { get { return 1e-5; } } - protected virtual double MegawattsTolerance { get { return 1e-5; } } - protected virtual double MicrowattsTolerance { get { return 1e-5; } } - protected virtual double MilliwattsTolerance { get { return 1e-5; } } - protected virtual double NanowattsTolerance { get { return 1e-5; } } - protected virtual double PetawattsTolerance { get { return 1e-5; } } - protected virtual double PicowattsTolerance { get { return 1e-5; } } - protected virtual double SolarLuminositiesTolerance { get { return 1e-5; } } - protected virtual double TerawattsTolerance { get { return 1e-5; } } - protected virtual double WattsTolerance { get { return 1e-5; } } + protected virtual double DecawattsTolerance { get { return 1E-5; } } + protected virtual double DeciwattsTolerance { get { return 1E-5; } } + protected virtual double FemtowattsTolerance { get { return 1E-5; } } + protected virtual double GigawattsTolerance { get { return 1E-5; } } + protected virtual double KilowattsTolerance { get { return 1E-5; } } + protected virtual double MegawattsTolerance { get { return 1E-5; } } + protected virtual double MicrowattsTolerance { get { return 1E-5; } } + protected virtual double MilliwattsTolerance { get { return 1E-5; } } + protected virtual double NanowattsTolerance { get { return 1E-5; } } + protected virtual double PetawattsTolerance { get { return 1E-5; } } + protected virtual double PicowattsTolerance { get { return 1E-5; } } + protected virtual double SolarLuminositiesTolerance { get { return 1E-5; } } + protected virtual double TerawattsTolerance { get { return 1E-5; } } + protected virtual double WattsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LuminosityUnit unit) @@ -288,7 +288,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -613,14 +613,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(LuminosityUnit unit) { - var inBaseUnits = Luminosity.From(1.0, Luminosity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Luminosity.From(1.0, Luminosity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Luminosity.From(1.0, Luminosity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(LuminosityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(LuminosityUnit unit) @@ -634,8 +641,8 @@ public void ToUnit_WithSameUnits_AreEqual(LuminosityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminosityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Luminosity.Units.Where(u => u != Luminosity.BaseUnit).DefaultIfEmpty(Luminosity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Luminosity.Units.First(u => u != Luminosity.BaseUnit); var quantity = Luminosity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -869,8 +876,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Luminosity.FromWatts(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -904,36 +912,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Luminosity.FromWatts(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Luminosity.FromWatts(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Luminosity.FromWatts(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Luminosity.FromWatts(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Luminosity.FromWatts(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -946,22 +959,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Luminosity.FromWatts(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Luminosity.FromWatts(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Luminosity.FromWatts(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1003,7 +1019,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(new {Luminosity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Luminosity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs index dcb107c35f..ad27f5af83 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class LuminousFluxTestsBase : QuantityTestsBase protected abstract double LumensInOneLumen { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double LumensTolerance { get { return 1e-5; } } + protected virtual double LumensTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LuminousFluxUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(LuminousFluxUnit unit) { - var inBaseUnits = LuminousFlux.From(1.0, LuminousFlux.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = LuminousFlux.From(1.0, LuminousFlux.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = LuminousFlux.From(1.0, LuminousFlux.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(LuminousFluxUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(LuminousFluxUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(LuminousFluxUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminousFluxUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = LuminousFlux.Units.Where(u => u != LuminousFlux.BaseUnit).DefaultIfEmpty(LuminousFlux.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = LuminousFlux.Units.First(u => u != LuminousFlux.BaseUnit); var quantity = LuminousFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = LuminousFlux.FromLumens(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = LuminousFlux.FromLumens(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = LuminousFlux.FromLumens(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = LuminousFlux.FromLumens(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = LuminousFlux.FromLumens(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = LuminousFlux.FromLumens(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = LuminousFlux.FromLumens(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = LuminousFlux.FromLumens(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = LuminousFlux.FromLumens(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(new {LuminousFlux.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(LuminousFlux.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs index fcd3954377..04ec63b13a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class LuminousIntensityTestsBase : QuantityTestsBase protected abstract double CandelaInOneCandela { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CandelaTolerance { get { return 1e-5; } } + protected virtual double CandelaTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(LuminousIntensityUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(LuminousIntensityUnit unit) { - var inBaseUnits = LuminousIntensity.From(1.0, LuminousIntensity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = LuminousIntensity.From(1.0, LuminousIntensity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = LuminousIntensity.From(1.0, LuminousIntensity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(LuminousIntensityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(LuminousIntensityUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(LuminousIntensityUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminousIntensityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = LuminousIntensity.Units.Where(u => u != LuminousIntensity.BaseUnit).DefaultIfEmpty(LuminousIntensity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = LuminousIntensity.Units.First(u => u != LuminousIntensity.BaseUnit); var quantity = LuminousIntensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = LuminousIntensity.FromCandela(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = LuminousIntensity.FromCandela(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = LuminousIntensity.FromCandela(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = LuminousIntensity.FromCandela(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = LuminousIntensity.FromCandela(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = LuminousIntensity.FromCandela(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = LuminousIntensity.FromCandela(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = LuminousIntensity.FromCandela(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = LuminousIntensity.FromCandela(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(new {LuminousIntensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(LuminousIntensity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs index 174b05b5bc..f0e1ec76db 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs @@ -46,12 +46,12 @@ public abstract partial class MagneticFieldTestsBase : QuantityTestsBase protected abstract double TeslasInOneTesla { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GaussesTolerance { get { return 1e-5; } } - protected virtual double MicroteslasTolerance { get { return 1e-5; } } - protected virtual double MilligaussesTolerance { get { return 1e-5; } } - protected virtual double MilliteslasTolerance { get { return 1e-5; } } - protected virtual double NanoteslasTolerance { get { return 1e-5; } } - protected virtual double TeslasTolerance { get { return 1e-5; } } + protected virtual double GaussesTolerance { get { return 1E-5; } } + protected virtual double MicroteslasTolerance { get { return 1E-5; } } + protected virtual double MilligaussesTolerance { get { return 1E-5; } } + protected virtual double MilliteslasTolerance { get { return 1E-5; } } + protected virtual double NanoteslasTolerance { get { return 1E-5; } } + protected virtual double TeslasTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MagneticFieldUnit unit) @@ -208,7 +208,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -385,14 +385,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MagneticFieldUnit unit) { - var inBaseUnits = MagneticField.From(1.0, MagneticField.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MagneticField.From(1.0, MagneticField.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MagneticField.From(1.0, MagneticField.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MagneticFieldUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MagneticFieldUnit unit) @@ -406,8 +413,8 @@ public void ToUnit_WithSameUnits_AreEqual(MagneticFieldUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagneticFieldUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MagneticField.Units.Where(u => u != MagneticField.BaseUnit).DefaultIfEmpty(MagneticField.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MagneticField.Units.First(u => u != MagneticField.BaseUnit); var quantity = MagneticField.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -617,8 +624,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MagneticField.FromTeslas(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -652,36 +660,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MagneticField.FromTeslas(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MagneticField.FromTeslas(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MagneticField.FromTeslas(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MagneticField.FromTeslas(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MagneticField.FromTeslas(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -694,22 +707,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MagneticField.FromTeslas(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MagneticField.FromTeslas(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MagneticField.FromTeslas(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -751,7 +767,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(new {MagneticField.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MagneticField.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs index acee8f296b..d76291cc93 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class MagneticFluxTestsBase : QuantityTestsBase protected abstract double WebersInOneWeber { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double WebersTolerance { get { return 1e-5; } } + protected virtual double WebersTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MagneticFluxUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MagneticFluxUnit unit) { - var inBaseUnits = MagneticFlux.From(1.0, MagneticFlux.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MagneticFlux.From(1.0, MagneticFlux.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MagneticFlux.From(1.0, MagneticFlux.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MagneticFluxUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MagneticFluxUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(MagneticFluxUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagneticFluxUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MagneticFlux.Units.Where(u => u != MagneticFlux.BaseUnit).DefaultIfEmpty(MagneticFlux.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MagneticFlux.Units.First(u => u != MagneticFlux.BaseUnit); var quantity = MagneticFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MagneticFlux.FromWebers(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MagneticFlux.FromWebers(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MagneticFlux.FromWebers(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MagneticFlux.FromWebers(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MagneticFlux.FromWebers(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MagneticFlux.FromWebers(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MagneticFlux.FromWebers(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MagneticFlux.FromWebers(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MagneticFlux.FromWebers(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(new {MagneticFlux.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MagneticFlux.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs index b6e2f93739..ea30c1f26e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class MagnetizationTestsBase : QuantityTestsBase protected abstract double AmperesPerMeterInOneAmperePerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmperesPerMeterTolerance { get { return 1e-5; } } + protected virtual double AmperesPerMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MagnetizationUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MagnetizationUnit unit) { - var inBaseUnits = Magnetization.From(1.0, Magnetization.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Magnetization.From(1.0, Magnetization.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Magnetization.From(1.0, Magnetization.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MagnetizationUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MagnetizationUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(MagnetizationUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagnetizationUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Magnetization.Units.Where(u => u != Magnetization.BaseUnit).DefaultIfEmpty(Magnetization.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Magnetization.Units.First(u => u != Magnetization.BaseUnit); var quantity = Magnetization.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Magnetization.FromAmperesPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Magnetization.FromAmperesPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Magnetization.FromAmperesPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Magnetization.FromAmperesPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Magnetization.FromAmperesPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Magnetization.FromAmperesPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Magnetization.FromAmperesPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Magnetization.FromAmperesPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Magnetization.FromAmperesPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(new {Magnetization.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Magnetization.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs index 4f1778b29c..9fceb48029 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs @@ -89,55 +89,55 @@ public abstract partial class MassConcentrationTestsBase : QuantityTestsBase protected abstract double TonnesPerCubicMillimeterInOneKilogramPerCubicMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentigramsPerDeciliterTolerance { get { return 1e-5; } } - protected virtual double CentigramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double CentigramsPerMicroliterTolerance { get { return 1e-5; } } - protected virtual double CentigramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerDeciliterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerMicroliterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerDeciliterTolerance { get { return 1e-5; } } - protected virtual double GramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double GramsPerMicroliterTolerance { get { return 1e-5; } } - protected virtual double GramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double KilopoundsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double KilopoundsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerDeciliterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerMicroliterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerDeciliterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerMicroliterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerDeciliterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerMicroliterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double OuncesPerImperialGallonTolerance { get { return 1e-5; } } - protected virtual double OuncesPerUSGallonTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerDeciliterTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerMicroliterTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double PoundsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double PoundsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double PoundsPerImperialGallonTolerance { get { return 1e-5; } } - protected virtual double PoundsPerUSGallonTolerance { get { return 1e-5; } } - protected virtual double SlugsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicMillimeterTolerance { get { return 1e-5; } } + protected virtual double CentigramsPerDeciliterTolerance { get { return 1E-5; } } + protected virtual double CentigramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double CentigramsPerMicroliterTolerance { get { return 1E-5; } } + protected virtual double CentigramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerDeciliterTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerMicroliterTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double GramsPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerCubicMillimeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerDeciliterTolerance { get { return 1E-5; } } + protected virtual double GramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double GramsPerMicroliterTolerance { get { return 1E-5; } } + protected virtual double GramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerCubicMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double KilopoundsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double KilopoundsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerDeciliterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerMicroliterTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerDeciliterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerMicroliterTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerDeciliterTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerMicroliterTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double OuncesPerImperialGallonTolerance { get { return 1E-5; } } + protected virtual double OuncesPerUSGallonTolerance { get { return 1E-5; } } + protected virtual double PicogramsPerDeciliterTolerance { get { return 1E-5; } } + protected virtual double PicogramsPerLiterTolerance { get { return 1E-5; } } + protected virtual double PicogramsPerMicroliterTolerance { get { return 1E-5; } } + protected virtual double PicogramsPerMilliliterTolerance { get { return 1E-5; } } + protected virtual double PoundsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double PoundsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double PoundsPerImperialGallonTolerance { get { return 1E-5; } } + protected virtual double PoundsPerUSGallonTolerance { get { return 1E-5; } } + protected virtual double SlugsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double TonnesPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double TonnesPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double TonnesPerCubicMillimeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassConcentrationUnit unit) @@ -638,7 +638,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1943,14 +1943,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MassConcentrationUnit unit) { - var inBaseUnits = MassConcentration.From(1.0, MassConcentration.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MassConcentration.From(1.0, MassConcentration.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MassConcentration.From(1.0, MassConcentration.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MassConcentrationUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MassConcentrationUnit unit) @@ -1964,8 +1971,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassConcentrationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassConcentrationUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MassConcentration.Units.Where(u => u != MassConcentration.BaseUnit).DefaultIfEmpty(MassConcentration.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MassConcentration.Units.First(u => u != MassConcentration.BaseUnit); var quantity = MassConcentration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2304,8 +2311,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MassConcentration.FromKilogramsPerCubicMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -2339,36 +2347,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MassConcentration.FromKilogramsPerCubicMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MassConcentration.FromKilogramsPerCubicMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MassConcentration.FromKilogramsPerCubicMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MassConcentration.FromKilogramsPerCubicMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MassConcentration.FromKilogramsPerCubicMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -2381,22 +2394,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MassConcentration.FromKilogramsPerCubicMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MassConcentration.FromKilogramsPerCubicMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MassConcentration.FromKilogramsPerCubicMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -2438,7 +2454,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(new {MassConcentration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MassConcentration.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs index d4696be3d2..93648bfbf7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs @@ -73,39 +73,39 @@ public abstract partial class MassFlowTestsBase : QuantityTestsBase protected abstract double TonnesPerHourInOneGramPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentigramsPerDayTolerance { get { return 1e-5; } } - protected virtual double CentigramsPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecagramsPerDayTolerance { get { return 1e-5; } } - protected virtual double DecagramsPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerDayTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerSecondTolerance { get { return 1e-5; } } - protected virtual double GramsPerDayTolerance { get { return 1e-5; } } - protected virtual double GramsPerHourTolerance { get { return 1e-5; } } - protected virtual double GramsPerSecondTolerance { get { return 1e-5; } } - protected virtual double HectogramsPerDayTolerance { get { return 1e-5; } } - protected virtual double HectogramsPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerDayTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerHourTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MegagramsPerDayTolerance { get { return 1e-5; } } - protected virtual double MegapoundsPerDayTolerance { get { return 1e-5; } } - protected virtual double MegapoundsPerHourTolerance { get { return 1e-5; } } - protected virtual double MegapoundsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double MegapoundsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerDayTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerDayTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerDayTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerSecondTolerance { get { return 1e-5; } } - protected virtual double PoundsPerDayTolerance { get { return 1e-5; } } - protected virtual double PoundsPerHourTolerance { get { return 1e-5; } } - protected virtual double PoundsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double PoundsPerSecondTolerance { get { return 1e-5; } } - protected virtual double ShortTonsPerHourTolerance { get { return 1e-5; } } - protected virtual double TonnesPerDayTolerance { get { return 1e-5; } } - protected virtual double TonnesPerHourTolerance { get { return 1e-5; } } + protected virtual double CentigramsPerDayTolerance { get { return 1E-5; } } + protected virtual double CentigramsPerSecondTolerance { get { return 1E-5; } } + protected virtual double DecagramsPerDayTolerance { get { return 1E-5; } } + protected virtual double DecagramsPerSecondTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerDayTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerSecondTolerance { get { return 1E-5; } } + protected virtual double GramsPerDayTolerance { get { return 1E-5; } } + protected virtual double GramsPerHourTolerance { get { return 1E-5; } } + protected virtual double GramsPerSecondTolerance { get { return 1E-5; } } + protected virtual double HectogramsPerDayTolerance { get { return 1E-5; } } + protected virtual double HectogramsPerSecondTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerDayTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerHourTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerSecondTolerance { get { return 1E-5; } } + protected virtual double MegagramsPerDayTolerance { get { return 1E-5; } } + protected virtual double MegapoundsPerDayTolerance { get { return 1E-5; } } + protected virtual double MegapoundsPerHourTolerance { get { return 1E-5; } } + protected virtual double MegapoundsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double MegapoundsPerSecondTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerDayTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerSecondTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerDayTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerSecondTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerDayTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerSecondTolerance { get { return 1E-5; } } + protected virtual double PoundsPerDayTolerance { get { return 1E-5; } } + protected virtual double PoundsPerHourTolerance { get { return 1E-5; } } + protected virtual double PoundsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double PoundsPerSecondTolerance { get { return 1E-5; } } + protected virtual double ShortTonsPerHourTolerance { get { return 1E-5; } } + protected virtual double TonnesPerDayTolerance { get { return 1E-5; } } + protected virtual double TonnesPerHourTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassFlowUnit unit) @@ -478,7 +478,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1545,14 +1545,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MassFlowUnit unit) { - var inBaseUnits = MassFlow.From(1.0, MassFlow.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MassFlow.From(1.0, MassFlow.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MassFlow.From(1.0, MassFlow.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MassFlowUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MassFlowUnit unit) @@ -1566,8 +1573,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassFlowUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFlowUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MassFlow.Units.Where(u => u != MassFlow.BaseUnit).DefaultIfEmpty(MassFlow.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MassFlow.Units.First(u => u != MassFlow.BaseUnit); var quantity = MassFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1858,8 +1865,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MassFlow.FromGramsPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1893,36 +1901,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MassFlow.FromGramsPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MassFlow.FromGramsPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MassFlow.FromGramsPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MassFlow.FromGramsPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MassFlow.FromGramsPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1935,22 +1948,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MassFlow.FromGramsPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MassFlow.FromGramsPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MassFlow.FromGramsPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1992,7 +2008,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(new {MassFlow.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MassFlow.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs index 54a6e654cf..629a37cbb0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs @@ -52,18 +52,18 @@ public abstract partial class MassFluxTestsBase : QuantityTestsBase protected abstract double KilogramsPerSecondPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramsPerHourPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerHourPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerHourPerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerSecondPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerSecondPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerSecondPerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerHourPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerHourPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerHourPerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerSecondPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerSecondPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerSecondPerSquareMillimeterTolerance { get { return 1e-5; } } + protected virtual double GramsPerHourPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerHourPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerHourPerSquareMillimeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerSecondPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerSecondPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double GramsPerSecondPerSquareMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerHourPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerHourPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerHourPerSquareMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerSecondPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerSecondPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerSecondPerSquareMillimeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassFluxUnit unit) @@ -268,7 +268,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -589,14 +589,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MassFluxUnit unit) { - var inBaseUnits = MassFlux.From(1.0, MassFlux.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MassFlux.From(1.0, MassFlux.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MassFlux.From(1.0, MassFlux.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MassFluxUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MassFluxUnit unit) @@ -610,8 +617,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassFluxUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFluxUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MassFlux.Units.Where(u => u != MassFlux.BaseUnit).DefaultIfEmpty(MassFlux.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MassFlux.Units.First(u => u != MassFlux.BaseUnit); var quantity = MassFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -839,8 +846,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -874,36 +882,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -916,22 +929,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -973,7 +989,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(new {MassFlux.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MassFlux.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs index 1cdfeb11b5..00b3490646 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs @@ -64,30 +64,30 @@ public abstract partial class MassFractionTestsBase : QuantityTestsBase protected abstract double PercentInOneDecimalFraction { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentigramsPerGramTolerance { get { return 1e-5; } } - protected virtual double CentigramsPerKilogramTolerance { get { return 1e-5; } } - protected virtual double DecagramsPerGramTolerance { get { return 1e-5; } } - protected virtual double DecagramsPerKilogramTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerGramTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerKilogramTolerance { get { return 1e-5; } } - protected virtual double DecimalFractionsTolerance { get { return 1e-5; } } - protected virtual double GramsPerGramTolerance { get { return 1e-5; } } - protected virtual double GramsPerKilogramTolerance { get { return 1e-5; } } - protected virtual double HectogramsPerGramTolerance { get { return 1e-5; } } - protected virtual double HectogramsPerKilogramTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerGramTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerKilogramTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerGramTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerKilogramTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerGramTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerKilogramTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerGramTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerKilogramTolerance { get { return 1e-5; } } - protected virtual double PartsPerBillionTolerance { get { return 1e-5; } } - protected virtual double PartsPerMillionTolerance { get { return 1e-5; } } - protected virtual double PartsPerThousandTolerance { get { return 1e-5; } } - protected virtual double PartsPerTrillionTolerance { get { return 1e-5; } } - protected virtual double PercentTolerance { get { return 1e-5; } } + protected virtual double CentigramsPerGramTolerance { get { return 1E-5; } } + protected virtual double CentigramsPerKilogramTolerance { get { return 1E-5; } } + protected virtual double DecagramsPerGramTolerance { get { return 1E-5; } } + protected virtual double DecagramsPerKilogramTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerGramTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerKilogramTolerance { get { return 1E-5; } } + protected virtual double DecimalFractionsTolerance { get { return 1E-5; } } + protected virtual double GramsPerGramTolerance { get { return 1E-5; } } + protected virtual double GramsPerKilogramTolerance { get { return 1E-5; } } + protected virtual double HectogramsPerGramTolerance { get { return 1E-5; } } + protected virtual double HectogramsPerKilogramTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerGramTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerKilogramTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerGramTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerKilogramTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerGramTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerKilogramTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerGramTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerKilogramTolerance { get { return 1E-5; } } + protected virtual double PartsPerBillionTolerance { get { return 1E-5; } } + protected virtual double PartsPerMillionTolerance { get { return 1E-5; } } + protected virtual double PartsPerThousandTolerance { get { return 1E-5; } } + protected virtual double PartsPerTrillionTolerance { get { return 1E-5; } } + protected virtual double PercentTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassFractionUnit unit) @@ -388,7 +388,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1021,14 +1021,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MassFractionUnit unit) { - var inBaseUnits = MassFraction.From(1.0, MassFraction.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MassFraction.From(1.0, MassFraction.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MassFraction.From(1.0, MassFraction.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MassFractionUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MassFractionUnit unit) @@ -1042,8 +1049,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassFractionUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFractionUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MassFraction.Units.Where(u => u != MassFraction.BaseUnit).DefaultIfEmpty(MassFraction.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MassFraction.Units.First(u => u != MassFraction.BaseUnit); var quantity = MassFraction.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1307,8 +1314,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MassFraction.FromDecimalFractions(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1342,36 +1350,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MassFraction.FromDecimalFractions(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MassFraction.FromDecimalFractions(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MassFraction.FromDecimalFractions(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MassFraction.FromDecimalFractions(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MassFraction.FromDecimalFractions(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1384,22 +1397,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MassFraction.FromDecimalFractions(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MassFraction.FromDecimalFractions(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MassFraction.FromDecimalFractions(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1441,7 +1457,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(new {MassFraction.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MassFraction.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs index 12f6d91b6e..ae4900fe18 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs @@ -68,34 +68,34 @@ public abstract partial class MassMomentOfInertiaTestsBase : QuantityTestsBase protected abstract double TonneSquareMilimetersInOneKilogramSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double GramSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double GramSquareMetersTolerance { get { return 1e-5; } } - protected virtual double GramSquareMillimetersTolerance { get { return 1e-5; } } - protected virtual double KilogramSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double KilogramSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double KilogramSquareMetersTolerance { get { return 1e-5; } } - protected virtual double KilogramSquareMillimetersTolerance { get { return 1e-5; } } - protected virtual double KilotonneSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double KilotonneSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double KilotonneSquareMetersTolerance { get { return 1e-5; } } - protected virtual double KilotonneSquareMilimetersTolerance { get { return 1e-5; } } - protected virtual double MegatonneSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double MegatonneSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double MegatonneSquareMetersTolerance { get { return 1e-5; } } - protected virtual double MegatonneSquareMilimetersTolerance { get { return 1e-5; } } - protected virtual double MilligramSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double MilligramSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double MilligramSquareMetersTolerance { get { return 1e-5; } } - protected virtual double MilligramSquareMillimetersTolerance { get { return 1e-5; } } - protected virtual double PoundSquareFeetTolerance { get { return 1e-5; } } - protected virtual double PoundSquareInchesTolerance { get { return 1e-5; } } - protected virtual double SlugSquareFeetTolerance { get { return 1e-5; } } - protected virtual double SlugSquareInchesTolerance { get { return 1e-5; } } - protected virtual double TonneSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double TonneSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double TonneSquareMetersTolerance { get { return 1e-5; } } - protected virtual double TonneSquareMilimetersTolerance { get { return 1e-5; } } + protected virtual double GramSquareCentimetersTolerance { get { return 1E-5; } } + protected virtual double GramSquareDecimetersTolerance { get { return 1E-5; } } + protected virtual double GramSquareMetersTolerance { get { return 1E-5; } } + protected virtual double GramSquareMillimetersTolerance { get { return 1E-5; } } + protected virtual double KilogramSquareCentimetersTolerance { get { return 1E-5; } } + protected virtual double KilogramSquareDecimetersTolerance { get { return 1E-5; } } + protected virtual double KilogramSquareMetersTolerance { get { return 1E-5; } } + protected virtual double KilogramSquareMillimetersTolerance { get { return 1E-5; } } + protected virtual double KilotonneSquareCentimetersTolerance { get { return 1E-5; } } + protected virtual double KilotonneSquareDecimetersTolerance { get { return 1E-5; } } + protected virtual double KilotonneSquareMetersTolerance { get { return 1E-5; } } + protected virtual double KilotonneSquareMilimetersTolerance { get { return 1E-5; } } + protected virtual double MegatonneSquareCentimetersTolerance { get { return 1E-5; } } + protected virtual double MegatonneSquareDecimetersTolerance { get { return 1E-5; } } + protected virtual double MegatonneSquareMetersTolerance { get { return 1E-5; } } + protected virtual double MegatonneSquareMilimetersTolerance { get { return 1E-5; } } + protected virtual double MilligramSquareCentimetersTolerance { get { return 1E-5; } } + protected virtual double MilligramSquareDecimetersTolerance { get { return 1E-5; } } + protected virtual double MilligramSquareMetersTolerance { get { return 1E-5; } } + protected virtual double MilligramSquareMillimetersTolerance { get { return 1E-5; } } + protected virtual double PoundSquareFeetTolerance { get { return 1E-5; } } + protected virtual double PoundSquareInchesTolerance { get { return 1E-5; } } + protected virtual double SlugSquareFeetTolerance { get { return 1E-5; } } + protected virtual double SlugSquareInchesTolerance { get { return 1E-5; } } + protected virtual double TonneSquareCentimetersTolerance { get { return 1E-5; } } + protected virtual double TonneSquareDecimetersTolerance { get { return 1E-5; } } + protected virtual double TonneSquareMetersTolerance { get { return 1E-5; } } + protected virtual double TonneSquareMilimetersTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassMomentOfInertiaUnit unit) @@ -428,7 +428,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1133,14 +1133,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MassMomentOfInertiaUnit unit) { - var inBaseUnits = MassMomentOfInertia.From(1.0, MassMomentOfInertia.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MassMomentOfInertia.From(1.0, MassMomentOfInertia.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MassMomentOfInertia.From(1.0, MassMomentOfInertia.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MassMomentOfInertiaUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MassMomentOfInertiaUnit unit) @@ -1154,8 +1161,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassMomentOfInertiaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassMomentOfInertiaUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MassMomentOfInertia.Units.Where(u => u != MassMomentOfInertia.BaseUnit).DefaultIfEmpty(MassMomentOfInertia.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MassMomentOfInertia.Units.First(u => u != MassMomentOfInertia.BaseUnit); var quantity = MassMomentOfInertia.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1431,8 +1438,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1466,36 +1474,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1508,22 +1521,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1565,7 +1581,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(new {MassMomentOfInertia.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MassMomentOfInertia.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs index aee8d32ea4..53bbe5b415 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs @@ -65,31 +65,31 @@ public abstract partial class MassTestsBase : QuantityTestsBase protected abstract double TonnesInOneKilogram { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentigramsTolerance { get { return 1e-5; } } - protected virtual double DecagramsTolerance { get { return 1e-5; } } - protected virtual double DecigramsTolerance { get { return 1e-5; } } - protected virtual double EarthMassesTolerance { get { return 1e-5; } } - protected virtual double GrainsTolerance { get { return 1e-5; } } - protected virtual double GramsTolerance { get { return 1e-5; } } - protected virtual double HectogramsTolerance { get { return 1e-5; } } - protected virtual double KilogramsTolerance { get { return 1e-5; } } - protected virtual double KilopoundsTolerance { get { return 1e-5; } } - protected virtual double KilotonnesTolerance { get { return 1e-5; } } - protected virtual double LongHundredweightTolerance { get { return 1e-5; } } - protected virtual double LongTonsTolerance { get { return 1e-5; } } - protected virtual double MegapoundsTolerance { get { return 1e-5; } } - protected virtual double MegatonnesTolerance { get { return 1e-5; } } - protected virtual double MicrogramsTolerance { get { return 1e-5; } } - protected virtual double MilligramsTolerance { get { return 1e-5; } } - protected virtual double NanogramsTolerance { get { return 1e-5; } } - protected virtual double OuncesTolerance { get { return 1e-5; } } - protected virtual double PoundsTolerance { get { return 1e-5; } } - protected virtual double ShortHundredweightTolerance { get { return 1e-5; } } - protected virtual double ShortTonsTolerance { get { return 1e-5; } } - protected virtual double SlugsTolerance { get { return 1e-5; } } - protected virtual double SolarMassesTolerance { get { return 1e-5; } } - protected virtual double StoneTolerance { get { return 1e-5; } } - protected virtual double TonnesTolerance { get { return 1e-5; } } + protected virtual double CentigramsTolerance { get { return 1E-5; } } + protected virtual double DecagramsTolerance { get { return 1E-5; } } + protected virtual double DecigramsTolerance { get { return 1E-5; } } + protected virtual double EarthMassesTolerance { get { return 1E-5; } } + protected virtual double GrainsTolerance { get { return 1E-5; } } + protected virtual double GramsTolerance { get { return 1E-5; } } + protected virtual double HectogramsTolerance { get { return 1E-5; } } + protected virtual double KilogramsTolerance { get { return 1E-5; } } + protected virtual double KilopoundsTolerance { get { return 1E-5; } } + protected virtual double KilotonnesTolerance { get { return 1E-5; } } + protected virtual double LongHundredweightTolerance { get { return 1E-5; } } + protected virtual double LongTonsTolerance { get { return 1E-5; } } + protected virtual double MegapoundsTolerance { get { return 1E-5; } } + protected virtual double MegatonnesTolerance { get { return 1E-5; } } + protected virtual double MicrogramsTolerance { get { return 1E-5; } } + protected virtual double MilligramsTolerance { get { return 1E-5; } } + protected virtual double NanogramsTolerance { get { return 1E-5; } } + protected virtual double OuncesTolerance { get { return 1E-5; } } + protected virtual double PoundsTolerance { get { return 1E-5; } } + protected virtual double ShortHundredweightTolerance { get { return 1E-5; } } + protected virtual double ShortTonsTolerance { get { return 1E-5; } } + protected virtual double SlugsTolerance { get { return 1E-5; } } + protected virtual double SolarMassesTolerance { get { return 1E-5; } } + protected virtual double StoneTolerance { get { return 1E-5; } } + protected virtual double TonnesTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MassUnit unit) @@ -398,7 +398,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -2019,14 +2019,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MassUnit unit) { - var inBaseUnits = Mass.From(1.0, Mass.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Mass.From(1.0, Mass.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Mass.From(1.0, Mass.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MassUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MassUnit unit) @@ -2040,8 +2047,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Mass.Units.Where(u => u != Mass.BaseUnit).DefaultIfEmpty(Mass.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Mass.Units.First(u => u != Mass.BaseUnit); var quantity = Mass.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2308,8 +2315,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Mass.FromKilograms(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -2343,36 +2351,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Mass.FromKilograms(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Mass.FromKilograms(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Mass.FromKilograms(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Mass.FromKilograms(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Mass.FromKilograms(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -2385,22 +2398,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Mass.FromKilograms(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Mass.FromKilograms(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Mass.FromKilograms(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -2442,7 +2458,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Mass.FromKilograms(1.0); - Assert.Equal(new {Mass.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Mass.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs index d02524f56e..67173dd576 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class MolarEnergyTestsBase : QuantityTestsBase protected abstract double MegajoulesPerMoleInOneJoulePerMole { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double JoulesPerMoleTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerMoleTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerMoleTolerance { get { return 1e-5; } } + protected virtual double JoulesPerMoleTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerMoleTolerance { get { return 1E-5; } } + protected virtual double MegajoulesPerMoleTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MolarEnergyUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MolarEnergyUnit unit) { - var inBaseUnits = MolarEnergy.From(1.0, MolarEnergy.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MolarEnergy.From(1.0, MolarEnergy.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MolarEnergy.From(1.0, MolarEnergy.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MolarEnergyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MolarEnergyUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(MolarEnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarEnergyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MolarEnergy.Units.Where(u => u != MolarEnergy.BaseUnit).DefaultIfEmpty(MolarEnergy.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MolarEnergy.Units.First(u => u != MolarEnergy.BaseUnit); var quantity = MolarEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MolarEnergy.FromJoulesPerMole(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MolarEnergy.FromJoulesPerMole(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MolarEnergy.FromJoulesPerMole(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MolarEnergy.FromJoulesPerMole(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MolarEnergy.FromJoulesPerMole(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MolarEnergy.FromJoulesPerMole(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MolarEnergy.FromJoulesPerMole(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MolarEnergy.FromJoulesPerMole(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MolarEnergy.FromJoulesPerMole(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(new {MolarEnergy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MolarEnergy.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs index 78a88ecb39..27d2a3f3ef 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class MolarEntropyTestsBase : QuantityTestsBase protected abstract double MegajoulesPerMoleKelvinInOneJoulePerMoleKelvin { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double JoulesPerMoleKelvinTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerMoleKelvinTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerMoleKelvinTolerance { get { return 1e-5; } } + protected virtual double JoulesPerMoleKelvinTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerMoleKelvinTolerance { get { return 1E-5; } } + protected virtual double MegajoulesPerMoleKelvinTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MolarEntropyUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MolarEntropyUnit unit) { - var inBaseUnits = MolarEntropy.From(1.0, MolarEntropy.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MolarEntropy.From(1.0, MolarEntropy.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MolarEntropy.From(1.0, MolarEntropy.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MolarEntropyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MolarEntropyUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(MolarEntropyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarEntropyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MolarEntropy.Units.Where(u => u != MolarEntropy.BaseUnit).DefaultIfEmpty(MolarEntropy.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MolarEntropy.Units.First(u => u != MolarEntropy.BaseUnit); var quantity = MolarEntropy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(new {MolarEntropy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MolarEntropy.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs index ffe0f30f77..1386699ba0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs @@ -52,18 +52,18 @@ public abstract partial class MolarMassTestsBase : QuantityTestsBase protected abstract double PoundsPerMoleInOneKilogramPerMole { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentigramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double DecagramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double GramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double HectogramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double KilopoundsPerMoleTolerance { get { return 1e-5; } } - protected virtual double MegapoundsPerMoleTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double PoundsPerMoleTolerance { get { return 1e-5; } } + protected virtual double CentigramsPerMoleTolerance { get { return 1E-5; } } + protected virtual double DecagramsPerMoleTolerance { get { return 1E-5; } } + protected virtual double DecigramsPerMoleTolerance { get { return 1E-5; } } + protected virtual double GramsPerMoleTolerance { get { return 1E-5; } } + protected virtual double HectogramsPerMoleTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerMoleTolerance { get { return 1E-5; } } + protected virtual double KilopoundsPerMoleTolerance { get { return 1E-5; } } + protected virtual double MegapoundsPerMoleTolerance { get { return 1E-5; } } + protected virtual double MicrogramsPerMoleTolerance { get { return 1E-5; } } + protected virtual double MilligramsPerMoleTolerance { get { return 1E-5; } } + protected virtual double NanogramsPerMoleTolerance { get { return 1E-5; } } + protected virtual double PoundsPerMoleTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MolarMassUnit unit) @@ -268,7 +268,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -877,14 +877,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MolarMassUnit unit) { - var inBaseUnits = MolarMass.From(1.0, MolarMass.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = MolarMass.From(1.0, MolarMass.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = MolarMass.From(1.0, MolarMass.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MolarMassUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MolarMassUnit unit) @@ -898,8 +905,8 @@ public void ToUnit_WithSameUnits_AreEqual(MolarMassUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarMassUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = MolarMass.Units.Where(u => u != MolarMass.BaseUnit).DefaultIfEmpty(MolarMass.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = MolarMass.Units.First(u => u != MolarMass.BaseUnit); var quantity = MolarMass.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1127,8 +1134,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = MolarMass.FromKilogramsPerMole(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1162,36 +1170,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = MolarMass.FromKilogramsPerMole(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = MolarMass.FromKilogramsPerMole(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = MolarMass.FromKilogramsPerMole(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = MolarMass.FromKilogramsPerMole(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = MolarMass.FromKilogramsPerMole(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1204,22 +1217,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = MolarMass.FromKilogramsPerMole(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = MolarMass.FromKilogramsPerMole(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = MolarMass.FromKilogramsPerMole(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1261,7 +1277,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(new {MolarMass.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(MolarMass.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs index 923b01a6b3..960cddfa8f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs @@ -49,15 +49,15 @@ public abstract partial class MolarityTestsBase : QuantityTestsBase protected abstract double PicomolesPerLiterInOneMolesPerCubicMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double DecimolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double FemtomolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double MicromolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double MillimolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double MolesPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double NanomolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double PicomolesPerLiterTolerance { get { return 1e-5; } } + protected virtual double CentimolesPerLiterTolerance { get { return 1E-5; } } + protected virtual double DecimolesPerLiterTolerance { get { return 1E-5; } } + protected virtual double FemtomolesPerLiterTolerance { get { return 1E-5; } } + protected virtual double MicromolesPerLiterTolerance { get { return 1E-5; } } + protected virtual double MillimolesPerLiterTolerance { get { return 1E-5; } } + protected virtual double MolesPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double MolesPerLiterTolerance { get { return 1E-5; } } + protected virtual double NanomolesPerLiterTolerance { get { return 1E-5; } } + protected virtual double PicomolesPerLiterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(MolarityUnit unit) @@ -302,7 +302,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -578,14 +578,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(MolarityUnit unit) { - var inBaseUnits = Molarity.From(1.0, Molarity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Molarity.From(1.0, Molarity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Molarity.From(1.0, Molarity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(MolarityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(MolarityUnit unit) @@ -599,8 +606,8 @@ public void ToUnit_WithSameUnits_AreEqual(MolarityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Molarity.Units.Where(u => u != Molarity.BaseUnit).DefaultIfEmpty(Molarity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Molarity.Units.First(u => u != Molarity.BaseUnit); var quantity = Molarity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -843,8 +850,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Molarity.FromMolesPerCubicMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -878,36 +886,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Molarity.FromMolesPerCubicMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Molarity.FromMolesPerCubicMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Molarity.FromMolesPerCubicMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Molarity.FromMolesPerCubicMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Molarity.FromMolesPerCubicMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -920,22 +933,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Molarity.FromMolesPerCubicMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Molarity.FromMolesPerCubicMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Molarity.FromMolesPerCubicMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -977,7 +993,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(new {Molarity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Molarity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs index af5bee7872..748184a20e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class PermeabilityTestsBase : QuantityTestsBase protected abstract double HenriesPerMeterInOneHenryPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double HenriesPerMeterTolerance { get { return 1e-5; } } + protected virtual double HenriesPerMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PermeabilityUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(PermeabilityUnit unit) { - var inBaseUnits = Permeability.From(1.0, Permeability.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Permeability.From(1.0, Permeability.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Permeability.From(1.0, Permeability.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(PermeabilityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(PermeabilityUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(PermeabilityUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PermeabilityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Permeability.Units.Where(u => u != Permeability.BaseUnit).DefaultIfEmpty(Permeability.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Permeability.Units.First(u => u != Permeability.BaseUnit); var quantity = Permeability.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Permeability.FromHenriesPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Permeability.FromHenriesPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Permeability.FromHenriesPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Permeability.FromHenriesPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Permeability.FromHenriesPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Permeability.FromHenriesPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Permeability.FromHenriesPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Permeability.FromHenriesPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Permeability.FromHenriesPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(new {Permeability.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Permeability.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs index 1a1aa929fa..4e6467c7df 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class PermittivityTestsBase : QuantityTestsBase protected abstract double FaradsPerMeterInOneFaradPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double FaradsPerMeterTolerance { get { return 1e-5; } } + protected virtual double FaradsPerMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PermittivityUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(PermittivityUnit unit) { - var inBaseUnits = Permittivity.From(1.0, Permittivity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Permittivity.From(1.0, Permittivity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Permittivity.From(1.0, Permittivity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(PermittivityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(PermittivityUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(PermittivityUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PermittivityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Permittivity.Units.Where(u => u != Permittivity.BaseUnit).DefaultIfEmpty(Permittivity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Permittivity.Units.First(u => u != Permittivity.BaseUnit); var quantity = Permittivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Permittivity.FromFaradsPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Permittivity.FromFaradsPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Permittivity.FromFaradsPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Permittivity.FromFaradsPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Permittivity.FromFaradsPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Permittivity.FromFaradsPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Permittivity.FromFaradsPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Permittivity.FromFaradsPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Permittivity.FromFaradsPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(new {Permittivity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Permittivity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs index 88b7bcfa81..414490e545 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs @@ -45,11 +45,11 @@ public abstract partial class PorousMediumPermeabilityTestsBase : QuantityTestsB protected abstract double SquareMetersInOneSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DarcysTolerance { get { return 1e-5; } } - protected virtual double MicrodarcysTolerance { get { return 1e-5; } } - protected virtual double MillidarcysTolerance { get { return 1e-5; } } - protected virtual double SquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double SquareMetersTolerance { get { return 1e-5; } } + protected virtual double DarcysTolerance { get { return 1E-5; } } + protected virtual double MicrodarcysTolerance { get { return 1E-5; } } + protected virtual double MillidarcysTolerance { get { return 1E-5; } } + protected virtual double SquareCentimetersTolerance { get { return 1E-5; } } + protected virtual double SquareMetersTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PorousMediumPermeabilityUnit unit) @@ -198,7 +198,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -351,14 +351,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(PorousMediumPermeabilityUnit unit) { - var inBaseUnits = PorousMediumPermeability.From(1.0, PorousMediumPermeability.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = PorousMediumPermeability.From(1.0, PorousMediumPermeability.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = PorousMediumPermeability.From(1.0, PorousMediumPermeability.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(PorousMediumPermeabilityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(PorousMediumPermeabilityUnit unit) @@ -372,8 +379,8 @@ public void ToUnit_WithSameUnits_AreEqual(PorousMediumPermeabilityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PorousMediumPermeabilityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = PorousMediumPermeability.Units.Where(u => u != PorousMediumPermeability.BaseUnit).DefaultIfEmpty(PorousMediumPermeability.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = PorousMediumPermeability.Units.First(u => u != PorousMediumPermeability.BaseUnit); var quantity = PorousMediumPermeability.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -580,8 +587,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = PorousMediumPermeability.FromSquareMeters(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -615,36 +623,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = PorousMediumPermeability.FromSquareMeters(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = PorousMediumPermeability.FromSquareMeters(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = PorousMediumPermeability.FromSquareMeters(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = PorousMediumPermeability.FromSquareMeters(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = PorousMediumPermeability.FromSquareMeters(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -657,22 +670,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = PorousMediumPermeability.FromSquareMeters(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = PorousMediumPermeability.FromSquareMeters(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = PorousMediumPermeability.FromSquareMeters(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -714,7 +730,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(new {PorousMediumPermeability.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(PorousMediumPermeability.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs index 9888200c48..82d5a94817 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs @@ -84,50 +84,50 @@ public abstract partial class PowerDensityTestsBase : QuantityTestsBase protected abstract double WattsPerLiterInOneWattPerCubicMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecawattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double DecawattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double DecawattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double DecawattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double TerawattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double TerawattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double TerawattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double TerawattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double WattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double WattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double WattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double WattsPerLiterTolerance { get { return 1e-5; } } + protected virtual double DecawattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double DecawattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double DecawattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double DecawattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double DeciwattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double DeciwattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double DeciwattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double DeciwattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double GigawattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double GigawattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double GigawattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double GigawattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double KilowattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double MegawattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double MicrowattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double MicrowattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double MicrowattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double MicrowattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double MilliwattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double NanowattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double NanowattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double NanowattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double NanowattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double PicowattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double PicowattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double PicowattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double PicowattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double TerawattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double TerawattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double TerawattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double TerawattsPerLiterTolerance { get { return 1E-5; } } + protected virtual double WattsPerCubicFootTolerance { get { return 1E-5; } } + protected virtual double WattsPerCubicInchTolerance { get { return 1E-5; } } + protected virtual double WattsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double WattsPerLiterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PowerDensityUnit unit) @@ -588,7 +588,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1589,14 +1589,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(PowerDensityUnit unit) { - var inBaseUnits = PowerDensity.From(1.0, PowerDensity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = PowerDensity.From(1.0, PowerDensity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = PowerDensity.From(1.0, PowerDensity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(PowerDensityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(PowerDensityUnit unit) @@ -1610,8 +1617,8 @@ public void ToUnit_WithSameUnits_AreEqual(PowerDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerDensityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = PowerDensity.Units.Where(u => u != PowerDensity.BaseUnit).DefaultIfEmpty(PowerDensity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = PowerDensity.Units.First(u => u != PowerDensity.BaseUnit); var quantity = PowerDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1935,8 +1942,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = PowerDensity.FromWattsPerCubicMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1970,36 +1978,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = PowerDensity.FromWattsPerCubicMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = PowerDensity.FromWattsPerCubicMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = PowerDensity.FromWattsPerCubicMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = PowerDensity.FromWattsPerCubicMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = PowerDensity.FromWattsPerCubicMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -2012,22 +2025,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = PowerDensity.FromWattsPerCubicMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = PowerDensity.FromWattsPerCubicMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = PowerDensity.FromWattsPerCubicMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -2069,7 +2085,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(new {PowerDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(PowerDensity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs index 3cd613b917..42ab82780f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs @@ -42,8 +42,8 @@ public abstract partial class PowerRatioTestsBase : QuantityTestsBase protected abstract double DecibelWattsInOneDecibelWatt { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecibelMilliwattsTolerance { get { return 1e-5; } } - protected virtual double DecibelWattsTolerance { get { return 1e-5; } } + protected virtual double DecibelMilliwattsTolerance { get { return 1E-5; } } + protected virtual double DecibelWattsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PowerRatioUnit unit) @@ -168,7 +168,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -273,14 +273,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(PowerRatioUnit unit) { - var inBaseUnits = PowerRatio.From(1.0, PowerRatio.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = PowerRatio.From(1.0, PowerRatio.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = PowerRatio.From(1.0, PowerRatio.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(PowerRatioUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(PowerRatioUnit unit) @@ -294,8 +301,8 @@ public void ToUnit_WithSameUnits_AreEqual(PowerRatioUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerRatioUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = PowerRatio.Units.Where(u => u != PowerRatio.BaseUnit).DefaultIfEmpty(PowerRatio.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = PowerRatio.Units.First(u => u != PowerRatio.BaseUnit); var quantity = PowerRatio.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -497,8 +504,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = PowerRatio.FromDecibelWatts(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -532,36 +540,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = PowerRatio.FromDecibelWatts(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = PowerRatio.FromDecibelWatts(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = PowerRatio.FromDecibelWatts(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = PowerRatio.FromDecibelWatts(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = PowerRatio.FromDecibelWatts(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -574,22 +587,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = PowerRatio.FromDecibelWatts(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = PowerRatio.FromDecibelWatts(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = PowerRatio.FromDecibelWatts(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -631,7 +647,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(new {PowerRatio.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(PowerRatio.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs index 84e4e66f28..99130bf8c2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs @@ -38,63 +38,63 @@ namespace UnitsNet.Tests // ReSharper disable once PartialTypeWithSinglePart public abstract partial class PowerTestsBase : QuantityTestsBase { - protected abstract double BoilerHorsepowerInOneWatt { get; } - protected abstract double BritishThermalUnitsPerHourInOneWatt { get; } - protected abstract double DecawattsInOneWatt { get; } - protected abstract double DeciwattsInOneWatt { get; } - protected abstract double ElectricalHorsepowerInOneWatt { get; } - protected abstract double FemtowattsInOneWatt { get; } - protected abstract double GigajoulesPerHourInOneWatt { get; } - protected abstract double GigawattsInOneWatt { get; } - protected abstract double HydraulicHorsepowerInOneWatt { get; } - protected abstract double JoulesPerHourInOneWatt { get; } - protected abstract double KilobritishThermalUnitsPerHourInOneWatt { get; } - protected abstract double KilojoulesPerHourInOneWatt { get; } - protected abstract double KilowattsInOneWatt { get; } - protected abstract double MechanicalHorsepowerInOneWatt { get; } - protected abstract double MegabritishThermalUnitsPerHourInOneWatt { get; } - protected abstract double MegajoulesPerHourInOneWatt { get; } - protected abstract double MegawattsInOneWatt { get; } - protected abstract double MetricHorsepowerInOneWatt { get; } - protected abstract double MicrowattsInOneWatt { get; } - protected abstract double MillijoulesPerHourInOneWatt { get; } - protected abstract double MilliwattsInOneWatt { get; } - protected abstract double NanowattsInOneWatt { get; } - protected abstract double PetawattsInOneWatt { get; } - protected abstract double PicowattsInOneWatt { get; } - protected abstract double TerawattsInOneWatt { get; } - protected abstract double WattsInOneWatt { get; } + protected abstract decimal BoilerHorsepowerInOneWatt { get; } + protected abstract decimal BritishThermalUnitsPerHourInOneWatt { get; } + protected abstract decimal DecawattsInOneWatt { get; } + protected abstract decimal DeciwattsInOneWatt { get; } + protected abstract decimal ElectricalHorsepowerInOneWatt { get; } + protected abstract decimal FemtowattsInOneWatt { get; } + protected abstract decimal GigajoulesPerHourInOneWatt { get; } + protected abstract decimal GigawattsInOneWatt { get; } + protected abstract decimal HydraulicHorsepowerInOneWatt { get; } + protected abstract decimal JoulesPerHourInOneWatt { get; } + protected abstract decimal KilobritishThermalUnitsPerHourInOneWatt { get; } + protected abstract decimal KilojoulesPerHourInOneWatt { get; } + protected abstract decimal KilowattsInOneWatt { get; } + protected abstract decimal MechanicalHorsepowerInOneWatt { get; } + protected abstract decimal MegabritishThermalUnitsPerHourInOneWatt { get; } + protected abstract decimal MegajoulesPerHourInOneWatt { get; } + protected abstract decimal MegawattsInOneWatt { get; } + protected abstract decimal MetricHorsepowerInOneWatt { get; } + protected abstract decimal MicrowattsInOneWatt { get; } + protected abstract decimal MillijoulesPerHourInOneWatt { get; } + protected abstract decimal MilliwattsInOneWatt { get; } + protected abstract decimal NanowattsInOneWatt { get; } + protected abstract decimal PetawattsInOneWatt { get; } + protected abstract decimal PicowattsInOneWatt { get; } + protected abstract decimal TerawattsInOneWatt { get; } + protected abstract decimal WattsInOneWatt { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BoilerHorsepowerTolerance { get { return 1e-5; } } - protected virtual double BritishThermalUnitsPerHourTolerance { get { return 1e-5; } } - protected virtual double DecawattsTolerance { get { return 1e-5; } } - protected virtual double DeciwattsTolerance { get { return 1e-5; } } - protected virtual double ElectricalHorsepowerTolerance { get { return 1e-5; } } - protected virtual double FemtowattsTolerance { get { return 1e-5; } } - protected virtual double GigajoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double GigawattsTolerance { get { return 1e-5; } } - protected virtual double HydraulicHorsepowerTolerance { get { return 1e-5; } } - protected virtual double JoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double KilobritishThermalUnitsPerHourTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double KilowattsTolerance { get { return 1e-5; } } - protected virtual double MechanicalHorsepowerTolerance { get { return 1e-5; } } - protected virtual double MegabritishThermalUnitsPerHourTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double MegawattsTolerance { get { return 1e-5; } } - protected virtual double MetricHorsepowerTolerance { get { return 1e-5; } } - protected virtual double MicrowattsTolerance { get { return 1e-5; } } - protected virtual double MillijoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double MilliwattsTolerance { get { return 1e-5; } } - protected virtual double NanowattsTolerance { get { return 1e-5; } } - protected virtual double PetawattsTolerance { get { return 1e-5; } } - protected virtual double PicowattsTolerance { get { return 1e-5; } } - protected virtual double TerawattsTolerance { get { return 1e-5; } } - protected virtual double WattsTolerance { get { return 1e-5; } } + protected virtual decimal BoilerHorsepowerTolerance { get { return 1E-9m; } } + protected virtual decimal BritishThermalUnitsPerHourTolerance { get { return 1E-9m; } } + protected virtual decimal DecawattsTolerance { get { return 1E-9m; } } + protected virtual decimal DeciwattsTolerance { get { return 1E-9m; } } + protected virtual decimal ElectricalHorsepowerTolerance { get { return 1E-9m; } } + protected virtual decimal FemtowattsTolerance { get { return 1E-9m; } } + protected virtual decimal GigajoulesPerHourTolerance { get { return 1E-9m; } } + protected virtual decimal GigawattsTolerance { get { return 1E-9m; } } + protected virtual decimal HydraulicHorsepowerTolerance { get { return 1E-9m; } } + protected virtual decimal JoulesPerHourTolerance { get { return 1E-9m; } } + protected virtual decimal KilobritishThermalUnitsPerHourTolerance { get { return 1E-9m; } } + protected virtual decimal KilojoulesPerHourTolerance { get { return 1E-9m; } } + protected virtual decimal KilowattsTolerance { get { return 1E-9m; } } + protected virtual decimal MechanicalHorsepowerTolerance { get { return 1E-9m; } } + protected virtual decimal MegabritishThermalUnitsPerHourTolerance { get { return 1E-9m; } } + protected virtual decimal MegajoulesPerHourTolerance { get { return 1E-9m; } } + protected virtual decimal MegawattsTolerance { get { return 1E-9m; } } + protected virtual decimal MetricHorsepowerTolerance { get { return 1E-9m; } } + protected virtual decimal MicrowattsTolerance { get { return 1E-9m; } } + protected virtual decimal MillijoulesPerHourTolerance { get { return 1E-9m; } } + protected virtual decimal MilliwattsTolerance { get { return 1E-9m; } } + protected virtual decimal NanowattsTolerance { get { return 1E-9m; } } + protected virtual decimal PetawattsTolerance { get { return 1E-9m; } } + protected virtual decimal PicowattsTolerance { get { return 1E-9m; } } + protected virtual decimal TerawattsTolerance { get { return 1E-9m; } } + protected virtual decimal WattsTolerance { get { return 1E-9m; } } // ReSharper restore VirtualMemberNeverOverriden.Global - protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PowerUnit unit) + protected (decimal UnitsInBaseUnit, decimal Tolerence) GetConversionFactor(PowerUnit unit) { return unit switch { @@ -383,7 +383,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1046,14 +1046,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(PowerUnit unit) { - var inBaseUnits = Power.From(1.0, Power.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Power.From(1.0, Power.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Power.From(1.0, Power.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(PowerUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(PowerUnit unit) @@ -1067,8 +1074,8 @@ public void ToUnit_WithSameUnits_AreEqual(PowerUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Power.Units.Where(u => u != Power.BaseUnit).DefaultIfEmpty(Power.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Power.Units.First(u => u != Power.BaseUnit); var quantity = Power.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1338,8 +1345,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Power.FromWatts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Power.FromWatts(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1373,36 +1381,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Power.FromWatts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Power.FromWatts(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Power.FromWatts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Power.FromWatts(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Power.FromWatts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Power.FromWatts(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Power.FromWatts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Power.FromWatts(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Power.FromWatts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Power.FromWatts(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1415,22 +1428,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Power.FromWatts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Power.FromWatts(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Power.FromWatts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Power.FromWatts(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Power.FromWatts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Power.FromWatts(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1472,7 +1488,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Power.FromWatts(1.0); - Assert.Equal(new {Power.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Power.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs index c489b22624..cbd23636df 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs @@ -54,20 +54,20 @@ public abstract partial class PressureChangeRateTestsBase : QuantityTestsBase protected abstract double PoundsForcePerSquareInchPerSecondInOnePascalPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AtmospheresPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilopascalsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double KilopascalsPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerSquareInchPerMinuteTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerSquareInchPerSecondTolerance { get { return 1e-5; } } - protected virtual double MegapascalsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double MegapascalsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MegapoundsForcePerSquareInchPerMinuteTolerance { get { return 1e-5; } } - protected virtual double MegapoundsForcePerSquareInchPerSecondTolerance { get { return 1e-5; } } - protected virtual double MillimetersOfMercuryPerSecondTolerance { get { return 1e-5; } } - protected virtual double PascalsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double PascalsPerSecondTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerSquareInchPerMinuteTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerSquareInchPerSecondTolerance { get { return 1e-5; } } + protected virtual double AtmospheresPerSecondTolerance { get { return 1E-5; } } + protected virtual double KilopascalsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double KilopascalsPerSecondTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerSquareInchPerMinuteTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerSquareInchPerSecondTolerance { get { return 1E-5; } } + protected virtual double MegapascalsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double MegapascalsPerSecondTolerance { get { return 1E-5; } } + protected virtual double MegapoundsForcePerSquareInchPerMinuteTolerance { get { return 1E-5; } } + protected virtual double MegapoundsForcePerSquareInchPerSecondTolerance { get { return 1E-5; } } + protected virtual double MillimetersOfMercuryPerSecondTolerance { get { return 1E-5; } } + protected virtual double PascalsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double PascalsPerSecondTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerSquareInchPerMinuteTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerSquareInchPerSecondTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PressureChangeRateUnit unit) @@ -288,7 +288,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1281,14 +1281,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(PressureChangeRateUnit unit) { - var inBaseUnits = PressureChangeRate.From(1.0, PressureChangeRate.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = PressureChangeRate.From(1.0, PressureChangeRate.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = PressureChangeRate.From(1.0, PressureChangeRate.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(PressureChangeRateUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(PressureChangeRateUnit unit) @@ -1302,8 +1309,8 @@ public void ToUnit_WithSameUnits_AreEqual(PressureChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PressureChangeRateUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = PressureChangeRate.Units.Where(u => u != PressureChangeRate.BaseUnit).DefaultIfEmpty(PressureChangeRate.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = PressureChangeRate.Units.First(u => u != PressureChangeRate.BaseUnit); var quantity = PressureChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1537,8 +1544,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = PressureChangeRate.FromPascalsPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1572,36 +1580,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = PressureChangeRate.FromPascalsPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = PressureChangeRate.FromPascalsPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = PressureChangeRate.FromPascalsPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = PressureChangeRate.FromPascalsPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = PressureChangeRate.FromPascalsPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1614,22 +1627,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = PressureChangeRate.FromPascalsPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = PressureChangeRate.FromPascalsPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = PressureChangeRate.FromPascalsPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1671,7 +1687,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(new {PressureChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(PressureChangeRate.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs index 3db47ed7e7..7d21a9bb4a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs @@ -87,53 +87,53 @@ public abstract partial class PressureTestsBase : QuantityTestsBase protected abstract double TorrsInOnePascal { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AtmospheresTolerance { get { return 1e-5; } } - protected virtual double BarsTolerance { get { return 1e-5; } } - protected virtual double CentibarsTolerance { get { return 1e-5; } } - protected virtual double DecapascalsTolerance { get { return 1e-5; } } - protected virtual double DecibarsTolerance { get { return 1e-5; } } - protected virtual double DynesPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double FeetOfElevationTolerance { get { return 1e-5; } } - protected virtual double FeetOfHeadTolerance { get { return 1e-5; } } - protected virtual double GigapascalsTolerance { get { return 1e-5; } } - protected virtual double HectopascalsTolerance { get { return 1e-5; } } - protected virtual double InchesOfMercuryTolerance { get { return 1e-5; } } - protected virtual double InchesOfWaterColumnTolerance { get { return 1e-5; } } - protected virtual double KilobarsTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilopascalsTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerSquareFootTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerSquareInchTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerSquareMilTolerance { get { return 1e-5; } } - protected virtual double MegabarsTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MegapascalsTolerance { get { return 1e-5; } } - protected virtual double MetersOfElevationTolerance { get { return 1e-5; } } - protected virtual double MetersOfHeadTolerance { get { return 1e-5; } } - protected virtual double MicrobarsTolerance { get { return 1e-5; } } - protected virtual double MicropascalsTolerance { get { return 1e-5; } } - protected virtual double MillibarsTolerance { get { return 1e-5; } } - protected virtual double MillimetersOfMercuryTolerance { get { return 1e-5; } } - protected virtual double MillimeterOfWaterColumnTolerance { get { return 1e-5; } } - protected virtual double MillipascalsTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double PascalsTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerSquareFootTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerSquareInchTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerSquareMilTolerance { get { return 1e-5; } } - protected virtual double PoundsPerInchSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double TechnicalAtmospheresTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double TorrsTolerance { get { return 1e-5; } } + protected virtual double AtmospheresTolerance { get { return 1E-5; } } + protected virtual double BarsTolerance { get { return 1E-5; } } + protected virtual double CentibarsTolerance { get { return 1E-5; } } + protected virtual double DecapascalsTolerance { get { return 1E-5; } } + protected virtual double DecibarsTolerance { get { return 1E-5; } } + protected virtual double DynesPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double FeetOfElevationTolerance { get { return 1E-5; } } + protected virtual double FeetOfHeadTolerance { get { return 1E-5; } } + protected virtual double GigapascalsTolerance { get { return 1E-5; } } + protected virtual double HectopascalsTolerance { get { return 1E-5; } } + protected virtual double InchesOfMercuryTolerance { get { return 1E-5; } } + protected virtual double InchesOfWaterColumnTolerance { get { return 1E-5; } } + protected virtual double KilobarsTolerance { get { return 1E-5; } } + protected virtual double KilogramsForcePerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsForcePerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsForcePerSquareMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerSquareMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilopascalsTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerSquareFootTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerSquareInchTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerSquareMilTolerance { get { return 1E-5; } } + protected virtual double MegabarsTolerance { get { return 1E-5; } } + protected virtual double MeganewtonsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double MegapascalsTolerance { get { return 1E-5; } } + protected virtual double MetersOfElevationTolerance { get { return 1E-5; } } + protected virtual double MetersOfHeadTolerance { get { return 1E-5; } } + protected virtual double MicrobarsTolerance { get { return 1E-5; } } + protected virtual double MicropascalsTolerance { get { return 1E-5; } } + protected virtual double MillibarsTolerance { get { return 1E-5; } } + protected virtual double MillimetersOfMercuryTolerance { get { return 1E-5; } } + protected virtual double MillimeterOfWaterColumnTolerance { get { return 1E-5; } } + protected virtual double MillipascalsTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerSquareMillimeterTolerance { get { return 1E-5; } } + protected virtual double PascalsTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerSquareFootTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerSquareInchTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerSquareMilTolerance { get { return 1E-5; } } + protected virtual double PoundsPerInchSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double TechnicalAtmospheresTolerance { get { return 1E-5; } } + protected virtual double TonnesForcePerSquareCentimeterTolerance { get { return 1E-5; } } + protected virtual double TonnesForcePerSquareMeterTolerance { get { return 1E-5; } } + protected virtual double TonnesForcePerSquareMillimeterTolerance { get { return 1E-5; } } + protected virtual double TorrsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PressureUnit unit) @@ -618,7 +618,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -2629,14 +2629,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(PressureUnit unit) { - var inBaseUnits = Pressure.From(1.0, Pressure.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Pressure.From(1.0, Pressure.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Pressure.From(1.0, Pressure.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(PressureUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(PressureUnit unit) @@ -2650,8 +2657,8 @@ public void ToUnit_WithSameUnits_AreEqual(PressureUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PressureUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Pressure.Units.Where(u => u != Pressure.BaseUnit).DefaultIfEmpty(Pressure.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Pressure.Units.First(u => u != Pressure.BaseUnit); var quantity = Pressure.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2984,8 +2991,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Pressure.FromPascals(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -3019,36 +3027,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Pressure.FromPascals(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Pressure.FromPascals(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Pressure.FromPascals(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Pressure.FromPascals(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Pressure.FromPascals(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -3061,22 +3074,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Pressure.FromPascals(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Pressure.FromPascals(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Pressure.FromPascals(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -3118,7 +3134,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Pressure.FromPascals(1.0); - Assert.Equal(new {Pressure.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Pressure.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs index 989c017044..3978af69d0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs @@ -42,8 +42,8 @@ public abstract partial class RatioChangeRateTestsBase : QuantityTestsBase protected abstract double PercentsPerSecondInOneDecimalFractionPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecimalFractionsPerSecondTolerance { get { return 1e-5; } } - protected virtual double PercentsPerSecondTolerance { get { return 1e-5; } } + protected virtual double DecimalFractionsPerSecondTolerance { get { return 1E-5; } } + protected virtual double PercentsPerSecondTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RatioChangeRateUnit unit) @@ -168,7 +168,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -249,14 +249,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(RatioChangeRateUnit unit) { - var inBaseUnits = RatioChangeRate.From(1.0, RatioChangeRate.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = RatioChangeRate.From(1.0, RatioChangeRate.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = RatioChangeRate.From(1.0, RatioChangeRate.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(RatioChangeRateUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(RatioChangeRateUnit unit) @@ -270,8 +277,8 @@ public void ToUnit_WithSameUnits_AreEqual(RatioChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RatioChangeRateUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = RatioChangeRate.Units.Where(u => u != RatioChangeRate.BaseUnit).DefaultIfEmpty(RatioChangeRate.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = RatioChangeRate.Units.First(u => u != RatioChangeRate.BaseUnit); var quantity = RatioChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -469,8 +476,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -504,36 +512,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -546,22 +559,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -603,7 +619,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(new {RatioChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(RatioChangeRate.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs index 8714c6f6a3..4c84253dd5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs @@ -46,12 +46,12 @@ public abstract partial class RatioTestsBase : QuantityTestsBase protected abstract double PercentInOneDecimalFraction { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecimalFractionsTolerance { get { return 1e-5; } } - protected virtual double PartsPerBillionTolerance { get { return 1e-5; } } - protected virtual double PartsPerMillionTolerance { get { return 1e-5; } } - protected virtual double PartsPerThousandTolerance { get { return 1e-5; } } - protected virtual double PartsPerTrillionTolerance { get { return 1e-5; } } - protected virtual double PercentTolerance { get { return 1e-5; } } + protected virtual double DecimalFractionsTolerance { get { return 1E-5; } } + protected virtual double PartsPerBillionTolerance { get { return 1E-5; } } + protected virtual double PartsPerMillionTolerance { get { return 1E-5; } } + protected virtual double PartsPerThousandTolerance { get { return 1E-5; } } + protected virtual double PartsPerTrillionTolerance { get { return 1E-5; } } + protected virtual double PercentTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RatioUnit unit) @@ -208,7 +208,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -385,14 +385,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(RatioUnit unit) { - var inBaseUnits = Ratio.From(1.0, Ratio.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Ratio.From(1.0, Ratio.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Ratio.From(1.0, Ratio.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(RatioUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(RatioUnit unit) @@ -406,8 +413,8 @@ public void ToUnit_WithSameUnits_AreEqual(RatioUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RatioUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Ratio.Units.Where(u => u != Ratio.BaseUnit).DefaultIfEmpty(Ratio.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Ratio.Units.First(u => u != Ratio.BaseUnit); var quantity = Ratio.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -617,8 +624,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Ratio.FromDecimalFractions(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -652,36 +660,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Ratio.FromDecimalFractions(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Ratio.FromDecimalFractions(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Ratio.FromDecimalFractions(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Ratio.FromDecimalFractions(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Ratio.FromDecimalFractions(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -694,22 +707,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Ratio.FromDecimalFractions(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Ratio.FromDecimalFractions(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Ratio.FromDecimalFractions(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -751,7 +767,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(new {Ratio.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Ratio.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs index 8c4ddb264c..be05f748b3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class ReactiveEnergyTestsBase : QuantityTestsBase protected abstract double VoltampereReactiveHoursInOneVoltampereReactiveHour { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltampereReactiveHoursTolerance { get { return 1e-5; } } - protected virtual double MegavoltampereReactiveHoursTolerance { get { return 1e-5; } } - protected virtual double VoltampereReactiveHoursTolerance { get { return 1e-5; } } + protected virtual double KilovoltampereReactiveHoursTolerance { get { return 1E-5; } } + protected virtual double MegavoltampereReactiveHoursTolerance { get { return 1E-5; } } + protected virtual double VoltampereReactiveHoursTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ReactiveEnergyUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ReactiveEnergyUnit unit) { - var inBaseUnits = ReactiveEnergy.From(1.0, ReactiveEnergy.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ReactiveEnergy.From(1.0, ReactiveEnergy.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ReactiveEnergy.From(1.0, ReactiveEnergy.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ReactiveEnergyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ReactiveEnergyUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(ReactiveEnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReactiveEnergyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ReactiveEnergy.Units.Where(u => u != ReactiveEnergy.BaseUnit).DefaultIfEmpty(ReactiveEnergy.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ReactiveEnergy.Units.First(u => u != ReactiveEnergy.BaseUnit); var quantity = ReactiveEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ReactiveEnergy.FromVoltampereReactiveHours(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ReactiveEnergy.FromVoltampereReactiveHours(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ReactiveEnergy.FromVoltampereReactiveHours(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ReactiveEnergy.FromVoltampereReactiveHours(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ReactiveEnergy.FromVoltampereReactiveHours(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ReactiveEnergy.FromVoltampereReactiveHours(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ReactiveEnergy.FromVoltampereReactiveHours(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ReactiveEnergy.FromVoltampereReactiveHours(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ReactiveEnergy.FromVoltampereReactiveHours(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(new {ReactiveEnergy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ReactiveEnergy.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs index 807b553fda..ef116e631d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class ReactivePowerTestsBase : QuantityTestsBase protected abstract double VoltamperesReactiveInOneVoltampereReactive { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GigavoltamperesReactiveTolerance { get { return 1e-5; } } - protected virtual double KilovoltamperesReactiveTolerance { get { return 1e-5; } } - protected virtual double MegavoltamperesReactiveTolerance { get { return 1e-5; } } - protected virtual double VoltamperesReactiveTolerance { get { return 1e-5; } } + protected virtual double GigavoltamperesReactiveTolerance { get { return 1E-5; } } + protected virtual double KilovoltamperesReactiveTolerance { get { return 1E-5; } } + protected virtual double MegavoltamperesReactiveTolerance { get { return 1E-5; } } + protected virtual double VoltamperesReactiveTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ReactivePowerUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -317,14 +317,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ReactivePowerUnit unit) { - var inBaseUnits = ReactivePower.From(1.0, ReactivePower.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ReactivePower.From(1.0, ReactivePower.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ReactivePower.From(1.0, ReactivePower.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ReactivePowerUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ReactivePowerUnit unit) @@ -338,8 +345,8 @@ public void ToUnit_WithSameUnits_AreEqual(ReactivePowerUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReactivePowerUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ReactivePower.Units.Where(u => u != ReactivePower.BaseUnit).DefaultIfEmpty(ReactivePower.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ReactivePower.Units.First(u => u != ReactivePower.BaseUnit); var quantity = ReactivePower.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -543,8 +550,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ReactivePower.FromVoltamperesReactive(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -578,36 +586,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ReactivePower.FromVoltamperesReactive(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ReactivePower.FromVoltamperesReactive(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ReactivePower.FromVoltamperesReactive(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ReactivePower.FromVoltamperesReactive(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ReactivePower.FromVoltamperesReactive(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -620,22 +633,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ReactivePower.FromVoltamperesReactive(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ReactivePower.FromVoltamperesReactive(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ReactivePower.FromVoltamperesReactive(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -677,7 +693,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(new {ReactivePower.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ReactivePower.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs index 93590fd301..3b7ffb3eb6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs @@ -51,17 +51,17 @@ public abstract partial class ReciprocalAreaTestsBase : QuantityTestsBase protected abstract double InverseUsSurveySquareFeetInOneInverseSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double InverseSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double InverseSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double InverseSquareFeetTolerance { get { return 1e-5; } } - protected virtual double InverseSquareInchesTolerance { get { return 1e-5; } } - protected virtual double InverseSquareKilometersTolerance { get { return 1e-5; } } - protected virtual double InverseSquareMetersTolerance { get { return 1e-5; } } - protected virtual double InverseSquareMicrometersTolerance { get { return 1e-5; } } - protected virtual double InverseSquareMilesTolerance { get { return 1e-5; } } - protected virtual double InverseSquareMillimetersTolerance { get { return 1e-5; } } - protected virtual double InverseSquareYardsTolerance { get { return 1e-5; } } - protected virtual double InverseUsSurveySquareFeetTolerance { get { return 1e-5; } } + protected virtual double InverseSquareCentimetersTolerance { get { return 1E-5; } } + protected virtual double InverseSquareDecimetersTolerance { get { return 1E-5; } } + protected virtual double InverseSquareFeetTolerance { get { return 1E-5; } } + protected virtual double InverseSquareInchesTolerance { get { return 1E-5; } } + protected virtual double InverseSquareKilometersTolerance { get { return 1E-5; } } + protected virtual double InverseSquareMetersTolerance { get { return 1E-5; } } + protected virtual double InverseSquareMicrometersTolerance { get { return 1E-5; } } + protected virtual double InverseSquareMilesTolerance { get { return 1E-5; } } + protected virtual double InverseSquareMillimetersTolerance { get { return 1E-5; } } + protected virtual double InverseSquareYardsTolerance { get { return 1E-5; } } + protected virtual double InverseUsSurveySquareFeetTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ReciprocalAreaUnit unit) @@ -258,7 +258,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -555,14 +555,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ReciprocalAreaUnit unit) { - var inBaseUnits = ReciprocalArea.From(1.0, ReciprocalArea.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ReciprocalArea.From(1.0, ReciprocalArea.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ReciprocalArea.From(1.0, ReciprocalArea.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ReciprocalAreaUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ReciprocalAreaUnit unit) @@ -576,8 +583,8 @@ public void ToUnit_WithSameUnits_AreEqual(ReciprocalAreaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReciprocalAreaUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ReciprocalArea.Units.Where(u => u != ReciprocalArea.BaseUnit).DefaultIfEmpty(ReciprocalArea.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ReciprocalArea.Units.First(u => u != ReciprocalArea.BaseUnit); var quantity = ReciprocalArea.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -802,8 +809,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ReciprocalArea.FromInverseSquareMeters(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -837,36 +845,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ReciprocalArea.FromInverseSquareMeters(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ReciprocalArea.FromInverseSquareMeters(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ReciprocalArea.FromInverseSquareMeters(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ReciprocalArea.FromInverseSquareMeters(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ReciprocalArea.FromInverseSquareMeters(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -879,22 +892,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ReciprocalArea.FromInverseSquareMeters(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ReciprocalArea.FromInverseSquareMeters(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ReciprocalArea.FromInverseSquareMeters(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -936,7 +952,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(new {ReciprocalArea.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ReciprocalArea.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs index 3de7afaf9e..a4292f5bdb 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs @@ -50,16 +50,16 @@ public abstract partial class ReciprocalLengthTestsBase : QuantityTestsBase protected abstract double InverseYardsInOneInverseMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double InverseCentimetersTolerance { get { return 1e-5; } } - protected virtual double InverseFeetTolerance { get { return 1e-5; } } - protected virtual double InverseInchesTolerance { get { return 1e-5; } } - protected virtual double InverseMetersTolerance { get { return 1e-5; } } - protected virtual double InverseMicroinchesTolerance { get { return 1e-5; } } - protected virtual double InverseMilsTolerance { get { return 1e-5; } } - protected virtual double InverseMilesTolerance { get { return 1e-5; } } - protected virtual double InverseMillimetersTolerance { get { return 1e-5; } } - protected virtual double InverseUsSurveyFeetTolerance { get { return 1e-5; } } - protected virtual double InverseYardsTolerance { get { return 1e-5; } } + protected virtual double InverseCentimetersTolerance { get { return 1E-5; } } + protected virtual double InverseFeetTolerance { get { return 1E-5; } } + protected virtual double InverseInchesTolerance { get { return 1E-5; } } + protected virtual double InverseMetersTolerance { get { return 1E-5; } } + protected virtual double InverseMicroinchesTolerance { get { return 1E-5; } } + protected virtual double InverseMilsTolerance { get { return 1E-5; } } + protected virtual double InverseMilesTolerance { get { return 1E-5; } } + protected virtual double InverseMillimetersTolerance { get { return 1E-5; } } + protected virtual double InverseUsSurveyFeetTolerance { get { return 1E-5; } } + protected virtual double InverseYardsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ReciprocalLengthUnit unit) @@ -248,7 +248,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -761,14 +761,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ReciprocalLengthUnit unit) { - var inBaseUnits = ReciprocalLength.From(1.0, ReciprocalLength.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ReciprocalLength.From(1.0, ReciprocalLength.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ReciprocalLength.From(1.0, ReciprocalLength.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ReciprocalLengthUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ReciprocalLengthUnit unit) @@ -782,8 +789,8 @@ public void ToUnit_WithSameUnits_AreEqual(ReciprocalLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReciprocalLengthUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ReciprocalLength.Units.Where(u => u != ReciprocalLength.BaseUnit).DefaultIfEmpty(ReciprocalLength.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ReciprocalLength.Units.First(u => u != ReciprocalLength.BaseUnit); var quantity = ReciprocalLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1005,8 +1012,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ReciprocalLength.FromInverseMeters(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1040,36 +1048,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ReciprocalLength.FromInverseMeters(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ReciprocalLength.FromInverseMeters(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ReciprocalLength.FromInverseMeters(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ReciprocalLength.FromInverseMeters(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ReciprocalLength.FromInverseMeters(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1082,22 +1095,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ReciprocalLength.FromInverseMeters(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ReciprocalLength.FromInverseMeters(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ReciprocalLength.FromInverseMeters(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1139,7 +1155,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(new {ReciprocalLength.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ReciprocalLength.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs index 60f67c7468..cd282ea216 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class RelativeHumidityTestsBase : QuantityTestsBase protected abstract double PercentInOnePercent { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double PercentTolerance { get { return 1e-5; } } + protected virtual double PercentTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RelativeHumidityUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(RelativeHumidityUnit unit) { - var inBaseUnits = RelativeHumidity.From(1.0, RelativeHumidity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = RelativeHumidity.From(1.0, RelativeHumidity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = RelativeHumidity.From(1.0, RelativeHumidity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(RelativeHumidityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(RelativeHumidityUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(RelativeHumidityUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RelativeHumidityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = RelativeHumidity.Units.Where(u => u != RelativeHumidity.BaseUnit).DefaultIfEmpty(RelativeHumidity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = RelativeHumidity.Units.First(u => u != RelativeHumidity.BaseUnit); var quantity = RelativeHumidity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = RelativeHumidity.FromPercent(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = RelativeHumidity.FromPercent(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = RelativeHumidity.FromPercent(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = RelativeHumidity.FromPercent(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = RelativeHumidity.FromPercent(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = RelativeHumidity.FromPercent(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = RelativeHumidity.FromPercent(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = RelativeHumidity.FromPercent(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = RelativeHumidity.FromPercent(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(new {RelativeHumidity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(RelativeHumidity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs index f0cc297b7e..1b6e0489a5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class RotationalAccelerationTestsBase : QuantityTestsBas protected abstract double RevolutionsPerSecondSquaredInOneRadianPerSecondSquared { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DegreesPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double RadiansPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double RevolutionsPerMinutePerSecondTolerance { get { return 1e-5; } } - protected virtual double RevolutionsPerSecondSquaredTolerance { get { return 1e-5; } } + protected virtual double DegreesPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double RadiansPerSecondSquaredTolerance { get { return 1E-5; } } + protected virtual double RevolutionsPerMinutePerSecondTolerance { get { return 1E-5; } } + protected virtual double RevolutionsPerSecondSquaredTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RotationalAccelerationUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -341,14 +341,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(RotationalAccelerationUnit unit) { - var inBaseUnits = RotationalAcceleration.From(1.0, RotationalAcceleration.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = RotationalAcceleration.From(1.0, RotationalAcceleration.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = RotationalAcceleration.From(1.0, RotationalAcceleration.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(RotationalAccelerationUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(RotationalAccelerationUnit unit) @@ -362,8 +369,8 @@ public void ToUnit_WithSameUnits_AreEqual(RotationalAccelerationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalAccelerationUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = RotationalAcceleration.Units.Where(u => u != RotationalAcceleration.BaseUnit).DefaultIfEmpty(RotationalAcceleration.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = RotationalAcceleration.Units.First(u => u != RotationalAcceleration.BaseUnit); var quantity = RotationalAcceleration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -567,8 +574,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -602,36 +610,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -644,22 +657,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -701,7 +717,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(new {RotationalAcceleration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(RotationalAcceleration.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs index a2df678911..084fe1f460 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs @@ -53,19 +53,19 @@ public abstract partial class RotationalSpeedTestsBase : QuantityTestsBase protected abstract double RevolutionsPerSecondInOneRadianPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentiradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double DeciradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double DegreesPerMinuteTolerance { get { return 1e-5; } } - protected virtual double DegreesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicrodegreesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicroradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double MillidegreesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MilliradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanodegreesPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanoradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double RadiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double RevolutionsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double RevolutionsPerSecondTolerance { get { return 1e-5; } } + protected virtual double CentiradiansPerSecondTolerance { get { return 1E-5; } } + protected virtual double DeciradiansPerSecondTolerance { get { return 1E-5; } } + protected virtual double DegreesPerMinuteTolerance { get { return 1E-5; } } + protected virtual double DegreesPerSecondTolerance { get { return 1E-5; } } + protected virtual double MicrodegreesPerSecondTolerance { get { return 1E-5; } } + protected virtual double MicroradiansPerSecondTolerance { get { return 1E-5; } } + protected virtual double MillidegreesPerSecondTolerance { get { return 1E-5; } } + protected virtual double MilliradiansPerSecondTolerance { get { return 1E-5; } } + protected virtual double NanodegreesPerSecondTolerance { get { return 1E-5; } } + protected virtual double NanoradiansPerSecondTolerance { get { return 1E-5; } } + protected virtual double RadiansPerSecondTolerance { get { return 1E-5; } } + protected virtual double RevolutionsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double RevolutionsPerSecondTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RotationalSpeedUnit unit) @@ -278,7 +278,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1055,14 +1055,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(RotationalSpeedUnit unit) { - var inBaseUnits = RotationalSpeed.From(1.0, RotationalSpeed.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = RotationalSpeed.From(1.0, RotationalSpeed.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = RotationalSpeed.From(1.0, RotationalSpeed.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(RotationalSpeedUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(RotationalSpeedUnit unit) @@ -1076,8 +1083,8 @@ public void ToUnit_WithSameUnits_AreEqual(RotationalSpeedUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalSpeedUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = RotationalSpeed.Units.Where(u => u != RotationalSpeed.BaseUnit).DefaultIfEmpty(RotationalSpeed.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = RotationalSpeed.Units.First(u => u != RotationalSpeed.BaseUnit); var quantity = RotationalSpeed.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1308,8 +1315,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = RotationalSpeed.FromRadiansPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1343,36 +1351,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = RotationalSpeed.FromRadiansPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = RotationalSpeed.FromRadiansPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = RotationalSpeed.FromRadiansPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = RotationalSpeed.FromRadiansPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = RotationalSpeed.FromRadiansPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1385,22 +1398,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = RotationalSpeed.FromRadiansPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = RotationalSpeed.FromRadiansPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = RotationalSpeed.FromRadiansPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1442,7 +1458,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(new {RotationalSpeed.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(RotationalSpeed.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs index 7880b8d001..02d476b09e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs @@ -45,11 +45,11 @@ public abstract partial class RotationalStiffnessPerLengthTestsBase : QuantityTe protected abstract double PoundForceFeetPerDegreesPerFeetInOneNewtonMeterPerRadianPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilonewtonMetersPerRadianPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilopoundForceFeetPerDegreesPerFeetTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMetersPerRadianPerMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonMetersPerRadianPerMeterTolerance { get { return 1e-5; } } - protected virtual double PoundForceFeetPerDegreesPerFeetTolerance { get { return 1e-5; } } + protected virtual double KilonewtonMetersPerRadianPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilopoundForceFeetPerDegreesPerFeetTolerance { get { return 1E-5; } } + protected virtual double MeganewtonMetersPerRadianPerMeterTolerance { get { return 1E-5; } } + protected virtual double NewtonMetersPerRadianPerMeterTolerance { get { return 1E-5; } } + protected virtual double PoundForceFeetPerDegreesPerFeetTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RotationalStiffnessPerLengthUnit unit) @@ -198,7 +198,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -543,14 +543,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(RotationalStiffnessPerLengthUnit unit) { - var inBaseUnits = RotationalStiffnessPerLength.From(1.0, RotationalStiffnessPerLength.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = RotationalStiffnessPerLength.From(1.0, RotationalStiffnessPerLength.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = RotationalStiffnessPerLength.From(1.0, RotationalStiffnessPerLength.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(RotationalStiffnessPerLengthUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(RotationalStiffnessPerLengthUnit unit) @@ -564,8 +571,8 @@ public void ToUnit_WithSameUnits_AreEqual(RotationalStiffnessPerLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalStiffnessPerLengthUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = RotationalStiffnessPerLength.Units.Where(u => u != RotationalStiffnessPerLength.BaseUnit).DefaultIfEmpty(RotationalStiffnessPerLength.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = RotationalStiffnessPerLength.Units.First(u => u != RotationalStiffnessPerLength.BaseUnit); var quantity = RotationalStiffnessPerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -772,8 +779,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -807,36 +815,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -849,22 +862,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -906,7 +922,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(new {RotationalStiffnessPerLength.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(RotationalStiffnessPerLength.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs index 8557dab512..afc2d9ab68 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs @@ -73,39 +73,39 @@ public abstract partial class RotationalStiffnessTestsBase : QuantityTestsBase protected abstract double PoundForceFeetPerDegreesInOneNewtonMeterPerRadian { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentinewtonMetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double CentinewtonMillimetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double CentinewtonMillimetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double DecanewtonMetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double DecanewtonMillimetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double DecanewtonMillimetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double DecinewtonMetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double DecinewtonMillimetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double DecinewtonMillimetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMillimetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMillimetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double KilopoundForceFeetPerDegreesTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMillimetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMillimetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double MicronewtonMetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double MicronewtonMillimetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double MicronewtonMillimetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double MillinewtonMetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double MillinewtonMillimetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double MillinewtonMillimetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double NanonewtonMetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double NanonewtonMillimetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double NanonewtonMillimetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double NewtonMetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double NewtonMetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double NewtonMillimetersPerDegreeTolerance { get { return 1e-5; } } - protected virtual double NewtonMillimetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double PoundForceFeetPerRadianTolerance { get { return 1e-5; } } - protected virtual double PoundForceFeetPerDegreesTolerance { get { return 1e-5; } } + protected virtual double CentinewtonMetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double CentinewtonMillimetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double CentinewtonMillimetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double DecanewtonMetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double DecanewtonMillimetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double DecanewtonMillimetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double DecinewtonMetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double DecinewtonMillimetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double DecinewtonMillimetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double KilonewtonMetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double KilonewtonMetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double KilonewtonMillimetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double KilonewtonMillimetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double KilopoundForceFeetPerDegreesTolerance { get { return 1E-5; } } + protected virtual double MeganewtonMetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double MeganewtonMetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double MeganewtonMillimetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double MeganewtonMillimetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double MicronewtonMetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double MicronewtonMillimetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double MicronewtonMillimetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double MillinewtonMetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double MillinewtonMillimetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double MillinewtonMillimetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double NanonewtonMetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double NanonewtonMillimetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double NanonewtonMillimetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double NewtonMetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double NewtonMetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double NewtonMillimetersPerDegreeTolerance { get { return 1E-5; } } + protected virtual double NewtonMillimetersPerRadianTolerance { get { return 1E-5; } } + protected virtual double PoundForceFeetPerRadianTolerance { get { return 1E-5; } } + protected virtual double PoundForceFeetPerDegreesTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(RotationalStiffnessUnit unit) @@ -478,7 +478,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -2787,14 +2787,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(RotationalStiffnessUnit unit) { - var inBaseUnits = RotationalStiffness.From(1.0, RotationalStiffness.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = RotationalStiffness.From(1.0, RotationalStiffness.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = RotationalStiffness.From(1.0, RotationalStiffness.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(RotationalStiffnessUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(RotationalStiffnessUnit unit) @@ -2808,8 +2815,8 @@ public void ToUnit_WithSameUnits_AreEqual(RotationalStiffnessUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalStiffnessUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = RotationalStiffness.Units.Where(u => u != RotationalStiffness.BaseUnit).DefaultIfEmpty(RotationalStiffness.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = RotationalStiffness.Units.First(u => u != RotationalStiffness.BaseUnit); var quantity = RotationalStiffness.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -3100,8 +3107,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -3135,36 +3143,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -3177,22 +3190,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -3234,7 +3250,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(new {RotationalStiffness.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(RotationalStiffness.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs index 427c4da867..ed5f413d32 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class ScalarTestsBase : QuantityTestsBase protected abstract double AmountInOneAmount { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmountTolerance { get { return 1e-5; } } + protected virtual double AmountTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ScalarUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ScalarUnit unit) { - var inBaseUnits = Scalar.From(1.0, Scalar.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Scalar.From(1.0, Scalar.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Scalar.From(1.0, Scalar.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ScalarUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ScalarUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(ScalarUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ScalarUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Scalar.Units.Where(u => u != Scalar.BaseUnit).DefaultIfEmpty(Scalar.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Scalar.Units.First(u => u != Scalar.BaseUnit); var quantity = Scalar.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Scalar.FromAmount(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Scalar.FromAmount(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Scalar.FromAmount(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Scalar.FromAmount(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Scalar.FromAmount(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Scalar.FromAmount(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Scalar.FromAmount(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Scalar.FromAmount(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Scalar.FromAmount(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Scalar.FromAmount(1.0); - Assert.Equal(new {Scalar.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Scalar.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs index 6fe1a3602c..3785ea8be3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class SolidAngleTestsBase : QuantityTestsBase protected abstract double SteradiansInOneSteradian { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double SteradiansTolerance { get { return 1e-5; } } + protected virtual double SteradiansTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SolidAngleUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(SolidAngleUnit unit) { - var inBaseUnits = SolidAngle.From(1.0, SolidAngle.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = SolidAngle.From(1.0, SolidAngle.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = SolidAngle.From(1.0, SolidAngle.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(SolidAngleUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(SolidAngleUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(SolidAngleUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SolidAngleUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = SolidAngle.Units.Where(u => u != SolidAngle.BaseUnit).DefaultIfEmpty(SolidAngle.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = SolidAngle.Units.First(u => u != SolidAngle.BaseUnit); var quantity = SolidAngle.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = SolidAngle.FromSteradians(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = SolidAngle.FromSteradians(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = SolidAngle.FromSteradians(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = SolidAngle.FromSteradians(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = SolidAngle.FromSteradians(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = SolidAngle.FromSteradians(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = SolidAngle.FromSteradians(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = SolidAngle.FromSteradians(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = SolidAngle.FromSteradians(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(new {SolidAngle.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(SolidAngle.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs index 32be1e830a..0c2e9defed 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs @@ -69,35 +69,35 @@ public abstract partial class SpecificEnergyTestsBase : QuantityTestsBase protected abstract double WattHoursPerPoundInOneJoulePerKilogram { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BtuPerPoundTolerance { get { return 1e-5; } } - protected virtual double CaloriesPerGramTolerance { get { return 1e-5; } } - protected virtual double GigawattDaysPerKilogramTolerance { get { return 1e-5; } } - protected virtual double GigawattDaysPerShortTonTolerance { get { return 1e-5; } } - protected virtual double GigawattDaysPerTonneTolerance { get { return 1e-5; } } - protected virtual double GigawattHoursPerKilogramTolerance { get { return 1e-5; } } - protected virtual double GigawattHoursPerPoundTolerance { get { return 1e-5; } } - protected virtual double JoulesPerKilogramTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerGramTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerKilogramTolerance { get { return 1e-5; } } - protected virtual double KilowattDaysPerKilogramTolerance { get { return 1e-5; } } - protected virtual double KilowattDaysPerShortTonTolerance { get { return 1e-5; } } - protected virtual double KilowattDaysPerTonneTolerance { get { return 1e-5; } } - protected virtual double KilowattHoursPerKilogramTolerance { get { return 1e-5; } } - protected virtual double KilowattHoursPerPoundTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerKilogramTolerance { get { return 1e-5; } } - protected virtual double MegawattDaysPerKilogramTolerance { get { return 1e-5; } } - protected virtual double MegawattDaysPerShortTonTolerance { get { return 1e-5; } } - protected virtual double MegawattDaysPerTonneTolerance { get { return 1e-5; } } - protected virtual double MegawattHoursPerKilogramTolerance { get { return 1e-5; } } - protected virtual double MegawattHoursPerPoundTolerance { get { return 1e-5; } } - protected virtual double TerawattDaysPerKilogramTolerance { get { return 1e-5; } } - protected virtual double TerawattDaysPerShortTonTolerance { get { return 1e-5; } } - protected virtual double TerawattDaysPerTonneTolerance { get { return 1e-5; } } - protected virtual double WattDaysPerKilogramTolerance { get { return 1e-5; } } - protected virtual double WattDaysPerShortTonTolerance { get { return 1e-5; } } - protected virtual double WattDaysPerTonneTolerance { get { return 1e-5; } } - protected virtual double WattHoursPerKilogramTolerance { get { return 1e-5; } } - protected virtual double WattHoursPerPoundTolerance { get { return 1e-5; } } + protected virtual double BtuPerPoundTolerance { get { return 1E-5; } } + protected virtual double CaloriesPerGramTolerance { get { return 1E-5; } } + protected virtual double GigawattDaysPerKilogramTolerance { get { return 1E-5; } } + protected virtual double GigawattDaysPerShortTonTolerance { get { return 1E-5; } } + protected virtual double GigawattDaysPerTonneTolerance { get { return 1E-5; } } + protected virtual double GigawattHoursPerKilogramTolerance { get { return 1E-5; } } + protected virtual double GigawattHoursPerPoundTolerance { get { return 1E-5; } } + protected virtual double JoulesPerKilogramTolerance { get { return 1E-5; } } + protected virtual double KilocaloriesPerGramTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerKilogramTolerance { get { return 1E-5; } } + protected virtual double KilowattDaysPerKilogramTolerance { get { return 1E-5; } } + protected virtual double KilowattDaysPerShortTonTolerance { get { return 1E-5; } } + protected virtual double KilowattDaysPerTonneTolerance { get { return 1E-5; } } + protected virtual double KilowattHoursPerKilogramTolerance { get { return 1E-5; } } + protected virtual double KilowattHoursPerPoundTolerance { get { return 1E-5; } } + protected virtual double MegajoulesPerKilogramTolerance { get { return 1E-5; } } + protected virtual double MegawattDaysPerKilogramTolerance { get { return 1E-5; } } + protected virtual double MegawattDaysPerShortTonTolerance { get { return 1E-5; } } + protected virtual double MegawattDaysPerTonneTolerance { get { return 1E-5; } } + protected virtual double MegawattHoursPerKilogramTolerance { get { return 1E-5; } } + protected virtual double MegawattHoursPerPoundTolerance { get { return 1E-5; } } + protected virtual double TerawattDaysPerKilogramTolerance { get { return 1E-5; } } + protected virtual double TerawattDaysPerShortTonTolerance { get { return 1E-5; } } + protected virtual double TerawattDaysPerTonneTolerance { get { return 1E-5; } } + protected virtual double WattDaysPerKilogramTolerance { get { return 1E-5; } } + protected virtual double WattDaysPerShortTonTolerance { get { return 1E-5; } } + protected virtual double WattDaysPerTonneTolerance { get { return 1E-5; } } + protected virtual double WattHoursPerKilogramTolerance { get { return 1E-5; } } + protected virtual double WattHoursPerPoundTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificEnergyUnit unit) @@ -438,7 +438,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1167,14 +1167,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificEnergyUnit unit) { - var inBaseUnits = SpecificEnergy.From(1.0, SpecificEnergy.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = SpecificEnergy.From(1.0, SpecificEnergy.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = SpecificEnergy.From(1.0, SpecificEnergy.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(SpecificEnergyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(SpecificEnergyUnit unit) @@ -1188,8 +1195,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificEnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificEnergyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = SpecificEnergy.Units.Where(u => u != SpecificEnergy.BaseUnit).DefaultIfEmpty(SpecificEnergy.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = SpecificEnergy.Units.First(u => u != SpecificEnergy.BaseUnit); var quantity = SpecificEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1468,8 +1475,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = SpecificEnergy.FromJoulesPerKilogram(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1503,36 +1511,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = SpecificEnergy.FromJoulesPerKilogram(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = SpecificEnergy.FromJoulesPerKilogram(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = SpecificEnergy.FromJoulesPerKilogram(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = SpecificEnergy.FromJoulesPerKilogram(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = SpecificEnergy.FromJoulesPerKilogram(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1545,22 +1558,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = SpecificEnergy.FromJoulesPerKilogram(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = SpecificEnergy.FromJoulesPerKilogram(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = SpecificEnergy.FromJoulesPerKilogram(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1602,7 +1618,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(new {SpecificEnergy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(SpecificEnergy.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs index b58e37b641..751acae18f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs @@ -49,15 +49,15 @@ public abstract partial class SpecificEntropyTestsBase : QuantityTestsBase protected abstract double MegajoulesPerKilogramKelvinInOneJoulePerKilogramKelvin { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BtusPerPoundFahrenheitTolerance { get { return 1e-5; } } - protected virtual double CaloriesPerGramKelvinTolerance { get { return 1e-5; } } - protected virtual double JoulesPerKilogramDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double JoulesPerKilogramKelvinTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerGramKelvinTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerKilogramDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerKilogramKelvinTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerKilogramDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerKilogramKelvinTolerance { get { return 1e-5; } } + protected virtual double BtusPerPoundFahrenheitTolerance { get { return 1E-5; } } + protected virtual double CaloriesPerGramKelvinTolerance { get { return 1E-5; } } + protected virtual double JoulesPerKilogramDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double JoulesPerKilogramKelvinTolerance { get { return 1E-5; } } + protected virtual double KilocaloriesPerGramKelvinTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerKilogramDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerKilogramKelvinTolerance { get { return 1E-5; } } + protected virtual double MegajoulesPerKilogramDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double MegajoulesPerKilogramKelvinTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificEntropyUnit unit) @@ -238,7 +238,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -511,14 +511,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificEntropyUnit unit) { - var inBaseUnits = SpecificEntropy.From(1.0, SpecificEntropy.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = SpecificEntropy.From(1.0, SpecificEntropy.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = SpecificEntropy.From(1.0, SpecificEntropy.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(SpecificEntropyUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(SpecificEntropyUnit unit) @@ -532,8 +539,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificEntropyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificEntropyUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = SpecificEntropy.Units.Where(u => u != SpecificEntropy.BaseUnit).DefaultIfEmpty(SpecificEntropy.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = SpecificEntropy.Units.First(u => u != SpecificEntropy.BaseUnit); var quantity = SpecificEntropy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -752,8 +759,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -787,36 +795,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -829,22 +842,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -886,7 +902,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(new {SpecificEntropy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(SpecificEntropy.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs index e0e7e9e8cc..b3b875a146 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class SpecificFuelConsumptionTestsBase : QuantityTestsBa protected abstract double PoundsMassPerPoundForceHourInOneGramPerKiloNewtonSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramsPerKiloNewtonSecondTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerKilogramForceHourTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerKiloNewtonSecondTolerance { get { return 1e-5; } } - protected virtual double PoundsMassPerPoundForceHourTolerance { get { return 1e-5; } } + protected virtual double GramsPerKiloNewtonSecondTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerKilogramForceHourTolerance { get { return 1E-5; } } + protected virtual double KilogramsPerKiloNewtonSecondTolerance { get { return 1E-5; } } + protected virtual double PoundsMassPerPoundForceHourTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificFuelConsumptionUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -317,14 +317,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificFuelConsumptionUnit unit) { - var inBaseUnits = SpecificFuelConsumption.From(1.0, SpecificFuelConsumption.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = SpecificFuelConsumption.From(1.0, SpecificFuelConsumption.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = SpecificFuelConsumption.From(1.0, SpecificFuelConsumption.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(SpecificFuelConsumptionUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(SpecificFuelConsumptionUnit unit) @@ -338,8 +345,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificFuelConsumptionUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificFuelConsumptionUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = SpecificFuelConsumption.Units.Where(u => u != SpecificFuelConsumption.BaseUnit).DefaultIfEmpty(SpecificFuelConsumption.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = SpecificFuelConsumption.Units.First(u => u != SpecificFuelConsumption.BaseUnit); var quantity = SpecificFuelConsumption.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -543,8 +550,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -578,36 +586,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -620,22 +633,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -677,7 +693,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal(new {SpecificFuelConsumption.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(SpecificFuelConsumption.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs index 44c9025100..770ffe6f5d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs @@ -43,9 +43,9 @@ public abstract partial class SpecificVolumeTestsBase : QuantityTestsBase protected abstract double MillicubicMetersPerKilogramInOneCubicMeterPerKilogram { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CubicFeetPerPoundTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerKilogramTolerance { get { return 1e-5; } } - protected virtual double MillicubicMetersPerKilogramTolerance { get { return 1e-5; } } + protected virtual double CubicFeetPerPoundTolerance { get { return 1E-5; } } + protected virtual double CubicMetersPerKilogramTolerance { get { return 1E-5; } } + protected virtual double MillicubicMetersPerKilogramTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificVolumeUnit unit) @@ -178,7 +178,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -283,14 +283,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificVolumeUnit unit) { - var inBaseUnits = SpecificVolume.From(1.0, SpecificVolume.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = SpecificVolume.From(1.0, SpecificVolume.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = SpecificVolume.From(1.0, SpecificVolume.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(SpecificVolumeUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(SpecificVolumeUnit unit) @@ -304,8 +311,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificVolumeUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificVolumeUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = SpecificVolume.Units.Where(u => u != SpecificVolume.BaseUnit).DefaultIfEmpty(SpecificVolume.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = SpecificVolume.Units.First(u => u != SpecificVolume.BaseUnit); var quantity = SpecificVolume.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -506,8 +513,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = SpecificVolume.FromCubicMetersPerKilogram(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -541,36 +549,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = SpecificVolume.FromCubicMetersPerKilogram(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = SpecificVolume.FromCubicMetersPerKilogram(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = SpecificVolume.FromCubicMetersPerKilogram(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = SpecificVolume.FromCubicMetersPerKilogram(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = SpecificVolume.FromCubicMetersPerKilogram(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -583,22 +596,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = SpecificVolume.FromCubicMetersPerKilogram(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = SpecificVolume.FromCubicMetersPerKilogram(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = SpecificVolume.FromCubicMetersPerKilogram(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -640,7 +656,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(new {SpecificVolume.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(SpecificVolume.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs index daf5cffeae..300b216a12 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs @@ -57,23 +57,23 @@ public abstract partial class SpecificWeightTestsBase : QuantityTestsBase protected abstract double TonnesForcePerCubicMillimeterInOneNewtonPerCubicMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilogramsForcePerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerCubicFootTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerCubicFootTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerCubicInchTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerCubicMillimeterTolerance { get { return 1e-5; } } + protected virtual double KilogramsForcePerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsForcePerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramsForcePerCubicMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonsPerCubicMillimeterTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerCubicFootTolerance { get { return 1E-5; } } + protected virtual double KilopoundsForcePerCubicInchTolerance { get { return 1E-5; } } + protected virtual double MeganewtonsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double NewtonsPerCubicMillimeterTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerCubicFootTolerance { get { return 1E-5; } } + protected virtual double PoundsForcePerCubicInchTolerance { get { return 1E-5; } } + protected virtual double TonnesForcePerCubicCentimeterTolerance { get { return 1E-5; } } + protected virtual double TonnesForcePerCubicMeterTolerance { get { return 1E-5; } } + protected virtual double TonnesForcePerCubicMillimeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpecificWeightUnit unit) @@ -318,7 +318,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -759,14 +759,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificWeightUnit unit) { - var inBaseUnits = SpecificWeight.From(1.0, SpecificWeight.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = SpecificWeight.From(1.0, SpecificWeight.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = SpecificWeight.From(1.0, SpecificWeight.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(SpecificWeightUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(SpecificWeightUnit unit) @@ -780,8 +787,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificWeightUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificWeightUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = SpecificWeight.Units.Where(u => u != SpecificWeight.BaseUnit).DefaultIfEmpty(SpecificWeight.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = SpecificWeight.Units.First(u => u != SpecificWeight.BaseUnit); var quantity = SpecificWeight.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1024,8 +1031,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1059,36 +1067,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1101,22 +1114,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1158,7 +1174,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(new {SpecificWeight.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(SpecificWeight.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs index 9ef94f5cab..6f91fa89b4 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs @@ -72,38 +72,38 @@ public abstract partial class SpeedTestsBase : QuantityTestsBase protected abstract double YardsPerSecondInOneMeterPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimetersPerHourTolerance { get { return 1e-5; } } - protected virtual double CentimetersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double CentimetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecimetersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double DecimetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double FeetPerHourTolerance { get { return 1e-5; } } - protected virtual double FeetPerMinuteTolerance { get { return 1e-5; } } - protected virtual double FeetPerSecondTolerance { get { return 1e-5; } } - protected virtual double InchesPerHourTolerance { get { return 1e-5; } } - protected virtual double InchesPerMinuteTolerance { get { return 1e-5; } } - protected virtual double InchesPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilometersPerHourTolerance { get { return 1e-5; } } - protected virtual double KilometersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double KilometersPerSecondTolerance { get { return 1e-5; } } - protected virtual double KnotsTolerance { get { return 1e-5; } } - protected virtual double MetersPerHourTolerance { get { return 1e-5; } } - protected virtual double MetersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double MetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicrometersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double MicrometersPerSecondTolerance { get { return 1e-5; } } - protected virtual double MilesPerHourTolerance { get { return 1e-5; } } - protected virtual double MillimetersPerHourTolerance { get { return 1e-5; } } - protected virtual double MillimetersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double MillimetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanometersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double NanometersPerSecondTolerance { get { return 1e-5; } } - protected virtual double UsSurveyFeetPerHourTolerance { get { return 1e-5; } } - protected virtual double UsSurveyFeetPerMinuteTolerance { get { return 1e-5; } } - protected virtual double UsSurveyFeetPerSecondTolerance { get { return 1e-5; } } - protected virtual double YardsPerHourTolerance { get { return 1e-5; } } - protected virtual double YardsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double YardsPerSecondTolerance { get { return 1e-5; } } + protected virtual double CentimetersPerHourTolerance { get { return 1E-5; } } + protected virtual double CentimetersPerMinutesTolerance { get { return 1E-5; } } + protected virtual double CentimetersPerSecondTolerance { get { return 1E-5; } } + protected virtual double DecimetersPerMinutesTolerance { get { return 1E-5; } } + protected virtual double DecimetersPerSecondTolerance { get { return 1E-5; } } + protected virtual double FeetPerHourTolerance { get { return 1E-5; } } + protected virtual double FeetPerMinuteTolerance { get { return 1E-5; } } + protected virtual double FeetPerSecondTolerance { get { return 1E-5; } } + protected virtual double InchesPerHourTolerance { get { return 1E-5; } } + protected virtual double InchesPerMinuteTolerance { get { return 1E-5; } } + protected virtual double InchesPerSecondTolerance { get { return 1E-5; } } + protected virtual double KilometersPerHourTolerance { get { return 1E-5; } } + protected virtual double KilometersPerMinutesTolerance { get { return 1E-5; } } + protected virtual double KilometersPerSecondTolerance { get { return 1E-5; } } + protected virtual double KnotsTolerance { get { return 1E-5; } } + protected virtual double MetersPerHourTolerance { get { return 1E-5; } } + protected virtual double MetersPerMinutesTolerance { get { return 1E-5; } } + protected virtual double MetersPerSecondTolerance { get { return 1E-5; } } + protected virtual double MicrometersPerMinutesTolerance { get { return 1E-5; } } + protected virtual double MicrometersPerSecondTolerance { get { return 1E-5; } } + protected virtual double MilesPerHourTolerance { get { return 1E-5; } } + protected virtual double MillimetersPerHourTolerance { get { return 1E-5; } } + protected virtual double MillimetersPerMinutesTolerance { get { return 1E-5; } } + protected virtual double MillimetersPerSecondTolerance { get { return 1E-5; } } + protected virtual double NanometersPerMinutesTolerance { get { return 1E-5; } } + protected virtual double NanometersPerSecondTolerance { get { return 1E-5; } } + protected virtual double UsSurveyFeetPerHourTolerance { get { return 1E-5; } } + protected virtual double UsSurveyFeetPerMinuteTolerance { get { return 1E-5; } } + protected virtual double UsSurveyFeetPerSecondTolerance { get { return 1E-5; } } + protected virtual double YardsPerHourTolerance { get { return 1E-5; } } + protected virtual double YardsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double YardsPerSecondTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(SpeedUnit unit) @@ -468,7 +468,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1893,14 +1893,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(SpeedUnit unit) { - var inBaseUnits = Speed.From(1.0, Speed.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Speed.From(1.0, Speed.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Speed.From(1.0, Speed.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(SpeedUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(SpeedUnit unit) @@ -1914,8 +1921,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpeedUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpeedUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Speed.Units.Where(u => u != Speed.BaseUnit).DefaultIfEmpty(Speed.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Speed.Units.First(u => u != Speed.BaseUnit); var quantity = Speed.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2203,8 +2210,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Speed.FromMetersPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -2238,36 +2246,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Speed.FromMetersPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Speed.FromMetersPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Speed.FromMetersPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Speed.FromMetersPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Speed.FromMetersPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -2280,22 +2293,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Speed.FromMetersPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Speed.FromMetersPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Speed.FromMetersPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -2337,7 +2353,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(new {Speed.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Speed.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs index 7dfaf4c928..29b28819d8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs @@ -49,15 +49,15 @@ public abstract partial class StandardVolumeFlowTestsBase : QuantityTestsBase protected abstract double StandardLitersPerMinuteInOneStandardCubicMeterPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double StandardCubicCentimetersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double StandardCubicFeetPerHourTolerance { get { return 1e-5; } } - protected virtual double StandardCubicFeetPerMinuteTolerance { get { return 1e-5; } } - protected virtual double StandardCubicFeetPerSecondTolerance { get { return 1e-5; } } - protected virtual double StandardCubicMetersPerDayTolerance { get { return 1e-5; } } - protected virtual double StandardCubicMetersPerHourTolerance { get { return 1e-5; } } - protected virtual double StandardCubicMetersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double StandardCubicMetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double StandardLitersPerMinuteTolerance { get { return 1e-5; } } + protected virtual double StandardCubicCentimetersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double StandardCubicFeetPerHourTolerance { get { return 1E-5; } } + protected virtual double StandardCubicFeetPerMinuteTolerance { get { return 1E-5; } } + protected virtual double StandardCubicFeetPerSecondTolerance { get { return 1E-5; } } + protected virtual double StandardCubicMetersPerDayTolerance { get { return 1E-5; } } + protected virtual double StandardCubicMetersPerHourTolerance { get { return 1E-5; } } + protected virtual double StandardCubicMetersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double StandardCubicMetersPerSecondTolerance { get { return 1E-5; } } + protected virtual double StandardLitersPerMinuteTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(StandardVolumeFlowUnit unit) @@ -238,7 +238,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -487,14 +487,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(StandardVolumeFlowUnit unit) { - var inBaseUnits = StandardVolumeFlow.From(1.0, StandardVolumeFlow.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = StandardVolumeFlow.From(1.0, StandardVolumeFlow.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = StandardVolumeFlow.From(1.0, StandardVolumeFlow.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(StandardVolumeFlowUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(StandardVolumeFlowUnit unit) @@ -508,8 +515,8 @@ public void ToUnit_WithSameUnits_AreEqual(StandardVolumeFlowUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(StandardVolumeFlowUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = StandardVolumeFlow.Units.Where(u => u != StandardVolumeFlow.BaseUnit).DefaultIfEmpty(StandardVolumeFlow.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = StandardVolumeFlow.Units.First(u => u != StandardVolumeFlow.BaseUnit); var quantity = StandardVolumeFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -728,8 +735,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -763,36 +771,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -805,22 +818,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -862,7 +878,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(new {StandardVolumeFlow.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(StandardVolumeFlow.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs index 6e8098579d..1126f1cbf4 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs @@ -50,16 +50,16 @@ public abstract partial class TemperatureChangeRateTestsBase : QuantityTestsBase protected abstract double NanodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentidegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecadegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecidegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double DegreesCelsiusPerMinuteTolerance { get { return 1e-5; } } - protected virtual double DegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double HectodegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilodegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicrodegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double MillidegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanodegreesCelsiusPerSecondTolerance { get { return 1e-5; } } + protected virtual double CentidegreesCelsiusPerSecondTolerance { get { return 1E-5; } } + protected virtual double DecadegreesCelsiusPerSecondTolerance { get { return 1E-5; } } + protected virtual double DecidegreesCelsiusPerSecondTolerance { get { return 1E-5; } } + protected virtual double DegreesCelsiusPerMinuteTolerance { get { return 1E-5; } } + protected virtual double DegreesCelsiusPerSecondTolerance { get { return 1E-5; } } + protected virtual double HectodegreesCelsiusPerSecondTolerance { get { return 1E-5; } } + protected virtual double KilodegreesCelsiusPerSecondTolerance { get { return 1E-5; } } + protected virtual double MicrodegreesCelsiusPerSecondTolerance { get { return 1E-5; } } + protected virtual double MillidegreesCelsiusPerSecondTolerance { get { return 1E-5; } } + protected virtual double NanodegreesCelsiusPerSecondTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TemperatureChangeRateUnit unit) @@ -248,7 +248,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -521,14 +521,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(TemperatureChangeRateUnit unit) { - var inBaseUnits = TemperatureChangeRate.From(1.0, TemperatureChangeRate.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = TemperatureChangeRate.From(1.0, TemperatureChangeRate.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = TemperatureChangeRate.From(1.0, TemperatureChangeRate.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(TemperatureChangeRateUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(TemperatureChangeRateUnit unit) @@ -542,8 +549,8 @@ public void ToUnit_WithSameUnits_AreEqual(TemperatureChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureChangeRateUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = TemperatureChangeRate.Units.Where(u => u != TemperatureChangeRate.BaseUnit).DefaultIfEmpty(TemperatureChangeRate.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = TemperatureChangeRate.Units.First(u => u != TemperatureChangeRate.BaseUnit); var quantity = TemperatureChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -765,8 +772,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -800,36 +808,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -842,22 +855,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -899,7 +915,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(new {TemperatureChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(TemperatureChangeRate.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs index 7febab8e92..888100c7d5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs @@ -49,15 +49,15 @@ public abstract partial class TemperatureDeltaTestsBase : QuantityTestsBase protected abstract double MillidegreesCelsiusInOneKelvin { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DegreesCelsiusTolerance { get { return 1e-5; } } - protected virtual double DegreesDelisleTolerance { get { return 1e-5; } } - protected virtual double DegreesFahrenheitTolerance { get { return 1e-5; } } - protected virtual double DegreesNewtonTolerance { get { return 1e-5; } } - protected virtual double DegreesRankineTolerance { get { return 1e-5; } } - protected virtual double DegreesReaumurTolerance { get { return 1e-5; } } - protected virtual double DegreesRoemerTolerance { get { return 1e-5; } } - protected virtual double KelvinsTolerance { get { return 1e-5; } } - protected virtual double MillidegreesCelsiusTolerance { get { return 1e-5; } } + protected virtual double DegreesCelsiusTolerance { get { return 1E-5; } } + protected virtual double DegreesDelisleTolerance { get { return 1E-5; } } + protected virtual double DegreesFahrenheitTolerance { get { return 1E-5; } } + protected virtual double DegreesNewtonTolerance { get { return 1E-5; } } + protected virtual double DegreesRankineTolerance { get { return 1E-5; } } + protected virtual double DegreesReaumurTolerance { get { return 1E-5; } } + protected virtual double DegreesRoemerTolerance { get { return 1E-5; } } + protected virtual double KelvinsTolerance { get { return 1E-5; } } + protected virtual double MillidegreesCelsiusTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TemperatureDeltaUnit unit) @@ -238,7 +238,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -487,14 +487,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(TemperatureDeltaUnit unit) { - var inBaseUnits = TemperatureDelta.From(1.0, TemperatureDelta.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = TemperatureDelta.From(1.0, TemperatureDelta.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = TemperatureDelta.From(1.0, TemperatureDelta.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(TemperatureDeltaUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(TemperatureDeltaUnit unit) @@ -508,8 +515,8 @@ public void ToUnit_WithSameUnits_AreEqual(TemperatureDeltaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureDeltaUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = TemperatureDelta.Units.Where(u => u != TemperatureDelta.BaseUnit).DefaultIfEmpty(TemperatureDelta.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = TemperatureDelta.Units.First(u => u != TemperatureDelta.BaseUnit); var quantity = TemperatureDelta.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -728,8 +735,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = TemperatureDelta.FromKelvins(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -763,36 +771,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = TemperatureDelta.FromKelvins(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = TemperatureDelta.FromKelvins(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = TemperatureDelta.FromKelvins(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = TemperatureDelta.FromKelvins(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = TemperatureDelta.FromKelvins(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -805,22 +818,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = TemperatureDelta.FromKelvins(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = TemperatureDelta.FromKelvins(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = TemperatureDelta.FromKelvins(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -862,7 +878,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(new {TemperatureDelta.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(TemperatureDelta.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs index e0a6f79454..6ba368aafa 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs @@ -44,10 +44,10 @@ public abstract partial class TemperatureGradientTestsBase : QuantityTestsBase protected abstract double KelvinsPerMeterInOneKelvinPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DegreesCelciusPerKilometerTolerance { get { return 1e-5; } } - protected virtual double DegreesCelciusPerMeterTolerance { get { return 1e-5; } } - protected virtual double DegreesFahrenheitPerFootTolerance { get { return 1e-5; } } - protected virtual double KelvinsPerMeterTolerance { get { return 1e-5; } } + protected virtual double DegreesCelciusPerKilometerTolerance { get { return 1E-5; } } + protected virtual double DegreesCelciusPerMeterTolerance { get { return 1E-5; } } + protected virtual double DegreesFahrenheitPerFootTolerance { get { return 1E-5; } } + protected virtual double KelvinsPerMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TemperatureGradientUnit unit) @@ -188,7 +188,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -317,14 +317,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(TemperatureGradientUnit unit) { - var inBaseUnits = TemperatureGradient.From(1.0, TemperatureGradient.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = TemperatureGradient.From(1.0, TemperatureGradient.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = TemperatureGradient.From(1.0, TemperatureGradient.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(TemperatureGradientUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(TemperatureGradientUnit unit) @@ -338,8 +345,8 @@ public void ToUnit_WithSameUnits_AreEqual(TemperatureGradientUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureGradientUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = TemperatureGradient.Units.Where(u => u != TemperatureGradient.BaseUnit).DefaultIfEmpty(TemperatureGradient.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = TemperatureGradient.Units.First(u => u != TemperatureGradient.BaseUnit); var quantity = TemperatureGradient.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -543,8 +550,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = TemperatureGradient.FromKelvinsPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -578,36 +586,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = TemperatureGradient.FromKelvinsPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = TemperatureGradient.FromKelvinsPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = TemperatureGradient.FromKelvinsPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = TemperatureGradient.FromKelvinsPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = TemperatureGradient.FromKelvinsPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -620,22 +633,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = TemperatureGradient.FromKelvinsPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = TemperatureGradient.FromKelvinsPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = TemperatureGradient.FromKelvinsPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -677,7 +693,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(new {TemperatureGradient.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(TemperatureGradient.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs index fe54557914..17da2c0e60 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs @@ -50,16 +50,16 @@ public abstract partial class TemperatureTestsBase : QuantityTestsBase protected abstract double SolarTemperaturesInOneKelvin { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DegreesCelsiusTolerance { get { return 1e-5; } } - protected virtual double DegreesDelisleTolerance { get { return 1e-5; } } - protected virtual double DegreesFahrenheitTolerance { get { return 1e-5; } } - protected virtual double DegreesNewtonTolerance { get { return 1e-5; } } - protected virtual double DegreesRankineTolerance { get { return 1e-5; } } - protected virtual double DegreesReaumurTolerance { get { return 1e-5; } } - protected virtual double DegreesRoemerTolerance { get { return 1e-5; } } - protected virtual double KelvinsTolerance { get { return 1e-5; } } - protected virtual double MillidegreesCelsiusTolerance { get { return 1e-5; } } - protected virtual double SolarTemperaturesTolerance { get { return 1e-5; } } + protected virtual double DegreesCelsiusTolerance { get { return 1E-5; } } + protected virtual double DegreesDelisleTolerance { get { return 1E-5; } } + protected virtual double DegreesFahrenheitTolerance { get { return 1E-5; } } + protected virtual double DegreesNewtonTolerance { get { return 1E-5; } } + protected virtual double DegreesRankineTolerance { get { return 1E-5; } } + protected virtual double DegreesReaumurTolerance { get { return 1E-5; } } + protected virtual double DegreesRoemerTolerance { get { return 1E-5; } } + protected virtual double KelvinsTolerance { get { return 1E-5; } } + protected virtual double MillidegreesCelsiusTolerance { get { return 1E-5; } } + protected virtual double SolarTemperaturesTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TemperatureUnit unit) @@ -248,7 +248,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -521,14 +521,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(TemperatureUnit unit) { - var inBaseUnits = Temperature.From(1.0, Temperature.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Temperature.From(1.0, Temperature.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Temperature.From(1.0, Temperature.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(TemperatureUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(TemperatureUnit unit) @@ -542,8 +549,8 @@ public void ToUnit_WithSameUnits_AreEqual(TemperatureUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Temperature.Units.Where(u => u != Temperature.BaseUnit).DefaultIfEmpty(Temperature.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Temperature.Units.First(u => u != Temperature.BaseUnit); var quantity = Temperature.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -753,8 +760,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Temperature.FromKelvins(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -788,36 +796,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Temperature.FromKelvins(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Temperature.FromKelvins(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Temperature.FromKelvins(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Temperature.FromKelvins(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Temperature.FromKelvins(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -830,22 +843,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Temperature.FromKelvins(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Temperature.FromKelvins(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Temperature.FromKelvins(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -887,7 +903,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(new {Temperature.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Temperature.Info.Name.GetHashCode(), quantity.GetHashCode()); } } diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs index f9ba3e2d05..a1e2152df9 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs @@ -42,8 +42,8 @@ public abstract partial class ThermalConductivityTestsBase : QuantityTestsBase protected abstract double WattsPerMeterKelvinInOneWattPerMeterKelvin { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BtusPerHourFootFahrenheitTolerance { get { return 1e-5; } } - protected virtual double WattsPerMeterKelvinTolerance { get { return 1e-5; } } + protected virtual double BtusPerHourFootFahrenheitTolerance { get { return 1E-5; } } + protected virtual double WattsPerMeterKelvinTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ThermalConductivityUnit unit) @@ -168,7 +168,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -249,14 +249,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ThermalConductivityUnit unit) { - var inBaseUnits = ThermalConductivity.From(1.0, ThermalConductivity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ThermalConductivity.From(1.0, ThermalConductivity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ThermalConductivity.From(1.0, ThermalConductivity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ThermalConductivityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ThermalConductivityUnit unit) @@ -270,8 +277,8 @@ public void ToUnit_WithSameUnits_AreEqual(ThermalConductivityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ThermalConductivityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ThermalConductivity.Units.Where(u => u != ThermalConductivity.BaseUnit).DefaultIfEmpty(ThermalConductivity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ThermalConductivity.Units.First(u => u != ThermalConductivity.BaseUnit); var quantity = ThermalConductivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -469,8 +476,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -504,36 +512,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -546,22 +559,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -603,7 +619,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(new {ThermalConductivity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ThermalConductivity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs index 00f985ad3e..00b775c402 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs @@ -46,12 +46,12 @@ public abstract partial class ThermalResistanceTestsBase : QuantityTestsBase protected abstract double SquareMeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double HourSquareFeetDegreesFahrenheitPerBtuTolerance { get { return 1e-5; } } - protected virtual double SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance { get { return 1e-5; } } - protected virtual double SquareCentimeterKelvinsPerWattTolerance { get { return 1e-5; } } - protected virtual double SquareMeterDegreesCelsiusPerWattTolerance { get { return 1e-5; } } - protected virtual double SquareMeterKelvinsPerKilowattTolerance { get { return 1e-5; } } - protected virtual double SquareMeterKelvinsPerWattTolerance { get { return 1e-5; } } + protected virtual double HourSquareFeetDegreesFahrenheitPerBtuTolerance { get { return 1E-5; } } + protected virtual double SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance { get { return 1E-5; } } + protected virtual double SquareCentimeterKelvinsPerWattTolerance { get { return 1E-5; } } + protected virtual double SquareMeterDegreesCelsiusPerWattTolerance { get { return 1E-5; } } + protected virtual double SquareMeterKelvinsPerKilowattTolerance { get { return 1E-5; } } + protected virtual double SquareMeterKelvinsPerWattTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ThermalResistanceUnit unit) @@ -208,7 +208,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -385,14 +385,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(ThermalResistanceUnit unit) { - var inBaseUnits = ThermalResistance.From(1.0, ThermalResistance.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = ThermalResistance.From(1.0, ThermalResistance.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = ThermalResistance.From(1.0, ThermalResistance.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(ThermalResistanceUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(ThermalResistanceUnit unit) @@ -406,8 +413,8 @@ public void ToUnit_WithSameUnits_AreEqual(ThermalResistanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ThermalResistanceUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = ThermalResistance.Units.Where(u => u != ThermalResistance.BaseUnit).DefaultIfEmpty(ThermalResistance.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = ThermalResistance.Units.First(u => u != ThermalResistance.BaseUnit); var quantity = ThermalResistance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -617,8 +624,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -652,36 +660,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -694,22 +707,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -751,7 +767,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(new {ThermalResistance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(ThermalResistance.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs index 4d7495ee03..ca4ffc8708 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs @@ -61,27 +61,27 @@ public abstract partial class TorquePerLengthTestsBase : QuantityTestsBase protected abstract double TonneForceMillimetersPerMeterInOneNewtonMeterPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilogramForceCentimetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramForceMetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramForceMillimetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonCentimetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMillimetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilopoundForceFeetPerFootTolerance { get { return 1e-5; } } - protected virtual double KilopoundForceInchesPerFootTolerance { get { return 1e-5; } } - protected virtual double MeganewtonCentimetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMillimetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double MegapoundForceFeetPerFootTolerance { get { return 1e-5; } } - protected virtual double MegapoundForceInchesPerFootTolerance { get { return 1e-5; } } - protected virtual double NewtonCentimetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonMetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonMillimetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double PoundForceFeetPerFootTolerance { get { return 1e-5; } } - protected virtual double PoundForceInchesPerFootTolerance { get { return 1e-5; } } - protected virtual double TonneForceCentimetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double TonneForceMetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double TonneForceMillimetersPerMeterTolerance { get { return 1e-5; } } + protected virtual double KilogramForceCentimetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramForceMetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilogramForceMillimetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonCentimetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonMetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilonewtonMillimetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double KilopoundForceFeetPerFootTolerance { get { return 1E-5; } } + protected virtual double KilopoundForceInchesPerFootTolerance { get { return 1E-5; } } + protected virtual double MeganewtonCentimetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double MeganewtonMetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double MeganewtonMillimetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double MegapoundForceFeetPerFootTolerance { get { return 1E-5; } } + protected virtual double MegapoundForceInchesPerFootTolerance { get { return 1E-5; } } + protected virtual double NewtonCentimetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double NewtonMetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double NewtonMillimetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double PoundForceFeetPerFootTolerance { get { return 1E-5; } } + protected virtual double PoundForceInchesPerFootTolerance { get { return 1E-5; } } + protected virtual double TonneForceCentimetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double TonneForceMetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double TonneForceMillimetersPerMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TorquePerLengthUnit unit) @@ -358,7 +358,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -967,14 +967,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(TorquePerLengthUnit unit) { - var inBaseUnits = TorquePerLength.From(1.0, TorquePerLength.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = TorquePerLength.From(1.0, TorquePerLength.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = TorquePerLength.From(1.0, TorquePerLength.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(TorquePerLengthUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(TorquePerLengthUnit unit) @@ -988,8 +995,8 @@ public void ToUnit_WithSameUnits_AreEqual(TorquePerLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TorquePerLengthUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = TorquePerLength.Units.Where(u => u != TorquePerLength.BaseUnit).DefaultIfEmpty(TorquePerLength.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = TorquePerLength.Units.First(u => u != TorquePerLength.BaseUnit); var quantity = TorquePerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1244,8 +1251,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = TorquePerLength.FromNewtonMetersPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1279,36 +1287,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = TorquePerLength.FromNewtonMetersPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = TorquePerLength.FromNewtonMetersPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = TorquePerLength.FromNewtonMetersPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = TorquePerLength.FromNewtonMetersPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = TorquePerLength.FromNewtonMetersPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1321,22 +1334,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = TorquePerLength.FromNewtonMetersPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = TorquePerLength.FromNewtonMetersPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = TorquePerLength.FromNewtonMetersPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1378,7 +1394,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal(new {TorquePerLength.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(TorquePerLength.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs index 322306450f..803d7bce5a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs @@ -65,31 +65,31 @@ public abstract partial class TorqueTestsBase : QuantityTestsBase protected abstract double TonneForceMillimetersInOneNewtonMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramForceCentimetersTolerance { get { return 1e-5; } } - protected virtual double GramForceMetersTolerance { get { return 1e-5; } } - protected virtual double GramForceMillimetersTolerance { get { return 1e-5; } } - protected virtual double KilogramForceCentimetersTolerance { get { return 1e-5; } } - protected virtual double KilogramForceMetersTolerance { get { return 1e-5; } } - protected virtual double KilogramForceMillimetersTolerance { get { return 1e-5; } } - protected virtual double KilonewtonCentimetersTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMetersTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMillimetersTolerance { get { return 1e-5; } } - protected virtual double KilopoundForceFeetTolerance { get { return 1e-5; } } - protected virtual double KilopoundForceInchesTolerance { get { return 1e-5; } } - protected virtual double MeganewtonCentimetersTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMetersTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMillimetersTolerance { get { return 1e-5; } } - protected virtual double MegapoundForceFeetTolerance { get { return 1e-5; } } - protected virtual double MegapoundForceInchesTolerance { get { return 1e-5; } } - protected virtual double NewtonCentimetersTolerance { get { return 1e-5; } } - protected virtual double NewtonMetersTolerance { get { return 1e-5; } } - protected virtual double NewtonMillimetersTolerance { get { return 1e-5; } } - protected virtual double PoundalFeetTolerance { get { return 1e-5; } } - protected virtual double PoundForceFeetTolerance { get { return 1e-5; } } - protected virtual double PoundForceInchesTolerance { get { return 1e-5; } } - protected virtual double TonneForceCentimetersTolerance { get { return 1e-5; } } - protected virtual double TonneForceMetersTolerance { get { return 1e-5; } } - protected virtual double TonneForceMillimetersTolerance { get { return 1e-5; } } + protected virtual double GramForceCentimetersTolerance { get { return 1E-5; } } + protected virtual double GramForceMetersTolerance { get { return 1E-5; } } + protected virtual double GramForceMillimetersTolerance { get { return 1E-5; } } + protected virtual double KilogramForceCentimetersTolerance { get { return 1E-5; } } + protected virtual double KilogramForceMetersTolerance { get { return 1E-5; } } + protected virtual double KilogramForceMillimetersTolerance { get { return 1E-5; } } + protected virtual double KilonewtonCentimetersTolerance { get { return 1E-5; } } + protected virtual double KilonewtonMetersTolerance { get { return 1E-5; } } + protected virtual double KilonewtonMillimetersTolerance { get { return 1E-5; } } + protected virtual double KilopoundForceFeetTolerance { get { return 1E-5; } } + protected virtual double KilopoundForceInchesTolerance { get { return 1E-5; } } + protected virtual double MeganewtonCentimetersTolerance { get { return 1E-5; } } + protected virtual double MeganewtonMetersTolerance { get { return 1E-5; } } + protected virtual double MeganewtonMillimetersTolerance { get { return 1E-5; } } + protected virtual double MegapoundForceFeetTolerance { get { return 1E-5; } } + protected virtual double MegapoundForceInchesTolerance { get { return 1E-5; } } + protected virtual double NewtonCentimetersTolerance { get { return 1E-5; } } + protected virtual double NewtonMetersTolerance { get { return 1E-5; } } + protected virtual double NewtonMillimetersTolerance { get { return 1E-5; } } + protected virtual double PoundalFeetTolerance { get { return 1E-5; } } + protected virtual double PoundForceFeetTolerance { get { return 1E-5; } } + protected virtual double PoundForceInchesTolerance { get { return 1E-5; } } + protected virtual double TonneForceCentimetersTolerance { get { return 1E-5; } } + protected virtual double TonneForceMetersTolerance { get { return 1E-5; } } + protected virtual double TonneForceMillimetersTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TorqueUnit unit) @@ -398,7 +398,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -1103,14 +1103,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(TorqueUnit unit) { - var inBaseUnits = Torque.From(1.0, Torque.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Torque.From(1.0, Torque.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Torque.From(1.0, Torque.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(TorqueUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(TorqueUnit unit) @@ -1124,8 +1131,8 @@ public void ToUnit_WithSameUnits_AreEqual(TorqueUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TorqueUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Torque.Units.Where(u => u != Torque.BaseUnit).DefaultIfEmpty(Torque.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Torque.Units.First(u => u != Torque.BaseUnit); var quantity = Torque.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1392,8 +1399,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Torque.FromNewtonMeters(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1427,36 +1435,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Torque.FromNewtonMeters(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Torque.FromNewtonMeters(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Torque.FromNewtonMeters(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Torque.FromNewtonMeters(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Torque.FromNewtonMeters(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1469,22 +1482,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Torque.FromNewtonMeters(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Torque.FromNewtonMeters(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Torque.FromNewtonMeters(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1526,7 +1542,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(new {Torque.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Torque.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs index 65fd4b5012..c7fec73200 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class TurbidityTestsBase : QuantityTestsBase protected abstract double NTUInOneNTU { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double NTUTolerance { get { return 1e-5; } } + protected virtual double NTUTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(TurbidityUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(TurbidityUnit unit) { - var inBaseUnits = Turbidity.From(1.0, Turbidity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Turbidity.From(1.0, Turbidity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Turbidity.From(1.0, Turbidity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(TurbidityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(TurbidityUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(TurbidityUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TurbidityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Turbidity.Units.Where(u => u != Turbidity.BaseUnit).DefaultIfEmpty(Turbidity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Turbidity.Units.First(u => u != Turbidity.BaseUnit); var quantity = Turbidity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Turbidity.FromNTU(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Turbidity.FromNTU(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Turbidity.FromNTU(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Turbidity.FromNTU(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Turbidity.FromNTU(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Turbidity.FromNTU(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Turbidity.FromNTU(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Turbidity.FromNTU(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Turbidity.FromNTU(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(new {Turbidity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Turbidity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs index 36661f561c..b08943ff4b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs @@ -41,7 +41,7 @@ public abstract partial class VitaminATestsBase : QuantityTestsBase protected abstract double InternationalUnitsInOneInternationalUnit { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double InternationalUnitsTolerance { get { return 1e-5; } } + protected virtual double InternationalUnitsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VitaminAUnit unit) @@ -158,7 +158,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -215,14 +215,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(VitaminAUnit unit) { - var inBaseUnits = VitaminA.From(1.0, VitaminA.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = VitaminA.From(1.0, VitaminA.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = VitaminA.From(1.0, VitaminA.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(VitaminAUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(VitaminAUnit unit) @@ -232,12 +239,12 @@ public void ToUnit_WithSameUnits_AreEqual(VitaminAUnit unit) Assert.Equal(quantity, toUnitWithSameUnit); } - [Theory] + [Theory(Skip = "Multiple units required")] [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VitaminAUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = VitaminA.Units.Where(u => u != VitaminA.BaseUnit).DefaultIfEmpty(VitaminA.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = VitaminA.Units.First(u => u != VitaminA.BaseUnit); var quantity = VitaminA.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -432,8 +439,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = VitaminA.FromInternationalUnits(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -467,36 +475,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = VitaminA.FromInternationalUnits(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = VitaminA.FromInternationalUnits(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = VitaminA.FromInternationalUnits(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = VitaminA.FromInternationalUnits(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = VitaminA.FromInternationalUnits(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -509,22 +522,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = VitaminA.FromInternationalUnits(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = VitaminA.FromInternationalUnits(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = VitaminA.FromInternationalUnits(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -566,7 +582,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(new {VitaminA.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(VitaminA.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs index d807ec47aa..4367e649aa 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs @@ -60,26 +60,26 @@ public abstract partial class VolumeConcentrationTestsBase : QuantityTestsBase protected abstract double PicolitersPerMililiterInOneDecimalFraction { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentilitersPerLiterTolerance { get { return 1e-5; } } - protected virtual double CentilitersPerMililiterTolerance { get { return 1e-5; } } - protected virtual double DecilitersPerLiterTolerance { get { return 1e-5; } } - protected virtual double DecilitersPerMililiterTolerance { get { return 1e-5; } } - protected virtual double DecimalFractionsTolerance { get { return 1e-5; } } - protected virtual double LitersPerLiterTolerance { get { return 1e-5; } } - protected virtual double LitersPerMililiterTolerance { get { return 1e-5; } } - protected virtual double MicrolitersPerLiterTolerance { get { return 1e-5; } } - protected virtual double MicrolitersPerMililiterTolerance { get { return 1e-5; } } - protected virtual double MillilitersPerLiterTolerance { get { return 1e-5; } } - protected virtual double MillilitersPerMililiterTolerance { get { return 1e-5; } } - protected virtual double NanolitersPerLiterTolerance { get { return 1e-5; } } - protected virtual double NanolitersPerMililiterTolerance { get { return 1e-5; } } - protected virtual double PartsPerBillionTolerance { get { return 1e-5; } } - protected virtual double PartsPerMillionTolerance { get { return 1e-5; } } - protected virtual double PartsPerThousandTolerance { get { return 1e-5; } } - protected virtual double PartsPerTrillionTolerance { get { return 1e-5; } } - protected virtual double PercentTolerance { get { return 1e-5; } } - protected virtual double PicolitersPerLiterTolerance { get { return 1e-5; } } - protected virtual double PicolitersPerMililiterTolerance { get { return 1e-5; } } + protected virtual double CentilitersPerLiterTolerance { get { return 1E-5; } } + protected virtual double CentilitersPerMililiterTolerance { get { return 1E-5; } } + protected virtual double DecilitersPerLiterTolerance { get { return 1E-5; } } + protected virtual double DecilitersPerMililiterTolerance { get { return 1E-5; } } + protected virtual double DecimalFractionsTolerance { get { return 1E-5; } } + protected virtual double LitersPerLiterTolerance { get { return 1E-5; } } + protected virtual double LitersPerMililiterTolerance { get { return 1E-5; } } + protected virtual double MicrolitersPerLiterTolerance { get { return 1E-5; } } + protected virtual double MicrolitersPerMililiterTolerance { get { return 1E-5; } } + protected virtual double MillilitersPerLiterTolerance { get { return 1E-5; } } + protected virtual double MillilitersPerMililiterTolerance { get { return 1E-5; } } + protected virtual double NanolitersPerLiterTolerance { get { return 1E-5; } } + protected virtual double NanolitersPerMililiterTolerance { get { return 1E-5; } } + protected virtual double PartsPerBillionTolerance { get { return 1E-5; } } + protected virtual double PartsPerMillionTolerance { get { return 1E-5; } } + protected virtual double PartsPerThousandTolerance { get { return 1E-5; } } + protected virtual double PartsPerTrillionTolerance { get { return 1E-5; } } + protected virtual double PercentTolerance { get { return 1E-5; } } + protected virtual double PicolitersPerLiterTolerance { get { return 1E-5; } } + protected virtual double PicolitersPerMililiterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumeConcentrationUnit unit) @@ -348,7 +348,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -885,14 +885,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(VolumeConcentrationUnit unit) { - var inBaseUnits = VolumeConcentration.From(1.0, VolumeConcentration.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = VolumeConcentration.From(1.0, VolumeConcentration.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = VolumeConcentration.From(1.0, VolumeConcentration.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(VolumeConcentrationUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(VolumeConcentrationUnit unit) @@ -906,8 +913,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumeConcentrationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeConcentrationUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = VolumeConcentration.Units.Where(u => u != VolumeConcentration.BaseUnit).DefaultIfEmpty(VolumeConcentration.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = VolumeConcentration.Units.First(u => u != VolumeConcentration.BaseUnit); var quantity = VolumeConcentration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1159,8 +1166,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = VolumeConcentration.FromDecimalFractions(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -1194,36 +1202,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = VolumeConcentration.FromDecimalFractions(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = VolumeConcentration.FromDecimalFractions(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = VolumeConcentration.FromDecimalFractions(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = VolumeConcentration.FromDecimalFractions(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = VolumeConcentration.FromDecimalFractions(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -1236,22 +1249,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = VolumeConcentration.FromDecimalFractions(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = VolumeConcentration.FromDecimalFractions(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = VolumeConcentration.FromDecimalFractions(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -1293,7 +1309,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(new {VolumeConcentration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(VolumeConcentration.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs index 722f63a1d7..918eab8558 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs @@ -42,8 +42,8 @@ public abstract partial class VolumeFlowPerAreaTestsBase : QuantityTestsBase protected abstract double CubicMetersPerSecondPerSquareMeterInOneCubicMeterPerSecondPerSquareMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CubicFeetPerMinutePerSquareFootTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerSecondPerSquareMeterTolerance { get { return 1e-5; } } + protected virtual double CubicFeetPerMinutePerSquareFootTolerance { get { return 1E-5; } } + protected virtual double CubicMetersPerSecondPerSquareMeterTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumeFlowPerAreaUnit unit) @@ -168,7 +168,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -249,14 +249,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(VolumeFlowPerAreaUnit unit) { - var inBaseUnits = VolumeFlowPerArea.From(1.0, VolumeFlowPerArea.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = VolumeFlowPerArea.From(1.0, VolumeFlowPerArea.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = VolumeFlowPerArea.From(1.0, VolumeFlowPerArea.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(VolumeFlowPerAreaUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(VolumeFlowPerAreaUnit unit) @@ -270,8 +277,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumeFlowPerAreaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeFlowPerAreaUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = VolumeFlowPerArea.Units.Where(u => u != VolumeFlowPerArea.BaseUnit).DefaultIfEmpty(VolumeFlowPerArea.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = VolumeFlowPerArea.Units.First(u => u != VolumeFlowPerArea.BaseUnit); var quantity = VolumeFlowPerArea.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -469,8 +476,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -504,36 +512,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -546,22 +559,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -603,7 +619,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(new {VolumeFlowPerArea.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(VolumeFlowPerArea.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs index caf0e209b2..7a84a2581a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs @@ -102,68 +102,68 @@ public abstract partial class VolumeFlowTestsBase : QuantityTestsBase protected abstract double UsGallonsPerSecondInOneCubicMeterPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AcreFeetPerDayTolerance { get { return 1e-5; } } - protected virtual double AcreFeetPerHourTolerance { get { return 1e-5; } } - protected virtual double AcreFeetPerMinuteTolerance { get { return 1e-5; } } - protected virtual double AcreFeetPerSecondTolerance { get { return 1e-5; } } - protected virtual double CentilitersPerDayTolerance { get { return 1e-5; } } - protected virtual double CentilitersPerHourTolerance { get { return 1e-5; } } - protected virtual double CentilitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CentilitersPerSecondTolerance { get { return 1e-5; } } - protected virtual double CubicCentimetersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicDecimetersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicFeetPerHourTolerance { get { return 1e-5; } } - protected virtual double CubicFeetPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicFeetPerSecondTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerDayTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerHourTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double CubicMillimetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double CubicYardsPerDayTolerance { get { return 1e-5; } } - protected virtual double CubicYardsPerHourTolerance { get { return 1e-5; } } - protected virtual double CubicYardsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicYardsPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecilitersPerDayTolerance { get { return 1e-5; } } - protected virtual double DecilitersPerHourTolerance { get { return 1e-5; } } - protected virtual double DecilitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double DecilitersPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilolitersPerDayTolerance { get { return 1e-5; } } - protected virtual double KilolitersPerHourTolerance { get { return 1e-5; } } - protected virtual double KilolitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double KilolitersPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilousGallonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double LitersPerDayTolerance { get { return 1e-5; } } - protected virtual double LitersPerHourTolerance { get { return 1e-5; } } - protected virtual double LitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double LitersPerSecondTolerance { get { return 1e-5; } } - protected virtual double MegalitersPerDayTolerance { get { return 1e-5; } } - protected virtual double MegaukGallonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicrolitersPerDayTolerance { get { return 1e-5; } } - protected virtual double MicrolitersPerHourTolerance { get { return 1e-5; } } - protected virtual double MicrolitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double MicrolitersPerSecondTolerance { get { return 1e-5; } } - protected virtual double MillilitersPerDayTolerance { get { return 1e-5; } } - protected virtual double MillilitersPerHourTolerance { get { return 1e-5; } } - protected virtual double MillilitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double MillilitersPerSecondTolerance { get { return 1e-5; } } - protected virtual double MillionUsGallonsPerDayTolerance { get { return 1e-5; } } - protected virtual double NanolitersPerDayTolerance { get { return 1e-5; } } - protected virtual double NanolitersPerHourTolerance { get { return 1e-5; } } - protected virtual double NanolitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double NanolitersPerSecondTolerance { get { return 1e-5; } } - protected virtual double OilBarrelsPerDayTolerance { get { return 1e-5; } } - protected virtual double OilBarrelsPerHourTolerance { get { return 1e-5; } } - protected virtual double OilBarrelsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double OilBarrelsPerSecondTolerance { get { return 1e-5; } } - protected virtual double UkGallonsPerDayTolerance { get { return 1e-5; } } - protected virtual double UkGallonsPerHourTolerance { get { return 1e-5; } } - protected virtual double UkGallonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double UkGallonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double UsGallonsPerDayTolerance { get { return 1e-5; } } - protected virtual double UsGallonsPerHourTolerance { get { return 1e-5; } } - protected virtual double UsGallonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double UsGallonsPerSecondTolerance { get { return 1e-5; } } + protected virtual double AcreFeetPerDayTolerance { get { return 1E-5; } } + protected virtual double AcreFeetPerHourTolerance { get { return 1E-5; } } + protected virtual double AcreFeetPerMinuteTolerance { get { return 1E-5; } } + protected virtual double AcreFeetPerSecondTolerance { get { return 1E-5; } } + protected virtual double CentilitersPerDayTolerance { get { return 1E-5; } } + protected virtual double CentilitersPerHourTolerance { get { return 1E-5; } } + protected virtual double CentilitersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double CentilitersPerSecondTolerance { get { return 1E-5; } } + protected virtual double CubicCentimetersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double CubicDecimetersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double CubicFeetPerHourTolerance { get { return 1E-5; } } + protected virtual double CubicFeetPerMinuteTolerance { get { return 1E-5; } } + protected virtual double CubicFeetPerSecondTolerance { get { return 1E-5; } } + protected virtual double CubicMetersPerDayTolerance { get { return 1E-5; } } + protected virtual double CubicMetersPerHourTolerance { get { return 1E-5; } } + protected virtual double CubicMetersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double CubicMetersPerSecondTolerance { get { return 1E-5; } } + protected virtual double CubicMillimetersPerSecondTolerance { get { return 1E-5; } } + protected virtual double CubicYardsPerDayTolerance { get { return 1E-5; } } + protected virtual double CubicYardsPerHourTolerance { get { return 1E-5; } } + protected virtual double CubicYardsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double CubicYardsPerSecondTolerance { get { return 1E-5; } } + protected virtual double DecilitersPerDayTolerance { get { return 1E-5; } } + protected virtual double DecilitersPerHourTolerance { get { return 1E-5; } } + protected virtual double DecilitersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double DecilitersPerSecondTolerance { get { return 1E-5; } } + protected virtual double KilolitersPerDayTolerance { get { return 1E-5; } } + protected virtual double KilolitersPerHourTolerance { get { return 1E-5; } } + protected virtual double KilolitersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double KilolitersPerSecondTolerance { get { return 1E-5; } } + protected virtual double KilousGallonsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double LitersPerDayTolerance { get { return 1E-5; } } + protected virtual double LitersPerHourTolerance { get { return 1E-5; } } + protected virtual double LitersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double LitersPerSecondTolerance { get { return 1E-5; } } + protected virtual double MegalitersPerDayTolerance { get { return 1E-5; } } + protected virtual double MegaukGallonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double MicrolitersPerDayTolerance { get { return 1E-5; } } + protected virtual double MicrolitersPerHourTolerance { get { return 1E-5; } } + protected virtual double MicrolitersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double MicrolitersPerSecondTolerance { get { return 1E-5; } } + protected virtual double MillilitersPerDayTolerance { get { return 1E-5; } } + protected virtual double MillilitersPerHourTolerance { get { return 1E-5; } } + protected virtual double MillilitersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double MillilitersPerSecondTolerance { get { return 1E-5; } } + protected virtual double MillionUsGallonsPerDayTolerance { get { return 1E-5; } } + protected virtual double NanolitersPerDayTolerance { get { return 1E-5; } } + protected virtual double NanolitersPerHourTolerance { get { return 1E-5; } } + protected virtual double NanolitersPerMinuteTolerance { get { return 1E-5; } } + protected virtual double NanolitersPerSecondTolerance { get { return 1E-5; } } + protected virtual double OilBarrelsPerDayTolerance { get { return 1E-5; } } + protected virtual double OilBarrelsPerHourTolerance { get { return 1E-5; } } + protected virtual double OilBarrelsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double OilBarrelsPerSecondTolerance { get { return 1E-5; } } + protected virtual double UkGallonsPerDayTolerance { get { return 1E-5; } } + protected virtual double UkGallonsPerHourTolerance { get { return 1E-5; } } + protected virtual double UkGallonsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double UkGallonsPerSecondTolerance { get { return 1E-5; } } + protected virtual double UsGallonsPerDayTolerance { get { return 1E-5; } } + protected virtual double UsGallonsPerHourTolerance { get { return 1E-5; } } + protected virtual double UsGallonsPerMinuteTolerance { get { return 1E-5; } } + protected virtual double UsGallonsPerSecondTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumeFlowUnit unit) @@ -768,7 +768,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -3951,14 +3951,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(VolumeFlowUnit unit) { - var inBaseUnits = VolumeFlow.From(1.0, VolumeFlow.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = VolumeFlow.From(1.0, VolumeFlow.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = VolumeFlow.From(1.0, VolumeFlow.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(VolumeFlowUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(VolumeFlowUnit unit) @@ -3972,8 +3979,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumeFlowUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeFlowUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = VolumeFlow.Units.Where(u => u != VolumeFlow.BaseUnit).DefaultIfEmpty(VolumeFlow.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = VolumeFlow.Units.First(u => u != VolumeFlow.BaseUnit); var quantity = VolumeFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -4351,8 +4358,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = VolumeFlow.FromCubicMetersPerSecond(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -4386,36 +4394,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = VolumeFlow.FromCubicMetersPerSecond(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = VolumeFlow.FromCubicMetersPerSecond(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = VolumeFlow.FromCubicMetersPerSecond(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = VolumeFlow.FromCubicMetersPerSecond(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = VolumeFlow.FromCubicMetersPerSecond(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -4428,22 +4441,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = VolumeFlow.FromCubicMetersPerSecond(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = VolumeFlow.FromCubicMetersPerSecond(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = VolumeFlow.FromCubicMetersPerSecond(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -4485,7 +4501,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(new {VolumeFlow.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(VolumeFlow.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs index 98f4ce00c7..ca1a1da646 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs @@ -47,13 +47,13 @@ public abstract partial class VolumePerLengthTestsBase : QuantityTestsBase protected abstract double OilBarrelsPerFootInOneCubicMeterPerMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CubicMetersPerMeterTolerance { get { return 1e-5; } } - protected virtual double CubicYardsPerFootTolerance { get { return 1e-5; } } - protected virtual double CubicYardsPerUsSurveyFootTolerance { get { return 1e-5; } } - protected virtual double LitersPerKilometerTolerance { get { return 1e-5; } } - protected virtual double LitersPerMeterTolerance { get { return 1e-5; } } - protected virtual double LitersPerMillimeterTolerance { get { return 1e-5; } } - protected virtual double OilBarrelsPerFootTolerance { get { return 1e-5; } } + protected virtual double CubicMetersPerMeterTolerance { get { return 1E-5; } } + protected virtual double CubicYardsPerFootTolerance { get { return 1E-5; } } + protected virtual double CubicYardsPerUsSurveyFootTolerance { get { return 1E-5; } } + protected virtual double LitersPerKilometerTolerance { get { return 1E-5; } } + protected virtual double LitersPerMeterTolerance { get { return 1E-5; } } + protected virtual double LitersPerMillimeterTolerance { get { return 1E-5; } } + protected virtual double OilBarrelsPerFootTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumePerLengthUnit unit) @@ -218,7 +218,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -419,14 +419,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(VolumePerLengthUnit unit) { - var inBaseUnits = VolumePerLength.From(1.0, VolumePerLength.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = VolumePerLength.From(1.0, VolumePerLength.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = VolumePerLength.From(1.0, VolumePerLength.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(VolumePerLengthUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(VolumePerLengthUnit unit) @@ -440,8 +447,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumePerLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumePerLengthUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = VolumePerLength.Units.Where(u => u != VolumePerLength.BaseUnit).DefaultIfEmpty(VolumePerLength.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = VolumePerLength.Units.First(u => u != VolumePerLength.BaseUnit); var quantity = VolumePerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -654,8 +661,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = VolumePerLength.FromCubicMetersPerMeter(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -689,36 +697,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = VolumePerLength.FromCubicMetersPerMeter(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = VolumePerLength.FromCubicMetersPerMeter(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = VolumePerLength.FromCubicMetersPerMeter(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = VolumePerLength.FromCubicMetersPerMeter(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = VolumePerLength.FromCubicMetersPerMeter(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -731,22 +744,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = VolumePerLength.FromCubicMetersPerMeter(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = VolumePerLength.FromCubicMetersPerMeter(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = VolumePerLength.FromCubicMetersPerMeter(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -788,7 +804,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(new {VolumePerLength.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(VolumePerLength.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs index 4447d491b4..2828a5de16 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs @@ -92,58 +92,58 @@ public abstract partial class VolumeTestsBase : QuantityTestsBase protected abstract double UsTeaspoonsInOneCubicMeter { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AcreFeetTolerance { get { return 1e-5; } } - protected virtual double AuTablespoonsTolerance { get { return 1e-5; } } - protected virtual double BoardFeetTolerance { get { return 1e-5; } } - protected virtual double CentilitersTolerance { get { return 1e-5; } } - protected virtual double CubicCentimetersTolerance { get { return 1e-5; } } - protected virtual double CubicDecimetersTolerance { get { return 1e-5; } } - protected virtual double CubicFeetTolerance { get { return 1e-5; } } - protected virtual double CubicHectometersTolerance { get { return 1e-5; } } - protected virtual double CubicInchesTolerance { get { return 1e-5; } } - protected virtual double CubicKilometersTolerance { get { return 1e-5; } } - protected virtual double CubicMetersTolerance { get { return 1e-5; } } - protected virtual double CubicMicrometersTolerance { get { return 1e-5; } } - protected virtual double CubicMilesTolerance { get { return 1e-5; } } - protected virtual double CubicMillimetersTolerance { get { return 1e-5; } } - protected virtual double CubicYardsTolerance { get { return 1e-5; } } - protected virtual double DecalitersTolerance { get { return 1e-5; } } - protected virtual double DecausGallonsTolerance { get { return 1e-5; } } - protected virtual double DecilitersTolerance { get { return 1e-5; } } - protected virtual double DeciusGallonsTolerance { get { return 1e-5; } } - protected virtual double HectocubicFeetTolerance { get { return 1e-5; } } - protected virtual double HectocubicMetersTolerance { get { return 1e-5; } } - protected virtual double HectolitersTolerance { get { return 1e-5; } } - protected virtual double HectousGallonsTolerance { get { return 1e-5; } } - protected virtual double ImperialBeerBarrelsTolerance { get { return 1e-5; } } - protected virtual double ImperialGallonsTolerance { get { return 1e-5; } } - protected virtual double ImperialOuncesTolerance { get { return 1e-5; } } - protected virtual double ImperialPintsTolerance { get { return 1e-5; } } - protected virtual double KilocubicFeetTolerance { get { return 1e-5; } } - protected virtual double KilocubicMetersTolerance { get { return 1e-5; } } - protected virtual double KiloimperialGallonsTolerance { get { return 1e-5; } } - protected virtual double KilolitersTolerance { get { return 1e-5; } } - protected virtual double KilousGallonsTolerance { get { return 1e-5; } } - protected virtual double LitersTolerance { get { return 1e-5; } } - protected virtual double MegacubicFeetTolerance { get { return 1e-5; } } - protected virtual double MegaimperialGallonsTolerance { get { return 1e-5; } } - protected virtual double MegalitersTolerance { get { return 1e-5; } } - protected virtual double MegausGallonsTolerance { get { return 1e-5; } } - protected virtual double MetricCupsTolerance { get { return 1e-5; } } - protected virtual double MetricTeaspoonsTolerance { get { return 1e-5; } } - protected virtual double MicrolitersTolerance { get { return 1e-5; } } - protected virtual double MillilitersTolerance { get { return 1e-5; } } - protected virtual double OilBarrelsTolerance { get { return 1e-5; } } - protected virtual double UkTablespoonsTolerance { get { return 1e-5; } } - protected virtual double UsBeerBarrelsTolerance { get { return 1e-5; } } - protected virtual double UsCustomaryCupsTolerance { get { return 1e-5; } } - protected virtual double UsGallonsTolerance { get { return 1e-5; } } - protected virtual double UsLegalCupsTolerance { get { return 1e-5; } } - protected virtual double UsOuncesTolerance { get { return 1e-5; } } - protected virtual double UsPintsTolerance { get { return 1e-5; } } - protected virtual double UsQuartsTolerance { get { return 1e-5; } } - protected virtual double UsTablespoonsTolerance { get { return 1e-5; } } - protected virtual double UsTeaspoonsTolerance { get { return 1e-5; } } + protected virtual double AcreFeetTolerance { get { return 1E-5; } } + protected virtual double AuTablespoonsTolerance { get { return 1E-5; } } + protected virtual double BoardFeetTolerance { get { return 1E-5; } } + protected virtual double CentilitersTolerance { get { return 1E-5; } } + protected virtual double CubicCentimetersTolerance { get { return 1E-5; } } + protected virtual double CubicDecimetersTolerance { get { return 1E-5; } } + protected virtual double CubicFeetTolerance { get { return 1E-5; } } + protected virtual double CubicHectometersTolerance { get { return 1E-5; } } + protected virtual double CubicInchesTolerance { get { return 1E-5; } } + protected virtual double CubicKilometersTolerance { get { return 1E-5; } } + protected virtual double CubicMetersTolerance { get { return 1E-5; } } + protected virtual double CubicMicrometersTolerance { get { return 1E-5; } } + protected virtual double CubicMilesTolerance { get { return 1E-5; } } + protected virtual double CubicMillimetersTolerance { get { return 1E-5; } } + protected virtual double CubicYardsTolerance { get { return 1E-5; } } + protected virtual double DecalitersTolerance { get { return 1E-5; } } + protected virtual double DecausGallonsTolerance { get { return 1E-5; } } + protected virtual double DecilitersTolerance { get { return 1E-5; } } + protected virtual double DeciusGallonsTolerance { get { return 1E-5; } } + protected virtual double HectocubicFeetTolerance { get { return 1E-5; } } + protected virtual double HectocubicMetersTolerance { get { return 1E-5; } } + protected virtual double HectolitersTolerance { get { return 1E-5; } } + protected virtual double HectousGallonsTolerance { get { return 1E-5; } } + protected virtual double ImperialBeerBarrelsTolerance { get { return 1E-5; } } + protected virtual double ImperialGallonsTolerance { get { return 1E-5; } } + protected virtual double ImperialOuncesTolerance { get { return 1E-5; } } + protected virtual double ImperialPintsTolerance { get { return 1E-5; } } + protected virtual double KilocubicFeetTolerance { get { return 1E-5; } } + protected virtual double KilocubicMetersTolerance { get { return 1E-5; } } + protected virtual double KiloimperialGallonsTolerance { get { return 1E-5; } } + protected virtual double KilolitersTolerance { get { return 1E-5; } } + protected virtual double KilousGallonsTolerance { get { return 1E-5; } } + protected virtual double LitersTolerance { get { return 1E-5; } } + protected virtual double MegacubicFeetTolerance { get { return 1E-5; } } + protected virtual double MegaimperialGallonsTolerance { get { return 1E-5; } } + protected virtual double MegalitersTolerance { get { return 1E-5; } } + protected virtual double MegausGallonsTolerance { get { return 1E-5; } } + protected virtual double MetricCupsTolerance { get { return 1E-5; } } + protected virtual double MetricTeaspoonsTolerance { get { return 1E-5; } } + protected virtual double MicrolitersTolerance { get { return 1E-5; } } + protected virtual double MillilitersTolerance { get { return 1E-5; } } + protected virtual double OilBarrelsTolerance { get { return 1E-5; } } + protected virtual double UkTablespoonsTolerance { get { return 1E-5; } } + protected virtual double UsBeerBarrelsTolerance { get { return 1E-5; } } + protected virtual double UsCustomaryCupsTolerance { get { return 1E-5; } } + protected virtual double UsGallonsTolerance { get { return 1E-5; } } + protected virtual double UsLegalCupsTolerance { get { return 1E-5; } } + protected virtual double UsOuncesTolerance { get { return 1E-5; } } + protected virtual double UsPintsTolerance { get { return 1E-5; } } + protected virtual double UsQuartsTolerance { get { return 1E-5; } } + protected virtual double UsTablespoonsTolerance { get { return 1E-5; } } + protected virtual double UsTeaspoonsTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumeUnit unit) @@ -668,7 +668,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -2945,14 +2945,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(VolumeUnit unit) { - var inBaseUnits = Volume.From(1.0, Volume.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = Volume.From(1.0, Volume.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = Volume.From(1.0, Volume.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(VolumeUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(VolumeUnit unit) @@ -2966,8 +2973,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumeUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = Volume.Units.Where(u => u != Volume.BaseUnit).DefaultIfEmpty(Volume.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = Volume.Units.First(u => u != Volume.BaseUnit); var quantity = Volume.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -3315,8 +3322,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = Volume.FromCubicMeters(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -3350,36 +3358,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = Volume.FromCubicMeters(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = Volume.FromCubicMeters(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = Volume.FromCubicMeters(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = Volume.FromCubicMeters(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = Volume.FromCubicMeters(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -3392,22 +3405,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = Volume.FromCubicMeters(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = Volume.FromCubicMeters(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = Volume.FromCubicMeters(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -3449,7 +3465,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(new {Volume.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(Volume.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs index 030c251bde..6c205dcb92 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs @@ -49,15 +49,15 @@ public abstract partial class VolumetricHeatCapacityTestsBase : QuantityTestsBas protected abstract double MegajoulesPerCubicMeterKelvinInOneJoulePerCubicMeterKelvin { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BtusPerCubicFootDegreeFahrenheitTolerance { get { return 1e-5; } } - protected virtual double CaloriesPerCubicCentimeterDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double JoulesPerCubicMeterDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double JoulesPerCubicMeterKelvinTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerCubicCentimeterDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerCubicMeterDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerCubicMeterKelvinTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerCubicMeterDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerCubicMeterKelvinTolerance { get { return 1e-5; } } + protected virtual double BtusPerCubicFootDegreeFahrenheitTolerance { get { return 1E-5; } } + protected virtual double CaloriesPerCubicCentimeterDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double JoulesPerCubicMeterDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double JoulesPerCubicMeterKelvinTolerance { get { return 1E-5; } } + protected virtual double KilocaloriesPerCubicCentimeterDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerCubicMeterDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double KilojoulesPerCubicMeterKelvinTolerance { get { return 1E-5; } } + protected virtual double MegajoulesPerCubicMeterDegreeCelsiusTolerance { get { return 1E-5; } } + protected virtual double MegajoulesPerCubicMeterKelvinTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(VolumetricHeatCapacityUnit unit) @@ -238,7 +238,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -487,14 +487,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(VolumetricHeatCapacityUnit unit) { - var inBaseUnits = VolumetricHeatCapacity.From(1.0, VolumetricHeatCapacity.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = VolumetricHeatCapacity.From(1.0, VolumetricHeatCapacity.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = VolumetricHeatCapacity.From(1.0, VolumetricHeatCapacity.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(VolumetricHeatCapacityUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(VolumetricHeatCapacityUnit unit) @@ -508,8 +515,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumetricHeatCapacityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumetricHeatCapacityUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = VolumetricHeatCapacity.Units.Where(u => u != VolumetricHeatCapacity.BaseUnit).DefaultIfEmpty(VolumetricHeatCapacity.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = VolumetricHeatCapacity.Units.First(u => u != VolumetricHeatCapacity.BaseUnit); var quantity = VolumetricHeatCapacity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -728,8 +735,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -763,36 +771,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -805,22 +818,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -862,7 +878,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(new {VolumetricHeatCapacity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(VolumetricHeatCapacity.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs index 683a9313ae..216a8b4dd8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs @@ -46,12 +46,12 @@ public abstract partial class WarpingMomentOfInertiaTestsBase : QuantityTestsBas protected abstract double MillimetersToTheSixthInOneMeterToTheSixth { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimetersToTheSixthTolerance { get { return 1e-5; } } - protected virtual double DecimetersToTheSixthTolerance { get { return 1e-5; } } - protected virtual double FeetToTheSixthTolerance { get { return 1e-5; } } - protected virtual double InchesToTheSixthTolerance { get { return 1e-5; } } - protected virtual double MetersToTheSixthTolerance { get { return 1e-5; } } - protected virtual double MillimetersToTheSixthTolerance { get { return 1e-5; } } + protected virtual double CentimetersToTheSixthTolerance { get { return 1E-5; } } + protected virtual double DecimetersToTheSixthTolerance { get { return 1E-5; } } + protected virtual double FeetToTheSixthTolerance { get { return 1E-5; } } + protected virtual double InchesToTheSixthTolerance { get { return 1E-5; } } + protected virtual double MetersToTheSixthTolerance { get { return 1E-5; } } + protected virtual double MillimetersToTheSixthTolerance { get { return 1E-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(WarpingMomentOfInertiaUnit unit) @@ -208,7 +208,7 @@ public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() if (SupportsSIUnitSystem) { - var value = (double) AsWithSIUnitSystem(); + var value = (double) (QuantityValue) AsWithSIUnitSystem(); Assert.Equal(1, value); } else @@ -529,14 +529,21 @@ public void TryParseUnit() [MemberData(nameof(UnitTypes))] public void ToUnit(WarpingMomentOfInertiaUnit unit) { - var inBaseUnits = WarpingMomentOfInertia.From(1.0, WarpingMomentOfInertia.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); + var inBaseUnit = WarpingMomentOfInertia.From(1.0, WarpingMomentOfInertia.BaseUnit); + var converted = inBaseUnit.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } + [Fact] + public void ToUnit_FromNonExistingUnit_ThrowsNotSupportedException() + { + var inBaseUnit = WarpingMomentOfInertia.From(1.0, WarpingMomentOfInertia.BaseUnit); + Assert.Throws(() => inBaseUnit.ToUnit(default(WarpingMomentOfInertiaUnit))); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit_WithSameUnits_AreEqual(WarpingMomentOfInertiaUnit unit) @@ -550,8 +557,8 @@ public void ToUnit_WithSameUnits_AreEqual(WarpingMomentOfInertiaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(WarpingMomentOfInertiaUnit unit) { - // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. - var fromUnit = WarpingMomentOfInertia.Units.Where(u => u != WarpingMomentOfInertia.BaseUnit).DefaultIfEmpty(WarpingMomentOfInertia.BaseUnit).FirstOrDefault(); + // This test is only available for quantities with more than one units. + var fromUnit = WarpingMomentOfInertia.Units.First(u => u != WarpingMomentOfInertia.BaseUnit); var quantity = WarpingMomentOfInertia.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -761,8 +768,9 @@ public void Convert_ToBool_ThrowsInvalidCastException() [Fact] public void Convert_ToByte_EqualsValueAsSameType() { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); + var value = 1.0; + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(value); + Assert.Equal((byte)value, Convert.ToByte(quantity)); } [Fact] @@ -796,36 +804,41 @@ public void Convert_ToDouble_EqualsValueAsSameType() [Fact] public void Convert_ToInt16_EqualsValueAsSameType() { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); + var value = 1.0; + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(value); + Assert.Equal((short)value, Convert.ToInt16(quantity)); } [Fact] public void Convert_ToInt32_EqualsValueAsSameType() { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); + var value = 1.0; + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(value); + Assert.Equal((int)value, Convert.ToInt32(quantity)); } [Fact] public void Convert_ToInt64_EqualsValueAsSameType() { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); + var value = 1.0; + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(value); + Assert.Equal((long)value, Convert.ToInt64(quantity)); } [Fact] public void Convert_ToSByte_EqualsValueAsSameType() { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); + var value = 1.0; + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(value); + Assert.Equal((sbyte)value, Convert.ToSByte(quantity)); } [Fact] public void Convert_ToSingle_EqualsValueAsSameType() { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); + var value = 1.0; + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(value); + Assert.Equal((float)value, Convert.ToSingle(quantity)); } [Fact] @@ -838,22 +851,25 @@ public void Convert_ToString_EqualsToString() [Fact] public void Convert_ToUInt16_EqualsValueAsSameType() { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); + var value = 1.0; + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(value); + Assert.Equal((ushort)value, Convert.ToUInt16(quantity)); } [Fact] public void Convert_ToUInt32_EqualsValueAsSameType() { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); + var value = 1.0; + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(value); + Assert.Equal((uint)value, Convert.ToUInt32(quantity)); } [Fact] public void Convert_ToUInt64_EqualsValueAsSameType() { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); + var value = 1.0; + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(value); + Assert.Equal((ulong)value, Convert.ToUInt64(quantity)); } [Fact] @@ -895,7 +911,7 @@ public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() public void GetHashCode_Equals() { var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(new {WarpingMomentOfInertia.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), quantity.GetHashCode()); + Assert.Equal(WarpingMomentOfInertia.Info.Name.GetHashCode(), quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs index d02428161f..87882f3ad3 100644 --- a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs +++ b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs @@ -26,7 +26,7 @@ public void LengthEquals_GivenMaxError_ReturnsTrueIfWithinError() Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), 0, ComparisonType.Relative), "Integer values have zero difference."); Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), smallError, ComparisonType.Relative), "Using a max difference value should not change that fact."); - Assert.False(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), 0, ComparisonType.Relative), + Assert.False(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), 0.0, ComparisonType.Relative), "Example of floating precision arithmetic that produces slightly different results."); Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), smallError, ComparisonType.Relative), "But the difference is very small"); } diff --git a/UnitsNet.Tests/IntOverloadTests.cs b/UnitsNet.Tests/IntOverloadTests.cs index bf63007ba7..9d059dcc46 100644 --- a/UnitsNet.Tests/IntOverloadTests.cs +++ b/UnitsNet.Tests/IntOverloadTests.cs @@ -18,7 +18,7 @@ public static void CreatingQuantityWithDoubleBackingFieldFromIntReturnsCorrectVa public static void CreatingQuantityWithIntBackingFieldFromIntReturnsCorrectValue() { Power power = Power.FromWatts(1); - Assert.Equal(1.0, power.Watts); + Assert.Equal(1.0m, power.Watts); } } } diff --git a/UnitsNet.Tests/LongOverloadTests.cs b/UnitsNet.Tests/LongOverloadTests.cs index fd54377f08..ba5c00a538 100644 --- a/UnitsNet.Tests/LongOverloadTests.cs +++ b/UnitsNet.Tests/LongOverloadTests.cs @@ -18,7 +18,7 @@ public static void CreatingQuantityWithDoubleBackingFieldFromLongReturnsCorrectV public static void CreatingQuantityWithLongBackingFieldFromLongReturnsCorrectValue() { Power power = Power.FromWatts(1L); - Assert.Equal(1.0, power.Watts); + Assert.Equal(1.0m, power.Watts); } } } diff --git a/UnitsNet.Tests/QuantityComparisonTests.cs b/UnitsNet.Tests/QuantityComparisonTests.cs new file mode 100644 index 0000000000..2947c2c251 --- /dev/null +++ b/UnitsNet.Tests/QuantityComparisonTests.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Generic; +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests +{ + public class QuantityComparisonTests + { + private static readonly decimal DecimalEpsilon = new decimal(1, 0, 0, false, 28); //1e-28m; + + #region IComparable + + [Fact] + public void CompareTo_DoubleQuantityWithSameQuantityInAnotherUnit_ReturnsZero() + { + var firstMass = Mass.FromGrams(0.001); + var secondMass = firstMass.ToUnit(MassUnit.Microgram); + + Assert.Equal(0, firstMass.CompareTo(secondMass)); + Assert.Equal(0, secondMass.CompareTo(firstMass)); + } + + [Fact] + public void CompareTo_DecimalQuantityWithSameQuantityInAnotherUnit_ReturnsZero() + { + var firstMass = Mass.FromGrams(0.001m); + var secondMass = firstMass.ToUnit(MassUnit.Microgram); + + Assert.Equal(0, firstMass.CompareTo(secondMass)); + Assert.Equal(0, secondMass.CompareTo(firstMass)); + } + + [Fact] + public void CompareTo_DoubleQuantityWithVeryCloseDoubleQuantity_ReturnsNonZero() + { + var firstMass = Mass.FromGrams(0.0); + var secondMass = Mass.FromGrams(double.Epsilon); + + Assert.Equal(-1, firstMass.CompareTo(secondMass)); + Assert.Equal(1, secondMass.CompareTo(firstMass)); + } + + [Fact] + public void CompareTo_DecimalQuantityWithVeryCloseDecimalQuantity_ReturnsNonZero() + { + var firstMass = Mass.FromGrams(0m); + var secondMass = Mass.FromGrams(DecimalEpsilon); + + Assert.Equal(-1, firstMass.CompareTo(secondMass)); + Assert.Equal(1, secondMass.CompareTo(firstMass)); + } + + [Fact] + public void CompareTo_DoubleQuantityWithVeryCloseDecimalQuantity_ReturnsNonZero() + { + var firstMass = Mass.FromGrams(-double.Epsilon); + var secondMass = Mass.FromGrams(0m); + + Assert.Equal(-1, firstMass.CompareTo(secondMass)); + Assert.Equal(1, secondMass.CompareTo(firstMass)); + } + + [Fact] + public void CompareTo_DecimalQuantityWithVeryCloseDoubleQuantity_ReturnsNonZero() + { + var firstMass = Mass.FromGrams(0m); + var secondMass = Mass.FromGrams(double.Epsilon); + + Assert.Equal(-1, firstMass.CompareTo(secondMass)); + Assert.Equal(1, secondMass.CompareTo(firstMass)); + } + + [Fact] + public void CompareTo_DecimalQuantityWithVeryLargeDoubleQuantity_ReturnsNonZero() + { + var firstMass = Mass.FromGrams(0m); + var secondMass = Mass.FromGrams(double.MaxValue); + + Assert.Equal(-1, firstMass.CompareTo(secondMass)); + Assert.Equal(1, secondMass.CompareTo(firstMass)); + } + + [Fact] + public void CompareTo_DecimalQuantityWithVerySmallDoubleQuantity_ReturnsNonZero() + { + var firstMass = Mass.FromGrams(0m); + var secondMass = Mass.FromGrams(double.MinValue); + + Assert.Equal(1, firstMass.CompareTo(secondMass)); + Assert.Equal(-1, secondMass.CompareTo(firstMass)); + } + + #endregion + + [Fact] + public void Equals_DoubleQuantityWithSameQuantityInAnotherUnit_ReturnsFalse() + { + var firstMass = Mass.FromGrams(0.001); + var secondMass = firstMass.ToUnit(MassUnit.Microgram); + + Assert.NotEqual(firstMass, secondMass); + Assert.NotEqual(secondMass, firstMass); + } + + [Fact] + public void Equals_DecimalQuantityWithSameQuantityInAnotherUnit_ReturnsTrue() + { + var firstMass = Mass.FromGrams(0.001m); + var secondMass = firstMass.ToUnit(MassUnit.Microgram); + + Assert.Equal(firstMass, secondMass); + Assert.Equal(secondMass, firstMass); + } + + [Fact] + public void Equals_DecimalQuantityWithVeryCloseDoubleQuantityInSameUnit_ReturnsFalse() + { + var firstMass = Mass.FromGrams(0m); + var secondMass = Mass.FromGrams(double.Epsilon); + + Assert.NotEqual(firstMass, secondMass); + Assert.NotEqual(secondMass, firstMass); + } + + [Fact] + public void GetHashCode_WithSameQuantityInAnotherUnit_ReturnsSameValue() + { + var firstMass = Mass.FromGrams(0.001); + var secondMass = firstMass.ToUnit(MassUnit.Microgram); + + Assert.Equal(firstMass.GetHashCode(), secondMass.GetHashCode()); + } + + [Fact] + public void GetHashCode_WithVeryCloseQuantities_ReturnsSameValue() + { + var firstMass = Mass.FromGrams(0); + var secondMass = Mass.FromGrams(double.Epsilon); + + Assert.Equal(firstMass.GetHashCode(), secondMass.GetHashCode()); + } + + [Fact] + public void Contains_CollectionWithMixedUnits_DependsOnTheOrderOfInsertion() + { + var firstMass = Mass.FromGrams(0.001); + var secondMass = firstMass.ToUnit(MassUnit.Microgram); + + var collectionWithFirst = new HashSet {firstMass}; + var collectionWithSecond = new HashSet {secondMass}; + + Assert.Contains(firstMass, collectionWithFirst); + Assert.DoesNotContain(secondMass, collectionWithFirst); + + Assert.DoesNotContain(firstMass, collectionWithSecond); + Assert.Contains(secondMass, collectionWithSecond); + } + + [Fact] + public void Contains_CollectionWithVeryCloseQuantities_ReturnsTrueIfValuesAreStrictlyEqual() + { + var firstMass = Mass.FromGrams(0); + var secondMass = Mass.FromGrams(double.Epsilon); + + var collection = new HashSet {firstMass}; + + // equal hash codes do not imply object equality + Assert.Equal(firstMass.GetHashCode(), secondMass.GetHashCode()); + Assert.NotEqual(firstMass, secondMass); + + // Contains first checks HashCode, followed by Equals check + Assert.Contains(firstMass, collection); + Assert.DoesNotContain(secondMass, collection); + } + + [Fact] + public void Sort_CollectionWithMixedUnits_SortedByNaturalOrder() + { + var firstMass = Mass.FromGrams(0); + var secondMass = Mass.FromGrams(double.Epsilon); + var thirdMass = Mass.FromGrams(0.001); + var fourthMass = thirdMass.ToUnit(MassUnit.Microgram); + + var collection = new[] {thirdMass, firstMass, fourthMass, secondMass}; + Array.Sort(collection); + + Assert.Equal(firstMass, collection[0]); + Assert.Equal(secondMass, collection[1]); + Assert.Equal(thirdMass, collection[2]); + Assert.Equal(fourthMass, collection[3]); + } + } +} diff --git a/UnitsNet.Tests/QuantityValueTests.cs b/UnitsNet.Tests/QuantityValueTests.cs new file mode 100644 index 0000000000..8df8cfb717 --- /dev/null +++ b/UnitsNet.Tests/QuantityValueTests.cs @@ -0,0 +1,150 @@ +using System; +using Xunit; + +namespace UnitsNet.Tests; + +public class QuantityValueTests +{ + [Fact] + public void QuantityValue_FromDouble_ContainsDouble() + { + QuantityValue value = 1.0; + + Assert.False(value.IsDecimal); + Assert.Equal(1.0, (double)value); + } + + [Fact] + public void QuantityValue_FromDecimal_ContainsDecimal() + { + QuantityValue value = 1.0m; + + Assert.True(value.IsDecimal); + Assert.Equal(1.0m, (decimal)value); + } + + [Fact] + public void QuantityValue_FromInteger_ContainsDecimal() + { + QuantityValue value = 1; + + Assert.True(value.IsDecimal); + Assert.Equal(1m, (decimal)value); + } + + [Fact] + public void QuantityValue_FromNaN_ThrowsException() + { + Assert.Throws(() => (QuantityValue)double.NaN); + } + + [Fact] + public void QuantityValue_FromInfinity_ThrowsException() + { + Assert.Throws(() => (QuantityValue)double.PositiveInfinity); + Assert.Throws(() => (QuantityValue)double.NegativeInfinity); + } + + [Fact] + public void Operations_WithDoubles_ReturnDoubles() + { + QuantityValue two = 2.0; + + QuantityValue twoPlusTwo = two + two; + QuantityValue twoMinusTwo = two - two; + QuantityValue twoTimesTwo = two * two; + QuantityValue twoDividedByTwo = two / two; + + Assert.False(twoPlusTwo.IsDecimal); + Assert.False(twoMinusTwo.IsDecimal); + Assert.False(twoTimesTwo.IsDecimal); + Assert.False(twoDividedByTwo.IsDecimal); + + Assert.Equal(4.0, (double)twoPlusTwo); + Assert.Equal(0.0, (double)twoMinusTwo); + Assert.Equal(4.0, (double)twoTimesTwo); + Assert.Equal(1.0, (double)twoDividedByTwo); + } + + [Fact] + public void Operations_WithDecimal_ReturnDecimals() + { + QuantityValue two = 2.0m; + + QuantityValue twoPlusTwo = two + two; + QuantityValue twoMinusTwo = two - two; + QuantityValue twoTimesTwo = two * two; + QuantityValue twoDividedByTwo = two / two; + + Assert.True(twoPlusTwo.IsDecimal); + Assert.True(twoMinusTwo.IsDecimal); + Assert.True(twoTimesTwo.IsDecimal); + Assert.True(twoDividedByTwo.IsDecimal); + + Assert.Equal(4.0m, (decimal)twoPlusTwo); + Assert.Equal(0.0m, (decimal)twoMinusTwo); + Assert.Equal(4.0m, (decimal)twoTimesTwo); + Assert.Equal(1.0m, (decimal)twoDividedByTwo); + } + + [Fact] + public void Operations_WithDoubleAndDecimal_ReturnDecimals() + { + QuantityValue twoFromDouble = 2.0; + QuantityValue twoFromDecimal = 2.0m; + + QuantityValue twoPlusTwo = twoFromDouble + twoFromDecimal; + QuantityValue twoMinusTwo = twoFromDouble - twoFromDecimal; + QuantityValue twoTimesTwo = twoFromDouble * twoFromDecimal; + QuantityValue twoDividedByTwo = twoFromDouble / twoFromDecimal; + + Assert.True(twoPlusTwo.IsDecimal); + Assert.True(twoMinusTwo.IsDecimal); + Assert.True(twoTimesTwo.IsDecimal); + Assert.True(twoDividedByTwo.IsDecimal); + + Assert.Equal(4.0m, (decimal)twoPlusTwo); + Assert.Equal(0.0m, (decimal)twoMinusTwo); + Assert.Equal(4.0m, (decimal)twoTimesTwo); + Assert.Equal(1.0m, (decimal)twoDividedByTwo); + } + + [Fact] + public void OverflowingOperations_WithDecimal_ReturnDoubles() + { + // TODO see about exposing a QuantityValue.MaxDecimal constant + const decimal maxDecimalValue = decimal.MaxValue * 1E-6m; // the clamping value is actual smaller than the decimal.MaxValue (ensuring the minimal conversion precision) + QuantityValue maxDecimal = maxDecimalValue; + + QuantityValue twoTimesMax = maxDecimal + maxDecimal; + QuantityValue twoTimesMin = -maxDecimal - maxDecimal; + QuantityValue maxSquared = maxDecimal * maxDecimal; + QuantityValue oneOverMax = 0.1 / maxDecimal; + + Assert.True(maxDecimal.IsDecimal); + Assert.False(twoTimesMax.IsDecimal); + Assert.False(twoTimesMin.IsDecimal); + Assert.False(maxSquared.IsDecimal); + Assert.False(oneOverMax.IsDecimal); + + const double max = (double)maxDecimalValue; + Assert.Equal(max + max, (double)twoTimesMax); + Assert.Equal(-max - max, (double)twoTimesMin); + Assert.Equal(max * max, (double)maxSquared); + Assert.Equal(0.1 / max, (double)oneOverMax); + } + + [Fact] + public void OverflowingOperations_WithDouble_ThrowArgumentException() + { + // TODO see about supporting Positive/Negative infinity + QuantityValue maxDouble = double.MaxValue; + + Assert.Throws(() => maxDouble + maxDouble); + Assert.Throws(() => -maxDouble - maxDouble); + Assert.Throws(() => maxDouble * maxDouble); + Assert.Throws(() => maxDouble / 0); + } + + // TODO add tests for IEquatable / IComparable (decimal comparison when both values are in the decimal range) +} diff --git a/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs b/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs index d556757893..ea9fdf9429 100644 --- a/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs +++ b/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs @@ -1,4 +1,5 @@ -using System.Globalization; +using System; +using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; @@ -41,12 +42,13 @@ protected override T DeserializeObject(string xml) #region Serialization tests + [Fact] - public void DoubleQuantity_SerializedWithDoubleValueAndunitInt() + public void DoubleQuantity_SerializedWithDoubleValueAndIntegerUnit() { var quantity = new Mass(1.20, MassUnit.Milligram); var unitInt = (int)quantity.Unit; - var expectedJson = $"{{\"Value\":1.2,\"Unit\":{unitInt}}}"; + var expectedJson = $"{{\"Value\":{{\"Double\":1.2}},\"Unit\":{unitInt}}}"; var json = SerializeObject(quantity); @@ -54,14 +56,14 @@ public void DoubleQuantity_SerializedWithDoubleValueAndunitInt() } [Fact] - public void DecimalQuantity_SerializedWithDecimalValueValueAndunitInt() + public void DecimalQuantity_SerializedWithDecimalValueValueAndIntegerUnit() { var quantity = new Information(1.20m, InformationUnit.Exabyte); var unitInt = (int)InformationUnit.Exabyte; - var expectedJson = $"{{\"Value\":1.20,\"Unit\":{unitInt}}}"; + var expectedJson = $"{{\"Value\":{{\"Decimal\":1.20}},\"Unit\":{unitInt}}}"; var json = SerializeObject(quantity); - + Assert.Equal(expectedJson, json); } @@ -70,11 +72,11 @@ public void DecimalQuantity_SerializedWithDecimalValueValueAndunitInt() #region Deserialization tests [Fact] - public void DoubleQuantity_DeserializedFromDoubleValueAndunitInt() + public void DoubleQuantity_DeserializedFromDoubleValueAndIntegerUnit() { var expectedUnit = MassUnit.Milligram; var unitInt = (int)expectedUnit; - var json = $"{{\"Value\":1.2,\"Unit\":{unitInt}}}"; + var json = $"{{\"Value\":{{\"Double\":1.2}},\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); @@ -83,11 +85,11 @@ public void DoubleQuantity_DeserializedFromDoubleValueAndunitInt() } [Fact] - public void DoubleQuantity_DeserializedFromQuotedDoubleValueAndunitInt() + public void DoubleQuantity_DeserializedFromQuotedDoubleValueAndIntegerUnit() { var expectedUnit = MassUnit.Milligram; var unitInt = (int)expectedUnit; - var json = $"{{\"Value\":\"1.2\",\"Unit\":{unitInt}}}"; + var json = $"{{\"Value\":{{\"Double\":\"1.2\"}},\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); @@ -96,7 +98,7 @@ public void DoubleQuantity_DeserializedFromQuotedDoubleValueAndunitInt() } [Fact] - public void DoubleZeroQuantity_DeserializedFromunitIntAndNoValue() + public void DoubleZeroQuantity_DeserializedFromIntegerUnitAndNoValue() { var expectedUnit = MassUnit.Milligram; var unitInt = (int)expectedUnit; @@ -114,7 +116,7 @@ public void InterfaceObject_IncludesTypeInformation() var unit = InformationUnit.Exabyte; var unitInt = (int)unit; var testObject = new TestInterfaceObject { Quantity = new Information(1.20m, unit) }; - var expectedJson = $"{{\"Quantity\":{{\"__type\":\"Information:#UnitsNet\",\"Value\":1.20,\"Unit\":{unitInt}}}}}"; + var expectedJson = $"{{\"Quantity\":{{\"__type\":\"Information:#UnitsNet\",\"Value\":{{\"Decimal\":1.20}},\"Unit\":{unitInt}}}}}"; var json = SerializeObject(testObject); @@ -124,7 +126,7 @@ public void InterfaceObject_IncludesTypeInformation() [Fact] public void DoubleBaseUnitQuantity_DeserializedFromValueAndNoUnit() { - var json = "{\"Value\":1.2}"; + var json = "{\"Value\":{\"Double\":1.2}}"; var quantity = DeserializeObject(json); @@ -144,11 +146,11 @@ public void DoubleZeroBaseQuantity_DeserializedFromEmptyInput() } [Fact] - public void DecimalQuantity_DeserializedFromDecimalValueAndunitInt() + public void DecimalQuantity_DeserializedFromDecimalValueAndIntegerUnit() { var expectedUnit = InformationUnit.Exabyte; var unitInt = (int)expectedUnit; - var json = $"{{\"Value\":1.200,\"Unit\":{unitInt}}}"; + var json = $"{{\"Value\":{{\"Decimal\":1.200}},\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); @@ -166,11 +168,11 @@ public void InterfaceObject_WithMissingKnownTypeInformation_ThrowsSerializationE } [Fact] - public void DecimalQuantity_DeserializedFromQuotedDecimalValueAndunitInt() + public void DecimalQuantity_DeserializedFromQuotedDecimalValueAndDecimalUnit() { var expectedUnit = InformationUnit.Exabyte; var unitInt = (int)expectedUnit; - var json = $"{{\"Value\":\"1.200\",\"Unit\":{unitInt}}}"; + var json = $"{{\"Value\":{{\"Decimal\":\"1.200\"}},\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); @@ -180,7 +182,7 @@ public void DecimalQuantity_DeserializedFromQuotedDecimalValueAndunitInt() } [Fact] - public void DecimalZeroQuantity_DeserializedFromunitIntAndNoValue() + public void DecimalZeroQuantity_DeserializedFromIntegerUnitAndNoValue() { var expectedUnit = InformationUnit.Exabyte; var unitInt = (int)expectedUnit; @@ -195,7 +197,7 @@ public void DecimalZeroQuantity_DeserializedFromunitIntAndNoValue() [Fact] public void DecimalBaseUnitQuantity_DeserializedFromDecimalValueAndNoUnit() { - var json = "{\"Value\":1.200}"; + var json = "{\"Value\":{\"Decimal\":1.200}}"; var quantity = DeserializeObject(json); diff --git a/UnitsNet.Tests/Serialization/SerializationTestsBase.cs b/UnitsNet.Tests/Serialization/SerializationTestsBase.cs index d2a4f6d6b8..83f468bd41 100644 --- a/UnitsNet.Tests/Serialization/SerializationTestsBase.cs +++ b/UnitsNet.Tests/Serialization/SerializationTestsBase.cs @@ -64,7 +64,7 @@ public void DecimalValueQuantity_SerializationRoundTrips() [Fact] public void LargeDecimalValueQuantity_SerializationRoundTrips() { - var quantity = Information.FromExabytes(1E+24); + var quantity = Information.FromExabytes(1E+24m); var payload = SerializeObject(quantity); var result = DeserializeObject(payload); diff --git a/UnitsNet.Tests/Serialization/Xml/DataContractSerializerTests.cs b/UnitsNet.Tests/Serialization/Xml/DataContractSerializerTests.cs index ca45df9395..21d4c6d989 100644 --- a/UnitsNet.Tests/Serialization/Xml/DataContractSerializerTests.cs +++ b/UnitsNet.Tests/Serialization/Xml/DataContractSerializerTests.cs @@ -39,7 +39,7 @@ protected override T DeserializeObject(string xml) public void DoubleQuantity_SerializedWithValueAndMemberName() { var quantity = new Mass(1.20, MassUnit.Milligram); - var expectedXml = $"1.2Milligram"; + var expectedXml = $"1.2Milligram"; var xml = SerializeObject(quantity); @@ -50,7 +50,7 @@ public void DoubleQuantity_SerializedWithValueAndMemberName() public void DecimalQuantity_SerializedWithValueAndMemberName() { var quantity = new Information(1.20m, InformationUnit.Exabyte); - var expectedXml = $"1.20Exabyte"; + var expectedXml = $"1.20Exabyte"; var xml = SerializeObject(quantity); @@ -63,7 +63,7 @@ public void InterfaceObject_IncludesTypeInformation() var testObject = new TestInterfaceObject { Quantity = new Information(1.20m, InformationUnit.Exabyte) }; var quantityNamespace = "xmlns:a=\"http://schemas.datacontract.org/2004/07/UnitsNet\""; // there is an extra 'a' compared to Namespace - var expectedQuantityXml = $"1.20Exabyte"; + var expectedQuantityXml = $"1.20Exabyte"; var expectedXml = $"{expectedQuantityXml}"; var xml = SerializeObject(testObject); diff --git a/UnitsNet.Tests/UnitConverterTest.cs b/UnitsNet.Tests/UnitConverterTest.cs index 421d7fef23..b58f13a258 100644 --- a/UnitsNet.Tests/UnitConverterTest.cs +++ b/UnitsNet.Tests/UnitConverterTest.cs @@ -112,8 +112,8 @@ public void ConversionForUnitsOfCustomQuantity(double fromValue, HowMuchUnit fro { // Intentionally don't map conversion Some->Some, it is not necessary var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(HowMuchUnit.Some, HowMuchUnit.ATon, x => new HowMuch(x.Value * 2, HowMuchUnit.ATon)); - unitConverter.SetConversionFunction(HowMuchUnit.Some, HowMuchUnit.AShitTon, x => new HowMuch(x.Value * 10, HowMuchUnit.AShitTon)); + unitConverter.SetConversionFunction(HowMuchUnit.Some, HowMuchUnit.ATon, x => new HowMuch((double)x.Value * 2, HowMuchUnit.ATon)); + unitConverter.SetConversionFunction(HowMuchUnit.Some, HowMuchUnit.AShitTon, x => new HowMuch((double)x.Value * 10, HowMuchUnit.AShitTon)); var foundConversionFunction = unitConverter.GetConversionFunction(fromUnit, toUnit); var converted = foundConversionFunction(new HowMuch(fromValue, fromUnit)); @@ -164,9 +164,9 @@ public void ConvertByName_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnit(doubl [InlineData(1, "UnknownQuantity", "Meter", "Centimeter")] [InlineData(1, "Length", "UnknownFromUnit", "Centimeter")] [InlineData(1, "Length", "Meter", "UnknownToUnit")] - public void TryConvertByName_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit) + public void TryConvertByName_ReturnsFalseForInvalidInput(QuantityValue inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.False(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out double result)); + Assert.False(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out var result)); Assert.Equal(0, result); } @@ -175,10 +175,10 @@ public void TryConvertByName_ReturnsFalseForInvalidInput(double inputValue, stri [InlineData(100, 1, "Length", "Meter", "Centimeter")] [InlineData(1, 1000, "Mass", "Gram", "Kilogram")] [InlineData(1000, 1, "ElectricCurrent", "Kiloampere", "Ampere")] - public void TryConvertByName_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, + public void TryConvertByName_ReturnsTrueOnSuccessAndOutputsResult(QuantityValue expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.True(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out double result), "TryConvertByName() return value."); + Assert.True(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out var result), "TryConvertByName() return value."); Assert.Equal(expectedValue, result); } @@ -211,9 +211,9 @@ public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUn [InlineData(1, "UnknownQuantity", "m", "cm")] [InlineData(1, "Length", "UnknownFromUnit", "cm")] [InlineData(1, "Length", "m", "UnknownToUnit")] - public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit) + public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(QuantityValue inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result)); + Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out var result)); Assert.Equal(0, result); } @@ -222,10 +222,10 @@ public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputVal [InlineData(100, 1, "Length", "m", "cm")] [InlineData(1, 1000, "Mass", "g", "kg")] [InlineData(1000, 1, "ElectricCurrent", "kA", "A")] - public void TryConvertByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, + public void TryConvertByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(QuantityValue expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result), "TryConvertByAbbreviation() return value."); + Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out var result), "TryConvertByAbbreviation() return value."); Assert.Equal(expectedValue, result); } } diff --git a/UnitsNet.Tests/UnitsNet.Tests.csproj b/UnitsNet.Tests/UnitsNet.Tests.csproj index 1d79559af7..5bc5c3cf63 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -24,8 +24,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/UnitsNet.sln b/UnitsNet.sln index 6ae0d3d8b3..4b402d54ec 100644 --- a/UnitsNet.sln +++ b/UnitsNet.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29609.76 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32811.315 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet", "UnitsNet\UnitsNet.csproj", "{CBEAD842-07BC-4B08-9D9D-D6659813776F}" EndProject @@ -11,8 +11,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.Json EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Tests", "UnitsNet.Tests\UnitsNet.Tests.csproj", "{0E3B7567-5DF2-44BD-88DB-CCF050D3F943}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.JsonNet.CompatibilityTests", "UnitsNet.Serialization.JsonNet.CompatibilityTests\UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj", "{21F2FFAC-BF39-487F-9ADE-37100162F955}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Benchmark", "UnitsNet.Benchmark\UnitsNet.Benchmark.csproj", "{76B9C7C8-E3D3-4FA7-B782-78E4BA1D0AD8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeGen", "CodeGen\CodeGen.csproj", "{078E3D44-4F60-46B3-9099-91A7CBF0B213}" @@ -22,27 +20,27 @@ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.NumberExtensions.Tests", "UnitsNet.NumberExtensions.Tests\UnitsNet.NumberExtensions.Tests.csproj", "{B4996AF5-9A8B-481A-9018-EC7F5B1605FF}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Files", "_Files", "{B92B01BE-243E-4CCB-B5E5-AF469ADB1F54}" -ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - .gitattributes = .gitattributes - .gitignore = .gitignore - appveyor.yml = appveyor.yml - build.bat = build.bat - build-all-targets.bat = build-all-targets.bat - clean.bat = clean.bat - CODE_OF_CONDUCT.md = CODE_OF_CONDUCT.md - CONTRIBUTING.md = CONTRIBUTING.md - Directory.Build.props = Directory.Build.props - generate-code.bat = generate-code.bat - init.bat = init.bat - LICENSE = LICENSE - nuget.config = nuget.config - publish-unitsnet.bat = publish-unitsnet.bat - README.md = README.md - test.bat = test.bat - UnitsNet.sln.DotSettings = UnitsNet.sln.DotSettings - UnitsNet.snk = UnitsNet.snk -EndProjectSection + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + .gitattributes = .gitattributes + .gitignore = .gitignore + appveyor.yml = appveyor.yml + build-all-targets.bat = build-all-targets.bat + build.bat = build.bat + clean.bat = clean.bat + CODE_OF_CONDUCT.md = CODE_OF_CONDUCT.md + CONTRIBUTING.md = CONTRIBUTING.md + Directory.Build.props = Directory.Build.props + generate-code.bat = generate-code.bat + init.bat = init.bat + LICENSE = LICENSE + nuget.config = nuget.config + publish-unitsnet.bat = publish-unitsnet.bat + README.md = README.md + test.bat = test.bat + UnitsNet.sln.DotSettings = UnitsNet.sln.DotSettings + UnitsNet.snk = UnitsNet.snk + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -66,10 +64,6 @@ Global {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|Any CPU.Build.0 = Debug|Any CPU {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|Any CPU.ActiveCfg = Release|Any CPU {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|Any CPU.Build.0 = Release|Any CPU - {21F2FFAC-BF39-487F-9ADE-37100162F955}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {21F2FFAC-BF39-487F-9ADE-37100162F955}.Debug|Any CPU.Build.0 = Debug|Any CPU - {21F2FFAC-BF39-487F-9ADE-37100162F955}.Release|Any CPU.ActiveCfg = Release|Any CPU - {21F2FFAC-BF39-487F-9ADE-37100162F955}.Release|Any CPU.Build.0 = Release|Any CPU {76B9C7C8-E3D3-4FA7-B782-78E4BA1D0AD8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {76B9C7C8-E3D3-4FA7-B782-78E4BA1D0AD8}.Debug|Any CPU.Build.0 = Debug|Any CPU {76B9C7C8-E3D3-4FA7-B782-78E4BA1D0AD8}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/UnitsNet/Comparison.cs b/UnitsNet/Comparison.cs index 575707e6b5..7a448f9b89 100644 --- a/UnitsNet/Comparison.cs +++ b/UnitsNet/Comparison.cs @@ -49,7 +49,66 @@ public static class Comparison /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// Whether the tolerance is absolute or relative. /// - public static bool Equals(double referenceValue, double otherValue, double tolerance, ComparisonType comparisonType) + public static bool Equals(QuantityValue referenceValue, QuantityValue otherValue, QuantityValue tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + + switch (comparisonType) + { + case ComparisonType.Relative: + return referenceValue.IsDecimal || otherValue.IsDecimal || tolerance.IsDecimal + ? EqualsRelative((decimal)referenceValue, (decimal)otherValue, (decimal)tolerance) + : EqualsRelative((double)referenceValue, (double)otherValue, (double)tolerance); + case ComparisonType.Absolute: + return referenceValue.IsDecimal || otherValue.IsDecimal || tolerance.IsDecimal + ? EqualsAbsolute((decimal)referenceValue, (decimal)otherValue, (decimal)tolerance) + : EqualsAbsolute((double)referenceValue, (double)otherValue, (double)tolerance); + default: + throw new InvalidOperationException("The given ComparisonType is not supported."); + } + } + + /// + /// + /// Checks if two values are equal with a given relative or absolute tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between + /// and + /// as a percentage of . A relative tolerance of + /// 0.01 means the + /// absolute difference of and must be within +/- + /// 1%. + /// + /// In this example, the two values will be equal if the value of b is within +/- 1% of a. + /// + /// Equals(a, b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between + /// and + /// as a fixed number. + /// + /// In this example, the two values will be equal if abs( - + /// ) <= 0.01 + /// + /// Equals(a, b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// + /// The reference value. If using relative tolerance, it is the value which the relative + /// tolerance will be calculated against. + /// + /// The value to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// Whether the tolerance is absolute or relative. + /// + public static bool Equals(decimal referenceValue, decimal otherValue, decimal tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); @@ -95,6 +154,36 @@ public static bool EqualsRelative(double referenceValue, double otherValue, doub return Math.Abs(referenceValue - otherValue) <= maxVariation; } + /// + /// Checks if two values are equal with a given relative tolerance. + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between + /// and + /// as a percentage of . A relative tolerance of + /// 0.01 means the + /// absolute difference of and must be within +/- + /// 1%. + /// + /// In this example, the two values will be equal if the value of b is within +/- 1% of a. + /// + /// EqualsRelative(a, b, 0.01); + /// + /// + /// + /// + /// The reference value which the tolerance will be calculated against. + /// The value to compare to. + /// The relative tolerance. Must be greater than or equal to 0. + /// True if the two values are equal within the given relative tolerance, otherwise false. + public static bool EqualsRelative(decimal referenceValue, decimal otherValue, decimal tolerance) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + + var maxVariation = Math.Abs(referenceValue * tolerance); + return Math.Abs(referenceValue - otherValue) <= maxVariation; + } + /// /// Checks if two values are equal with a given absolute tolerance. /// @@ -121,5 +210,32 @@ public static bool EqualsAbsolute(double value1, double value2, double tolerance return Math.Abs(value1 - value2) <= tolerance; } + + /// + /// Checks if two values are equal with a given absolute tolerance. + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between + /// and + /// as a fixed number. + /// + /// In this example, the two values will be equal if abs( - + /// ) <= 0.01 + /// + /// Equals(a, b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// The first value. + /// The second value. + /// The absolute tolerance. Must be greater than or equal to 0. + /// True if the two values are equal within the given absolute tolerance, otherwise false. + public static bool EqualsAbsolute(decimal value1, decimal value2, decimal tolerance) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + + return Math.Abs(value1 - value2) <= tolerance; + } } } diff --git a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs index 5d486417ec..8b88ed6197 100644 --- a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs @@ -31,7 +31,7 @@ public partial struct AmountOfSubstance public double NumberOfParticles() { var moles = GetValueAs(AmountOfSubstanceUnit.Mole); - return AvogadroConstant * moles; + return AvogadroConstant * (double) moles; } /// Get from and a given . diff --git a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs index cc0a3cfcdf..b67402cd73 100644 --- a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs @@ -24,7 +24,7 @@ public AmplitudeRatio(ElectricPotential voltage) "The base-10 logarithm of a number ≤ 0 is undefined. Voltage must be greater than 0 V."); // E(dBV) = 20*log10(value(V)/reference(V)) - _value = 20 * Math.Log10(voltage.Volts / 1); + _value = 20 * Math.Log10((double)(voltage.Volts / 1)); _unit = AmplitudeRatioUnit.DecibelVolt; } @@ -40,7 +40,7 @@ public AmplitudeRatio(ElectricPotential voltage) public ElectricPotential ToElectricPotential() { // E(V) = 1V * 10^(E(dBV)/20) - return ElectricPotential.FromVolts( Math.Pow( 10, DecibelVolts / 20 ) ); + return ElectricPotential.FromVolts( Math.Pow( 10, (double)(DecibelVolts / 20) ) ); } /// @@ -51,7 +51,7 @@ public ElectricPotential ToElectricPotential() public PowerRatio ToPowerRatio( ElectricResistance impedance ) { // P(dBW) = E(dBV) - 10*log10(Z(Ω)/1) - return PowerRatio.FromDecibelWatts( DecibelVolts - 10 * Math.Log10( impedance.Ohms / 1 ) ); + return PowerRatio.FromDecibelWatts( DecibelVolts - 10 * Math.Log10( (double)(impedance.Ohms / 1) ) ); } #region Static Methods diff --git a/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs b/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs index 5bd29a877a..46785cd29a 100644 --- a/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs +++ b/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs @@ -1,6 +1,8 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using UnitsNet.Units; + namespace UnitsNet { public partial struct BrakeSpecificFuelConsumption @@ -8,7 +10,7 @@ public partial struct BrakeSpecificFuelConsumption /// Get from times . public static MassFlow operator *(BrakeSpecificFuelConsumption bsfc, Power power) { - return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule*power.Watts); + return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule * power.Watts); } /// Get from divided by . @@ -18,9 +20,9 @@ public partial struct BrakeSpecificFuelConsumption } /// Get constant from times . - public static double operator *(BrakeSpecificFuelConsumption bsfc, SpecificEnergy specificEnergy) + public static QuantityValue operator *(BrakeSpecificFuelConsumption bsfc, SpecificEnergy specificEnergy) { - return specificEnergy.JoulesPerKilogram*bsfc.KilogramsPerJoule; + return specificEnergy.JoulesPerKilogram * bsfc.KilogramsPerJoule; } } } diff --git a/UnitsNet/CustomCode/Quantities/Duration.extra.cs b/UnitsNet/CustomCode/Quantities/Duration.extra.cs index e1e898c62d..537a5d619d 100644 --- a/UnitsNet/CustomCode/Quantities/Duration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Duration.extra.cs @@ -18,19 +18,19 @@ public TimeSpan ToTimeSpan() if ( Seconds > TimeSpan.MaxValue.TotalSeconds || Seconds < TimeSpan.MinValue.TotalSeconds ) throw new ArgumentOutOfRangeException( nameof( Duration ), "The duration is too large or small to fit in a TimeSpan" ); - return TimeSpan.FromTicks((long)(Seconds * TimeSpan.TicksPerSecond)); + return TimeSpan.FromTicks((long)((double)Seconds * TimeSpan.TicksPerSecond)); } /// Get from plus . public static DateTime operator +(DateTime time, Duration duration) { - return time.AddSeconds(duration.Seconds); + return time.AddSeconds((double)duration.Seconds); } /// Get from minus . public static DateTime operator -(DateTime time, Duration duration) { - return time.AddSeconds(-duration.Seconds); + return time.AddSeconds(-(double)duration.Seconds); } /// Explicitly cast to . diff --git a/UnitsNet/CustomCode/Quantities/Force.extra.cs b/UnitsNet/CustomCode/Quantities/Force.extra.cs index 7972c0f412..38f3742e71 100644 --- a/UnitsNet/CustomCode/Quantities/Force.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Force.extra.cs @@ -10,7 +10,7 @@ public partial struct Force /// Get from divided by . public static Force FromPressureByArea(Pressure p, Area area) { - double newtons = p.Pascals * area.SquareMeters; + var newtons = p.Pascals * area.SquareMeters; return new Force(newtons, ForceUnit.Newton); } diff --git a/UnitsNet/CustomCode/Quantities/Length.extra.cs b/UnitsNet/CustomCode/Quantities/Length.extra.cs index 5bb37e2562..ae8e78eb01 100644 --- a/UnitsNet/CustomCode/Quantities/Length.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Length.extra.cs @@ -32,7 +32,7 @@ public FeetInches FeetInches { get { - var inInches = Inches; + var inInches = (double)Inches; var feet = Math.Truncate(inInches / InchesInOneFoot); var inches = inInches % InchesInOneFoot; diff --git a/UnitsNet/CustomCode/Quantities/Mass.extra.cs b/UnitsNet/CustomCode/Quantities/Mass.extra.cs index 3b8f101e7e..f87d867b48 100644 --- a/UnitsNet/CustomCode/Quantities/Mass.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Mass.extra.cs @@ -29,7 +29,7 @@ public StonePounds StonePounds { get { - var inPounds = Pounds; + var inPounds = (double)Pounds; var stones = Math.Truncate(inPounds / StonesInOnePound); var pounds = inPounds % StonesInOnePound; diff --git a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs index e60c5c75d8..dd552aa937 100644 --- a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs @@ -2,6 +2,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using UnitsNet.Units; namespace UnitsNet { diff --git a/UnitsNet/CustomCode/Quantities/Power.extra.cs b/UnitsNet/CustomCode/Quantities/Power.extra.cs index 187c2740fc..024c4f44e9 100644 --- a/UnitsNet/CustomCode/Quantities/Power.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Power.extra.cs @@ -2,6 +2,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using UnitsNet.Units; namespace UnitsNet { @@ -90,7 +91,7 @@ public PowerRatio ToPowerRatio() /// Get from divided by . public static Area operator /(Power power, HeatFlux heatFlux) { - return Area.FromSquareMeters( power.Watts / heatFlux.WattsPerSquareMeter ); + return Area.FromSquareMeters(power.Watts / heatFlux.WattsPerSquareMeter ); } /// Calculate from divided by . diff --git a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs index f563f720ae..3cbc0d9e10 100644 --- a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs @@ -21,7 +21,7 @@ public PowerRatio(Power power) nameof(power), "The base-10 logarithm of a number ≤ 0 is undefined. Power must be greater than 0 W."); // P(dBW) = 10*log10(value(W)/reference(W)) - _value = 10 * Math.Log10(power.Watts / 1); + _value = 10 * Math.Log10((double)power.Watts); _unit = PowerRatioUnit.DecibelWatt; } @@ -37,7 +37,7 @@ public PowerRatio(Power power) public Power ToPower() { // P(W) = 1W * 10^(P(dBW)/10) - return Power.FromWatts(Math.Pow(10, DecibelWatts / 10)); + return Power.FromWatts(Math.Pow(10, (double)(DecibelWatts / 10))); } /// @@ -47,7 +47,7 @@ public Power ToPower() public AmplitudeRatio ToAmplitudeRatio(ElectricResistance impedance) { // E(dBV) = 10*log10(Z(Ω)/1) + P(dBW) - return AmplitudeRatio.FromDecibelVolts(10 * Math.Log10(impedance.Ohms / 1) + DecibelWatts); + return AmplitudeRatio.FromDecibelVolts(10 * Math.Log10((double)(impedance.Ohms / 1)) + DecibelWatts); } #region Static Methods diff --git a/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs b/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs index 45f4473f80..c6d0c172ad 100644 --- a/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs +++ b/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs @@ -24,7 +24,7 @@ public partial struct SpecificEnergy } /// Get from times . - public static double operator *(SpecificEnergy specificEnergy, BrakeSpecificFuelConsumption bsfc) + public static QuantityValue operator *(SpecificEnergy specificEnergy, BrakeSpecificFuelConsumption bsfc) { return specificEnergy.JoulesPerKilogram * bsfc.KilogramsPerJoule; } diff --git a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs index 4556009fc6..60b411f358 100644 --- a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs @@ -60,7 +60,7 @@ public partial struct Temperature /// The resulting . public Temperature Multiply(double factor, TemperatureUnit unit) { - double resultInUnit = As(unit) * factor; + var resultInUnit = As(unit) * factor; return From(resultInUnit, unit); } @@ -77,7 +77,7 @@ public Temperature Multiply(double factor, TemperatureUnit unit) /// The resulting . public Temperature Divide(double divisor, TemperatureUnit unit) { - double resultInUnit = As(unit) / divisor; + var resultInUnit = As(unit) / divisor; return From(resultInUnit, unit); } } diff --git a/UnitsNet/CustomCode/Quantities/Volume.extra.cs b/UnitsNet/CustomCode/Quantities/Volume.extra.cs index aab43915a4..1debb193e1 100644 --- a/UnitsNet/CustomCode/Quantities/Volume.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Volume.extra.cs @@ -34,7 +34,7 @@ public partial struct Volume /// Get from divided by . public static TimeSpan operator /(Volume volume, VolumeFlow volumeFlow) { - return TimeSpan.FromSeconds(volume.CubicMeters / volumeFlow.CubicMetersPerSecond); + return TimeSpan.FromSeconds((double)(volume.CubicMeters / volumeFlow.CubicMetersPerSecond)); } } } diff --git a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs index 5291b7d77b..dea64fb637 100644 --- a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs +++ b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs @@ -130,7 +130,7 @@ private Pressure As(PressureReference reference) /// /// The to convert to. /// The value of pressure at - private double AsBaseNumericType(PressureReference reference) + private QuantityValue AsBaseNumericType(PressureReference reference) { var baseReferenceValue = AsBaseReference(); @@ -156,7 +156,7 @@ private double AsBaseNumericType(PressureReference reference) /// /// /// The value of pressure at the - private double AsBaseReference() + private QuantityValue AsBaseReference() { switch (Reference) { diff --git a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs index 820cb3a395..082b101238 100644 --- a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration. /// [DataContract] - public partial struct Acceleration : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Acceleration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -85,9 +85,9 @@ static Acceleration() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Acceleration(double value, AccelerationUnit unit) + public Acceleration(QuantityValue value, AccelerationUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -99,14 +99,14 @@ public Acceleration(double value, AccelerationUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Acceleration(double value, UnitSystem unitSystem) + public Acceleration(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -147,7 +147,10 @@ public Acceleration(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -170,74 +173,74 @@ public Acceleration(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentimetersPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); + public QuantityValue CentimetersPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimetersPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); + public QuantityValue DecimetersPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); + public QuantityValue FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); + public QuantityValue InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilometersPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); + public QuantityValue KilometersPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KnotsPerHour => As(AccelerationUnit.KnotPerHour); + public QuantityValue KnotsPerHour => As(AccelerationUnit.KnotPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); + public QuantityValue KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); + public QuantityValue KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetersPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); + public QuantityValue MetersPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrometersPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); + public QuantityValue MicrometersPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimetersPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); + public QuantityValue MillimetersPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillistandardGravity => As(AccelerationUnit.MillistandardGravity); + public QuantityValue MillistandardGravity => As(AccelerationUnit.MillistandardGravity); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanometersPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); + public QuantityValue NanometersPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardGravity => As(AccelerationUnit.StandardGravity); + public QuantityValue StandardGravity => As(AccelerationUnit.StandardGravity); #endregion @@ -346,7 +349,7 @@ public static string GetAbbreviation(AccelerationUnit unit, IFormatProvider? pro /// If value is NaN or Infinity. public static Acceleration FromCentimetersPerSecondSquared(QuantityValue centimeterspersecondsquared) { - double value = (double) centimeterspersecondsquared; + QuantityValue value = (QuantityValue) centimeterspersecondsquared; return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); } @@ -356,7 +359,7 @@ public static Acceleration FromCentimetersPerSecondSquared(QuantityValue centime /// If value is NaN or Infinity. public static Acceleration FromDecimetersPerSecondSquared(QuantityValue decimeterspersecondsquared) { - double value = (double) decimeterspersecondsquared; + QuantityValue value = (QuantityValue) decimeterspersecondsquared; return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); } @@ -366,7 +369,7 @@ public static Acceleration FromDecimetersPerSecondSquared(QuantityValue decimete /// If value is NaN or Infinity. public static Acceleration FromFeetPerSecondSquared(QuantityValue feetpersecondsquared) { - double value = (double) feetpersecondsquared; + QuantityValue value = (QuantityValue) feetpersecondsquared; return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); } @@ -376,7 +379,7 @@ public static Acceleration FromFeetPerSecondSquared(QuantityValue feetperseconds /// If value is NaN or Infinity. public static Acceleration FromInchesPerSecondSquared(QuantityValue inchespersecondsquared) { - double value = (double) inchespersecondsquared; + QuantityValue value = (QuantityValue) inchespersecondsquared; return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); } @@ -386,7 +389,7 @@ public static Acceleration FromInchesPerSecondSquared(QuantityValue inchespersec /// If value is NaN or Infinity. public static Acceleration FromKilometersPerSecondSquared(QuantityValue kilometerspersecondsquared) { - double value = (double) kilometerspersecondsquared; + QuantityValue value = (QuantityValue) kilometerspersecondsquared; return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); } @@ -396,7 +399,7 @@ public static Acceleration FromKilometersPerSecondSquared(QuantityValue kilomete /// If value is NaN or Infinity. public static Acceleration FromKnotsPerHour(QuantityValue knotsperhour) { - double value = (double) knotsperhour; + QuantityValue value = (QuantityValue) knotsperhour; return new Acceleration(value, AccelerationUnit.KnotPerHour); } @@ -406,7 +409,7 @@ public static Acceleration FromKnotsPerHour(QuantityValue knotsperhour) /// If value is NaN or Infinity. public static Acceleration FromKnotsPerMinute(QuantityValue knotsperminute) { - double value = (double) knotsperminute; + QuantityValue value = (QuantityValue) knotsperminute; return new Acceleration(value, AccelerationUnit.KnotPerMinute); } @@ -416,7 +419,7 @@ public static Acceleration FromKnotsPerMinute(QuantityValue knotsperminute) /// If value is NaN or Infinity. public static Acceleration FromKnotsPerSecond(QuantityValue knotspersecond) { - double value = (double) knotspersecond; + QuantityValue value = (QuantityValue) knotspersecond; return new Acceleration(value, AccelerationUnit.KnotPerSecond); } @@ -426,7 +429,7 @@ public static Acceleration FromKnotsPerSecond(QuantityValue knotspersecond) /// If value is NaN or Infinity. public static Acceleration FromMetersPerSecondSquared(QuantityValue meterspersecondsquared) { - double value = (double) meterspersecondsquared; + QuantityValue value = (QuantityValue) meterspersecondsquared; return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); } @@ -436,7 +439,7 @@ public static Acceleration FromMetersPerSecondSquared(QuantityValue meterspersec /// If value is NaN or Infinity. public static Acceleration FromMicrometersPerSecondSquared(QuantityValue micrometerspersecondsquared) { - double value = (double) micrometerspersecondsquared; + QuantityValue value = (QuantityValue) micrometerspersecondsquared; return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); } @@ -446,7 +449,7 @@ public static Acceleration FromMicrometersPerSecondSquared(QuantityValue microme /// If value is NaN or Infinity. public static Acceleration FromMillimetersPerSecondSquared(QuantityValue millimeterspersecondsquared) { - double value = (double) millimeterspersecondsquared; + QuantityValue value = (QuantityValue) millimeterspersecondsquared; return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); } @@ -456,7 +459,7 @@ public static Acceleration FromMillimetersPerSecondSquared(QuantityValue millime /// If value is NaN or Infinity. public static Acceleration FromMillistandardGravity(QuantityValue millistandardgravity) { - double value = (double) millistandardgravity; + QuantityValue value = (QuantityValue) millistandardgravity; return new Acceleration(value, AccelerationUnit.MillistandardGravity); } @@ -466,7 +469,7 @@ public static Acceleration FromMillistandardGravity(QuantityValue millistandardg /// If value is NaN or Infinity. public static Acceleration FromNanometersPerSecondSquared(QuantityValue nanometerspersecondsquared) { - double value = (double) nanometerspersecondsquared; + QuantityValue value = (QuantityValue) nanometerspersecondsquared; return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); } @@ -476,7 +479,7 @@ public static Acceleration FromNanometersPerSecondSquared(QuantityValue nanomete /// If value is NaN or Infinity. public static Acceleration FromStandardGravity(QuantityValue standardgravity) { - double value = (double) standardgravity; + QuantityValue value = (QuantityValue) standardgravity; return new Acceleration(value, AccelerationUnit.StandardGravity); } @@ -488,7 +491,7 @@ public static Acceleration FromStandardGravity(QuantityValue standardgravity) /// Acceleration unit value. public static Acceleration From(QuantityValue value, AccelerationUnit fromUnit) { - return new Acceleration((double)value, fromUnit); + return new Acceleration((QuantityValue)value, fromUnit); } #endregion @@ -658,25 +661,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Accel } /// Get from multiplying value and . - public static Acceleration operator *(double left, Acceleration right) + public static Acceleration operator *(QuantityValue left, Acceleration right) { return new Acceleration(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Acceleration operator *(Acceleration left, double right) + public static Acceleration operator *(Acceleration left, QuantityValue right) { return new Acceleration(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Acceleration operator /(Acceleration left, double right) + public static Acceleration operator /(Acceleration left, QuantityValue right) { return new Acceleration(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Acceleration left, Acceleration right) + public static QuantityValue operator /(Acceleration left, Acceleration right) { return left.MetersPerSecondSquared / right.MetersPerSecondSquared; } @@ -709,6 +712,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Accel return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Acceleration left, Acceleration right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Acceleration left, Acceleration right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -721,7 +737,29 @@ public int CompareTo(object obj) /// public int CompareTo(Acceleration other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Acceleration objAcceleration)) + return false; + return Equals(objAcceleration); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Acceleration other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -764,13 +802,13 @@ public int CompareTo(Acceleration other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Acceleration other, double tolerance, ComparisonType comparisonType) + public bool Equals(Acceleration other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -781,7 +819,7 @@ public bool Equals(Acceleration other, double tolerance, ComparisonType comparis /// A hash code for the current Acceleration. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -792,17 +830,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(AccelerationUnit unit) + public QuantityValue As(AccelerationUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -817,12 +854,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is AccelerationUnit unitAsAccelerationUnit)) + if (!(unit is AccelerationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AccelerationUnit)} is supported.", nameof(unit)); - return As(unitAsAccelerationUnit); + return (QuantityValue)As(typedUnit); } /// @@ -854,7 +891,7 @@ public Acceleration ToUnit(AccelerationUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Acceleration)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(AccelerationUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -862,17 +899,17 @@ public Acceleration ToUnit(AccelerationUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AccelerationUnit unitAsAccelerationUnit)) + if (!(unit is AccelerationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AccelerationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAccelerationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -899,10 +936,10 @@ public Acceleration ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(AccelerationUnit unit) + private QuantityValue GetValueAs(AccelerationUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs index 6b796bdd8a..31197dbed3 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals. /// [DataContract] - public partial struct AmountOfSubstance : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct AmountOfSubstance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -86,9 +86,9 @@ static AmountOfSubstance() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public AmountOfSubstance(double value, AmountOfSubstanceUnit unit) + public AmountOfSubstance(QuantityValue value, AmountOfSubstanceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -100,14 +100,14 @@ public AmountOfSubstance(double value, AmountOfSubstanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public AmountOfSubstance(double value, UnitSystem unitSystem) + public AmountOfSubstance(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -148,7 +148,10 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -171,79 +174,79 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Centimoles => As(AmountOfSubstanceUnit.Centimole); + public QuantityValue Centimoles => As(AmountOfSubstanceUnit.Centimole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); + public QuantityValue CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decimoles => As(AmountOfSubstanceUnit.Decimole); + public QuantityValue Decimoles => As(AmountOfSubstanceUnit.Decimole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); + public QuantityValue DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilomoles => As(AmountOfSubstanceUnit.Kilomole); + public QuantityValue Kilomoles => As(AmountOfSubstanceUnit.Kilomole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); + public QuantityValue KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megamoles => As(AmountOfSubstanceUnit.Megamole); + public QuantityValue Megamoles => As(AmountOfSubstanceUnit.Megamole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Micromoles => As(AmountOfSubstanceUnit.Micromole); + public QuantityValue Micromoles => As(AmountOfSubstanceUnit.Micromole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); + public QuantityValue MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millimoles => As(AmountOfSubstanceUnit.Millimole); + public QuantityValue Millimoles => As(AmountOfSubstanceUnit.Millimole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); + public QuantityValue MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Moles => As(AmountOfSubstanceUnit.Mole); + public QuantityValue Moles => As(AmountOfSubstanceUnit.Mole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanomoles => As(AmountOfSubstanceUnit.Nanomole); + public QuantityValue Nanomoles => As(AmountOfSubstanceUnit.Nanomole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); + public QuantityValue NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundMoles => As(AmountOfSubstanceUnit.PoundMole); + public QuantityValue PoundMoles => As(AmountOfSubstanceUnit.PoundMole); #endregion @@ -341,7 +344,7 @@ public static string GetAbbreviation(AmountOfSubstanceUnit unit, IFormatProvider /// If value is NaN or Infinity. public static AmountOfSubstance FromCentimoles(QuantityValue centimoles) { - double value = (double) centimoles; + QuantityValue value = (QuantityValue) centimoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); } @@ -351,7 +354,7 @@ public static AmountOfSubstance FromCentimoles(QuantityValue centimoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromCentipoundMoles(QuantityValue centipoundmoles) { - double value = (double) centipoundmoles; + QuantityValue value = (QuantityValue) centipoundmoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); } @@ -361,7 +364,7 @@ public static AmountOfSubstance FromCentipoundMoles(QuantityValue centipoundmole /// If value is NaN or Infinity. public static AmountOfSubstance FromDecimoles(QuantityValue decimoles) { - double value = (double) decimoles; + QuantityValue value = (QuantityValue) decimoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); } @@ -371,7 +374,7 @@ public static AmountOfSubstance FromDecimoles(QuantityValue decimoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromDecipoundMoles(QuantityValue decipoundmoles) { - double value = (double) decipoundmoles; + QuantityValue value = (QuantityValue) decipoundmoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); } @@ -381,7 +384,7 @@ public static AmountOfSubstance FromDecipoundMoles(QuantityValue decipoundmoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromKilomoles(QuantityValue kilomoles) { - double value = (double) kilomoles; + QuantityValue value = (QuantityValue) kilomoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); } @@ -391,7 +394,7 @@ public static AmountOfSubstance FromKilomoles(QuantityValue kilomoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromKilopoundMoles(QuantityValue kilopoundmoles) { - double value = (double) kilopoundmoles; + QuantityValue value = (QuantityValue) kilopoundmoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); } @@ -401,7 +404,7 @@ public static AmountOfSubstance FromKilopoundMoles(QuantityValue kilopoundmoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromMegamoles(QuantityValue megamoles) { - double value = (double) megamoles; + QuantityValue value = (QuantityValue) megamoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.Megamole); } @@ -411,7 +414,7 @@ public static AmountOfSubstance FromMegamoles(QuantityValue megamoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromMicromoles(QuantityValue micromoles) { - double value = (double) micromoles; + QuantityValue value = (QuantityValue) micromoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); } @@ -421,7 +424,7 @@ public static AmountOfSubstance FromMicromoles(QuantityValue micromoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromMicropoundMoles(QuantityValue micropoundmoles) { - double value = (double) micropoundmoles; + QuantityValue value = (QuantityValue) micropoundmoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); } @@ -431,7 +434,7 @@ public static AmountOfSubstance FromMicropoundMoles(QuantityValue micropoundmole /// If value is NaN or Infinity. public static AmountOfSubstance FromMillimoles(QuantityValue millimoles) { - double value = (double) millimoles; + QuantityValue value = (QuantityValue) millimoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); } @@ -441,7 +444,7 @@ public static AmountOfSubstance FromMillimoles(QuantityValue millimoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromMillipoundMoles(QuantityValue millipoundmoles) { - double value = (double) millipoundmoles; + QuantityValue value = (QuantityValue) millipoundmoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); } @@ -451,7 +454,7 @@ public static AmountOfSubstance FromMillipoundMoles(QuantityValue millipoundmole /// If value is NaN or Infinity. public static AmountOfSubstance FromMoles(QuantityValue moles) { - double value = (double) moles; + QuantityValue value = (QuantityValue) moles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); } @@ -461,7 +464,7 @@ public static AmountOfSubstance FromMoles(QuantityValue moles) /// If value is NaN or Infinity. public static AmountOfSubstance FromNanomoles(QuantityValue nanomoles) { - double value = (double) nanomoles; + QuantityValue value = (QuantityValue) nanomoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); } @@ -471,7 +474,7 @@ public static AmountOfSubstance FromNanomoles(QuantityValue nanomoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromNanopoundMoles(QuantityValue nanopoundmoles) { - double value = (double) nanopoundmoles; + QuantityValue value = (QuantityValue) nanopoundmoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); } @@ -481,7 +484,7 @@ public static AmountOfSubstance FromNanopoundMoles(QuantityValue nanopoundmoles) /// If value is NaN or Infinity. public static AmountOfSubstance FromPoundMoles(QuantityValue poundmoles) { - double value = (double) poundmoles; + QuantityValue value = (QuantityValue) poundmoles; return new AmountOfSubstance(value, AmountOfSubstanceUnit.PoundMole); } @@ -493,7 +496,7 @@ public static AmountOfSubstance FromPoundMoles(QuantityValue poundmoles) /// AmountOfSubstance unit value. public static AmountOfSubstance From(QuantityValue value, AmountOfSubstanceUnit fromUnit) { - return new AmountOfSubstance((double)value, fromUnit); + return new AmountOfSubstance((QuantityValue)value, fromUnit); } #endregion @@ -663,25 +666,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Amoun } /// Get from multiplying value and . - public static AmountOfSubstance operator *(double left, AmountOfSubstance right) + public static AmountOfSubstance operator *(QuantityValue left, AmountOfSubstance right) { return new AmountOfSubstance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static AmountOfSubstance operator *(AmountOfSubstance left, double right) + public static AmountOfSubstance operator *(AmountOfSubstance left, QuantityValue right) { return new AmountOfSubstance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static AmountOfSubstance operator /(AmountOfSubstance left, double right) + public static AmountOfSubstance operator /(AmountOfSubstance left, QuantityValue right) { return new AmountOfSubstance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(AmountOfSubstance left, AmountOfSubstance right) + public static QuantityValue operator /(AmountOfSubstance left, AmountOfSubstance right) { return left.Moles / right.Moles; } @@ -714,6 +717,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Amoun return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(AmountOfSubstance left, AmountOfSubstance right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -726,7 +742,29 @@ public int CompareTo(object obj) /// public int CompareTo(AmountOfSubstance other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is AmountOfSubstance objAmountOfSubstance)) + return false; + return Equals(objAmountOfSubstance); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(AmountOfSubstance other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -769,13 +807,13 @@ public int CompareTo(AmountOfSubstance other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AmountOfSubstance other, double tolerance, ComparisonType comparisonType) + public bool Equals(AmountOfSubstance other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -786,7 +824,7 @@ public bool Equals(AmountOfSubstance other, double tolerance, ComparisonType com /// A hash code for the current AmountOfSubstance. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -797,17 +835,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(AmountOfSubstanceUnit unit) + public QuantityValue As(AmountOfSubstanceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -822,12 +859,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is AmountOfSubstanceUnit unitAsAmountOfSubstanceUnit)) + if (!(unit is AmountOfSubstanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmountOfSubstanceUnit)} is supported.", nameof(unit)); - return As(unitAsAmountOfSubstanceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -859,7 +896,7 @@ public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit, UnitConverter unitCo var converted = conversionFunction(this); return (AmountOfSubstance)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(AmountOfSubstanceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -867,17 +904,17 @@ public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit, UnitConverter unitCo } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AmountOfSubstanceUnit unitAsAmountOfSubstanceUnit)) + if (!(unit is AmountOfSubstanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmountOfSubstanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAmountOfSubstanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -904,10 +941,10 @@ public AmountOfSubstance ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(AmountOfSubstanceUnit unit) + private QuantityValue GetValueAs(AmountOfSubstanceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs index 05d7dfc95a..1a13590478 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. /// [DataContract] - public partial struct AmplitudeRatio : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct AmplitudeRatio : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static AmplitudeRatio() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public AmplitudeRatio(double value, AmplitudeRatioUnit unit) + public AmplitudeRatio(QuantityValue value, AmplitudeRatioUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public AmplitudeRatio(double value, AmplitudeRatioUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public AmplitudeRatio(double value, UnitSystem unitSystem) + public AmplitudeRatio(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public AmplitudeRatio(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,24 +163,24 @@ public AmplitudeRatio(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); + public QuantityValue DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); + public QuantityValue DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); + public QuantityValue DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); + public QuantityValue DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); #endregion @@ -242,7 +245,7 @@ public static string GetAbbreviation(AmplitudeRatioUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue decibelmicrovolts) { - double value = (double) decibelmicrovolts; + QuantityValue value = (QuantityValue) decibelmicrovolts; return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); } @@ -252,7 +255,7 @@ public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue decibelmicrovol /// If value is NaN or Infinity. public static AmplitudeRatio FromDecibelMillivolts(QuantityValue decibelmillivolts) { - double value = (double) decibelmillivolts; + QuantityValue value = (QuantityValue) decibelmillivolts; return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); } @@ -262,7 +265,7 @@ public static AmplitudeRatio FromDecibelMillivolts(QuantityValue decibelmillivol /// If value is NaN or Infinity. public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue decibelsunloaded) { - double value = (double) decibelsunloaded; + QuantityValue value = (QuantityValue) decibelsunloaded; return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); } @@ -272,7 +275,7 @@ public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue decibelsunloaded /// If value is NaN or Infinity. public static AmplitudeRatio FromDecibelVolts(QuantityValue decibelvolts) { - double value = (double) decibelvolts; + QuantityValue value = (QuantityValue) decibelvolts; return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelVolt); } @@ -284,7 +287,7 @@ public static AmplitudeRatio FromDecibelVolts(QuantityValue decibelvolts) /// AmplitudeRatio unit value. public static AmplitudeRatio From(QuantityValue value, AmplitudeRatioUnit fromUnit) { - return new AmplitudeRatio((double)value, fromUnit); + return new AmplitudeRatio((QuantityValue)value, fromUnit); } #endregion @@ -446,7 +449,7 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ampli { // Logarithmic addition // Formula: 20 * log10(10^(x/20) + 10^(y/20)) - return new AmplitudeRatio(20 * Math.Log10(Math.Pow(10, left.Value/20) + Math.Pow(10, right.GetValueAs(left.Unit)/20)), left.Unit); + return new AmplitudeRatio(20 * Math.Log10(Math.Pow(10, (double)left.Value/20) + Math.Pow(10, (double)right.GetValueAs(left.Unit)/20)), left.Unit); } /// Get from logarithmic subtraction of two . @@ -454,11 +457,11 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ampli { // Logarithmic subtraction // Formula: 20 * log10(10^(x/20) - 10^(y/20)) - return new AmplitudeRatio(20 * Math.Log10(Math.Pow(10, left.Value/20) - Math.Pow(10, right.GetValueAs(left.Unit)/20)), left.Unit); + return new AmplitudeRatio(20 * Math.Log10(Math.Pow(10, (double)left.Value/20) - Math.Pow(10, (double)right.GetValueAs(left.Unit)/20)), left.Unit); } /// Get from logarithmic multiplication of value and . - public static AmplitudeRatio operator *(double left, AmplitudeRatio right) + public static AmplitudeRatio operator *(QuantityValue left, AmplitudeRatio right) { // Logarithmic multiplication = addition return new AmplitudeRatio(left + right.Value, right.Unit); @@ -468,14 +471,14 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ampli public static AmplitudeRatio operator *(AmplitudeRatio left, double right) { // Logarithmic multiplication = addition - return new AmplitudeRatio(left.Value + (double)right, left.Unit); + return new AmplitudeRatio(left.Value + (QuantityValue)right, left.Unit); } /// Get from logarithmic division of by value. public static AmplitudeRatio operator /(AmplitudeRatio left, double right) { // Logarithmic division = subtraction - return new AmplitudeRatio(left.Value - (double)right, left.Unit); + return new AmplitudeRatio(left.Value - (QuantityValue)right, left.Unit); } /// Get ratio value from logarithmic division of by . @@ -513,6 +516,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ampli return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(AmplitudeRatio left, AmplitudeRatio right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(AmplitudeRatio left, AmplitudeRatio right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -525,7 +541,29 @@ public int CompareTo(object obj) /// public int CompareTo(AmplitudeRatio other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is AmplitudeRatio objAmplitudeRatio)) + return false; + return Equals(objAmplitudeRatio); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(AmplitudeRatio other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -568,13 +606,13 @@ public int CompareTo(AmplitudeRatio other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AmplitudeRatio other, double tolerance, ComparisonType comparisonType) + public bool Equals(AmplitudeRatio other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -585,7 +623,7 @@ public bool Equals(AmplitudeRatio other, double tolerance, ComparisonType compar /// A hash code for the current AmplitudeRatio. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -596,17 +634,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(AmplitudeRatioUnit unit) + public QuantityValue As(AmplitudeRatioUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -621,12 +658,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is AmplitudeRatioUnit unitAsAmplitudeRatioUnit)) + if (!(unit is AmplitudeRatioUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmplitudeRatioUnit)} is supported.", nameof(unit)); - return As(unitAsAmplitudeRatioUnit); + return (QuantityValue)As(typedUnit); } /// @@ -658,7 +695,7 @@ public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (AmplitudeRatio)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(AmplitudeRatioUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -666,17 +703,17 @@ public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AmplitudeRatioUnit unitAsAmplitudeRatioUnit)) + if (!(unit is AmplitudeRatioUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmplitudeRatioUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAmplitudeRatioUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -703,10 +740,10 @@ public AmplitudeRatio ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(AmplitudeRatioUnit unit) + private QuantityValue GetValueAs(AmplitudeRatioUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs index 55d9a88517..210b47270f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. /// [DataContract] - public partial struct Angle : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Angle : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -87,9 +87,9 @@ static Angle() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Angle(double value, AngleUnit unit) + public Angle(QuantityValue value, AngleUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -101,14 +101,14 @@ public Angle(double value, AngleUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Angle(double value, UnitSystem unitSystem) + public Angle(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -149,7 +149,10 @@ public Angle(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -172,84 +175,84 @@ public Angle(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Arcminutes => As(AngleUnit.Arcminute); + public QuantityValue Arcminutes => As(AngleUnit.Arcminute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Arcseconds => As(AngleUnit.Arcsecond); + public QuantityValue Arcseconds => As(AngleUnit.Arcsecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Centiradians => As(AngleUnit.Centiradian); + public QuantityValue Centiradians => As(AngleUnit.Centiradian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Deciradians => As(AngleUnit.Deciradian); + public QuantityValue Deciradians => As(AngleUnit.Deciradian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Degrees => As(AngleUnit.Degree); + public QuantityValue Degrees => As(AngleUnit.Degree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gradians => As(AngleUnit.Gradian); + public QuantityValue Gradians => As(AngleUnit.Gradian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microdegrees => As(AngleUnit.Microdegree); + public QuantityValue Microdegrees => As(AngleUnit.Microdegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microradians => As(AngleUnit.Microradian); + public QuantityValue Microradians => As(AngleUnit.Microradian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millidegrees => As(AngleUnit.Millidegree); + public QuantityValue Millidegrees => As(AngleUnit.Millidegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milliradians => As(AngleUnit.Milliradian); + public QuantityValue Milliradians => As(AngleUnit.Milliradian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanodegrees => As(AngleUnit.Nanodegree); + public QuantityValue Nanodegrees => As(AngleUnit.Nanodegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanoradians => As(AngleUnit.Nanoradian); + public QuantityValue Nanoradians => As(AngleUnit.Nanoradian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NatoMils => As(AngleUnit.NatoMil); + public QuantityValue NatoMils => As(AngleUnit.NatoMil); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Radians => As(AngleUnit.Radian); + public QuantityValue Radians => As(AngleUnit.Radian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Revolutions => As(AngleUnit.Revolution); + public QuantityValue Revolutions => As(AngleUnit.Revolution); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Tilt => As(AngleUnit.Tilt); + public QuantityValue Tilt => As(AngleUnit.Tilt); #endregion @@ -276,7 +279,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) 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)); + unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Tilt, quantity => new Angle(Math.Sin((double)quantity.Value / 180 * Math.PI), AngleUnit.Tilt)); // Register in unit converter: BaseUnit <-> BaseUnit unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Degree, quantity => quantity); @@ -296,7 +299,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) 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)); + unitConverter.SetConversionFunction(AngleUnit.Tilt, AngleUnit.Degree, quantity => new Angle(Math.Asin((double)quantity.Value) * 180 / Math.PI, AngleUnit.Degree)); } internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) @@ -362,7 +365,7 @@ public static string GetAbbreviation(AngleUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Angle FromArcminutes(QuantityValue arcminutes) { - double value = (double) arcminutes; + QuantityValue value = (QuantityValue) arcminutes; return new Angle(value, AngleUnit.Arcminute); } @@ -372,7 +375,7 @@ public static Angle FromArcminutes(QuantityValue arcminutes) /// If value is NaN or Infinity. public static Angle FromArcseconds(QuantityValue arcseconds) { - double value = (double) arcseconds; + QuantityValue value = (QuantityValue) arcseconds; return new Angle(value, AngleUnit.Arcsecond); } @@ -382,7 +385,7 @@ public static Angle FromArcseconds(QuantityValue arcseconds) /// If value is NaN or Infinity. public static Angle FromCentiradians(QuantityValue centiradians) { - double value = (double) centiradians; + QuantityValue value = (QuantityValue) centiradians; return new Angle(value, AngleUnit.Centiradian); } @@ -392,7 +395,7 @@ public static Angle FromCentiradians(QuantityValue centiradians) /// If value is NaN or Infinity. public static Angle FromDeciradians(QuantityValue deciradians) { - double value = (double) deciradians; + QuantityValue value = (QuantityValue) deciradians; return new Angle(value, AngleUnit.Deciradian); } @@ -402,7 +405,7 @@ public static Angle FromDeciradians(QuantityValue deciradians) /// If value is NaN or Infinity. public static Angle FromDegrees(QuantityValue degrees) { - double value = (double) degrees; + QuantityValue value = (QuantityValue) degrees; return new Angle(value, AngleUnit.Degree); } @@ -412,7 +415,7 @@ public static Angle FromDegrees(QuantityValue degrees) /// If value is NaN or Infinity. public static Angle FromGradians(QuantityValue gradians) { - double value = (double) gradians; + QuantityValue value = (QuantityValue) gradians; return new Angle(value, AngleUnit.Gradian); } @@ -422,7 +425,7 @@ public static Angle FromGradians(QuantityValue gradians) /// If value is NaN or Infinity. public static Angle FromMicrodegrees(QuantityValue microdegrees) { - double value = (double) microdegrees; + QuantityValue value = (QuantityValue) microdegrees; return new Angle(value, AngleUnit.Microdegree); } @@ -432,7 +435,7 @@ public static Angle FromMicrodegrees(QuantityValue microdegrees) /// If value is NaN or Infinity. public static Angle FromMicroradians(QuantityValue microradians) { - double value = (double) microradians; + QuantityValue value = (QuantityValue) microradians; return new Angle(value, AngleUnit.Microradian); } @@ -442,7 +445,7 @@ public static Angle FromMicroradians(QuantityValue microradians) /// If value is NaN or Infinity. public static Angle FromMillidegrees(QuantityValue millidegrees) { - double value = (double) millidegrees; + QuantityValue value = (QuantityValue) millidegrees; return new Angle(value, AngleUnit.Millidegree); } @@ -452,7 +455,7 @@ public static Angle FromMillidegrees(QuantityValue millidegrees) /// If value is NaN or Infinity. public static Angle FromMilliradians(QuantityValue milliradians) { - double value = (double) milliradians; + QuantityValue value = (QuantityValue) milliradians; return new Angle(value, AngleUnit.Milliradian); } @@ -462,7 +465,7 @@ public static Angle FromMilliradians(QuantityValue milliradians) /// If value is NaN or Infinity. public static Angle FromNanodegrees(QuantityValue nanodegrees) { - double value = (double) nanodegrees; + QuantityValue value = (QuantityValue) nanodegrees; return new Angle(value, AngleUnit.Nanodegree); } @@ -472,7 +475,7 @@ public static Angle FromNanodegrees(QuantityValue nanodegrees) /// If value is NaN or Infinity. public static Angle FromNanoradians(QuantityValue nanoradians) { - double value = (double) nanoradians; + QuantityValue value = (QuantityValue) nanoradians; return new Angle(value, AngleUnit.Nanoradian); } @@ -482,7 +485,7 @@ public static Angle FromNanoradians(QuantityValue nanoradians) /// If value is NaN or Infinity. public static Angle FromNatoMils(QuantityValue natomils) { - double value = (double) natomils; + QuantityValue value = (QuantityValue) natomils; return new Angle(value, AngleUnit.NatoMil); } @@ -492,7 +495,7 @@ public static Angle FromNatoMils(QuantityValue natomils) /// If value is NaN or Infinity. public static Angle FromRadians(QuantityValue radians) { - double value = (double) radians; + QuantityValue value = (QuantityValue) radians; return new Angle(value, AngleUnit.Radian); } @@ -502,7 +505,7 @@ public static Angle FromRadians(QuantityValue radians) /// If value is NaN or Infinity. public static Angle FromRevolutions(QuantityValue revolutions) { - double value = (double) revolutions; + QuantityValue value = (QuantityValue) revolutions; return new Angle(value, AngleUnit.Revolution); } @@ -512,7 +515,7 @@ public static Angle FromRevolutions(QuantityValue revolutions) /// If value is NaN or Infinity. public static Angle FromTilt(QuantityValue tilt) { - double value = (double) tilt; + QuantityValue value = (QuantityValue) tilt; return new Angle(value, AngleUnit.Tilt); } @@ -524,7 +527,7 @@ public static Angle FromTilt(QuantityValue tilt) /// Angle unit value. public static Angle From(QuantityValue value, AngleUnit fromUnit) { - return new Angle((double)value, fromUnit); + return new Angle((QuantityValue)value, fromUnit); } #endregion @@ -694,25 +697,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Angle } /// Get from multiplying value and . - public static Angle operator *(double left, Angle right) + public static Angle operator *(QuantityValue left, Angle right) { return new Angle(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Angle operator *(Angle left, double right) + public static Angle operator *(Angle left, QuantityValue right) { return new Angle(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Angle operator /(Angle left, double right) + public static Angle operator /(Angle left, QuantityValue right) { return new Angle(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Angle left, Angle right) + public static QuantityValue operator /(Angle left, Angle right) { return left.Degrees / right.Degrees; } @@ -745,6 +748,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Angle return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Angle left, Angle right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Angle left, Angle right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -757,7 +773,29 @@ public int CompareTo(object obj) /// public int CompareTo(Angle other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Angle objAngle)) + return false; + return Equals(objAngle); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Angle other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -800,13 +838,13 @@ public int CompareTo(Angle other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Angle other, double tolerance, ComparisonType comparisonType) + public bool Equals(Angle other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -817,7 +855,7 @@ public bool Equals(Angle other, double tolerance, ComparisonType comparisonType) /// A hash code for the current Angle. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -828,17 +866,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(AngleUnit unit) + public QuantityValue As(AngleUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -853,12 +890,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is AngleUnit unitAsAngleUnit)) + if (!(unit is AngleUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AngleUnit)} is supported.", nameof(unit)); - return As(unitAsAngleUnit); + return (QuantityValue)As(typedUnit); } /// @@ -890,7 +927,7 @@ public Angle ToUnit(AngleUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Angle)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(AngleUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -898,17 +935,17 @@ public Angle ToUnit(AngleUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AngleUnit unitAsAngleUnit)) + if (!(unit is AngleUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AngleUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAngleUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -935,10 +972,10 @@ public Angle ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(AngleUnit unit) + private QuantityValue GetValueAs(AngleUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs index db89646bfd..fc7df3950d 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules. /// [DataContract] - public partial struct ApparentEnergy : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ApparentEnergy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -74,9 +74,9 @@ static ApparentEnergy() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ApparentEnergy(double value, ApparentEnergyUnit unit) + public ApparentEnergy(QuantityValue value, ApparentEnergyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -88,14 +88,14 @@ public ApparentEnergy(double value, ApparentEnergyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ApparentEnergy(double value, UnitSystem unitSystem) + public ApparentEnergy(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -136,7 +136,10 @@ public ApparentEnergy(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -159,19 +162,19 @@ public ApparentEnergy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilovoltampereHours => As(ApparentEnergyUnit.KilovoltampereHour); + public QuantityValue KilovoltampereHours => As(ApparentEnergyUnit.KilovoltampereHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegavoltampereHours => As(ApparentEnergyUnit.MegavoltampereHour); + public QuantityValue MegavoltampereHours => As(ApparentEnergyUnit.MegavoltampereHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltampereHours => As(ApparentEnergyUnit.VoltampereHour); + public QuantityValue VoltampereHours => As(ApparentEnergyUnit.VoltampereHour); #endregion @@ -233,7 +236,7 @@ public static string GetAbbreviation(ApparentEnergyUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static ApparentEnergy FromKilovoltampereHours(QuantityValue kilovoltamperehours) { - double value = (double) kilovoltamperehours; + QuantityValue value = (QuantityValue) kilovoltamperehours; return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); } @@ -243,7 +246,7 @@ public static ApparentEnergy FromKilovoltampereHours(QuantityValue kilovoltamper /// If value is NaN or Infinity. public static ApparentEnergy FromMegavoltampereHours(QuantityValue megavoltamperehours) { - double value = (double) megavoltamperehours; + QuantityValue value = (QuantityValue) megavoltamperehours; return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); } @@ -253,7 +256,7 @@ public static ApparentEnergy FromMegavoltampereHours(QuantityValue megavoltamper /// If value is NaN or Infinity. public static ApparentEnergy FromVoltampereHours(QuantityValue voltamperehours) { - double value = (double) voltamperehours; + QuantityValue value = (QuantityValue) voltamperehours; return new ApparentEnergy(value, ApparentEnergyUnit.VoltampereHour); } @@ -265,7 +268,7 @@ public static ApparentEnergy FromVoltampereHours(QuantityValue voltamperehours) /// ApparentEnergy unit value. public static ApparentEnergy From(QuantityValue value, ApparentEnergyUnit fromUnit) { - return new ApparentEnergy((double)value, fromUnit); + return new ApparentEnergy((QuantityValue)value, fromUnit); } #endregion @@ -435,25 +438,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Appar } /// Get from multiplying value and . - public static ApparentEnergy operator *(double left, ApparentEnergy right) + public static ApparentEnergy operator *(QuantityValue left, ApparentEnergy right) { return new ApparentEnergy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ApparentEnergy operator *(ApparentEnergy left, double right) + public static ApparentEnergy operator *(ApparentEnergy left, QuantityValue right) { return new ApparentEnergy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ApparentEnergy operator /(ApparentEnergy left, double right) + public static ApparentEnergy operator /(ApparentEnergy left, QuantityValue right) { return new ApparentEnergy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ApparentEnergy left, ApparentEnergy right) + public static QuantityValue operator /(ApparentEnergy left, ApparentEnergy right) { return left.VoltampereHours / right.VoltampereHours; } @@ -486,6 +489,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Appar return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ApparentEnergy left, ApparentEnergy right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ApparentEnergy left, ApparentEnergy right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -498,7 +514,29 @@ public int CompareTo(object obj) /// public int CompareTo(ApparentEnergy other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ApparentEnergy objApparentEnergy)) + return false; + return Equals(objApparentEnergy); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ApparentEnergy other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -541,13 +579,13 @@ public int CompareTo(ApparentEnergy other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ApparentEnergy other, double tolerance, ComparisonType comparisonType) + public bool Equals(ApparentEnergy other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -558,7 +596,7 @@ public bool Equals(ApparentEnergy other, double tolerance, ComparisonType compar /// A hash code for the current ApparentEnergy. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -569,17 +607,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ApparentEnergyUnit unit) + public QuantityValue As(ApparentEnergyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -594,12 +631,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ApparentEnergyUnit unitAsApparentEnergyUnit)) + if (!(unit is ApparentEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentEnergyUnit)} is supported.", nameof(unit)); - return As(unitAsApparentEnergyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -631,7 +668,7 @@ public ApparentEnergy ToUnit(ApparentEnergyUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (ApparentEnergy)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ApparentEnergyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -639,17 +676,17 @@ public ApparentEnergy ToUnit(ApparentEnergyUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ApparentEnergyUnit unitAsApparentEnergyUnit)) + if (!(unit is ApparentEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentEnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsApparentEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -676,10 +713,10 @@ public ApparentEnergy ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ApparentEnergyUnit unit) + private QuantityValue GetValueAs(ApparentEnergyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs index 403251e02c..b39709e9b2 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current. /// [DataContract] - public partial struct ApparentPower : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ApparentPower : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static ApparentPower() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ApparentPower(double value, ApparentPowerUnit unit) + public ApparentPower(QuantityValue value, ApparentPowerUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public ApparentPower(double value, ApparentPowerUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ApparentPower(double value, UnitSystem unitSystem) + public ApparentPower(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public ApparentPower(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,24 +163,24 @@ public ApparentPower(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gigavoltamperes => As(ApparentPowerUnit.Gigavoltampere); + public QuantityValue Gigavoltamperes => As(ApparentPowerUnit.Gigavoltampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilovoltamperes => As(ApparentPowerUnit.Kilovoltampere); + public QuantityValue Kilovoltamperes => As(ApparentPowerUnit.Kilovoltampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megavoltamperes => As(ApparentPowerUnit.Megavoltampere); + public QuantityValue Megavoltamperes => As(ApparentPowerUnit.Megavoltampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Voltamperes => As(ApparentPowerUnit.Voltampere); + public QuantityValue Voltamperes => As(ApparentPowerUnit.Voltampere); #endregion @@ -242,7 +245,7 @@ public static string GetAbbreviation(ApparentPowerUnit unit, IFormatProvider? pr /// If value is NaN or Infinity. public static ApparentPower FromGigavoltamperes(QuantityValue gigavoltamperes) { - double value = (double) gigavoltamperes; + QuantityValue value = (QuantityValue) gigavoltamperes; return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); } @@ -252,7 +255,7 @@ public static ApparentPower FromGigavoltamperes(QuantityValue gigavoltamperes) /// If value is NaN or Infinity. public static ApparentPower FromKilovoltamperes(QuantityValue kilovoltamperes) { - double value = (double) kilovoltamperes; + QuantityValue value = (QuantityValue) kilovoltamperes; return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); } @@ -262,7 +265,7 @@ public static ApparentPower FromKilovoltamperes(QuantityValue kilovoltamperes) /// If value is NaN or Infinity. public static ApparentPower FromMegavoltamperes(QuantityValue megavoltamperes) { - double value = (double) megavoltamperes; + QuantityValue value = (QuantityValue) megavoltamperes; return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); } @@ -272,7 +275,7 @@ public static ApparentPower FromMegavoltamperes(QuantityValue megavoltamperes) /// If value is NaN or Infinity. public static ApparentPower FromVoltamperes(QuantityValue voltamperes) { - double value = (double) voltamperes; + QuantityValue value = (QuantityValue) voltamperes; return new ApparentPower(value, ApparentPowerUnit.Voltampere); } @@ -284,7 +287,7 @@ public static ApparentPower FromVoltamperes(QuantityValue voltamperes) /// ApparentPower unit value. public static ApparentPower From(QuantityValue value, ApparentPowerUnit fromUnit) { - return new ApparentPower((double)value, fromUnit); + return new ApparentPower((QuantityValue)value, fromUnit); } #endregion @@ -454,25 +457,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Appar } /// Get from multiplying value and . - public static ApparentPower operator *(double left, ApparentPower right) + public static ApparentPower operator *(QuantityValue left, ApparentPower right) { return new ApparentPower(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ApparentPower operator *(ApparentPower left, double right) + public static ApparentPower operator *(ApparentPower left, QuantityValue right) { return new ApparentPower(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ApparentPower operator /(ApparentPower left, double right) + public static ApparentPower operator /(ApparentPower left, QuantityValue right) { return new ApparentPower(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ApparentPower left, ApparentPower right) + public static QuantityValue operator /(ApparentPower left, ApparentPower right) { return left.Voltamperes / right.Voltamperes; } @@ -505,6 +508,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Appar return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ApparentPower left, ApparentPower right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ApparentPower left, ApparentPower right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -517,7 +533,29 @@ public int CompareTo(object obj) /// public int CompareTo(ApparentPower other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ApparentPower objApparentPower)) + return false; + return Equals(objApparentPower); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ApparentPower other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -560,13 +598,13 @@ public int CompareTo(ApparentPower other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ApparentPower other, double tolerance, ComparisonType comparisonType) + public bool Equals(ApparentPower other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -577,7 +615,7 @@ public bool Equals(ApparentPower other, double tolerance, ComparisonType compari /// A hash code for the current ApparentPower. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -588,17 +626,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ApparentPowerUnit unit) + public QuantityValue As(ApparentPowerUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -613,12 +650,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ApparentPowerUnit unitAsApparentPowerUnit)) + if (!(unit is ApparentPowerUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentPowerUnit)} is supported.", nameof(unit)); - return As(unitAsApparentPowerUnit); + return (QuantityValue)As(typedUnit); } /// @@ -650,7 +687,7 @@ public ApparentPower ToUnit(ApparentPowerUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (ApparentPower)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ApparentPowerUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -658,17 +695,17 @@ public ApparentPower ToUnit(ApparentPowerUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ApparentPowerUnit unitAsApparentPowerUnit)) + if (!(unit is ApparentPowerUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentPowerUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsApparentPowerUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -695,10 +732,10 @@ public ApparentPower ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ApparentPowerUnit unit) + private QuantityValue GetValueAs(ApparentPowerUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Area.g.cs b/UnitsNet/GeneratedCode/Quantities/Area.g.cs index e7b786a82d..b09d112214 100644 --- a/UnitsNet/GeneratedCode/Quantities/Area.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Area.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept). /// [DataContract] - public partial struct Area : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Area : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -85,9 +85,9 @@ static Area() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Area(double value, AreaUnit unit) + public Area(QuantityValue value, AreaUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -99,14 +99,14 @@ public Area(double value, AreaUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Area(double value, UnitSystem unitSystem) + public Area(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -147,7 +147,10 @@ public Area(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -170,74 +173,74 @@ public Area(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Acres => As(AreaUnit.Acre); + public QuantityValue Acres => As(AreaUnit.Acre); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Hectares => As(AreaUnit.Hectare); + public QuantityValue Hectares => As(AreaUnit.Hectare); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareCentimeters => As(AreaUnit.SquareCentimeter); + public QuantityValue SquareCentimeters => As(AreaUnit.SquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareDecimeters => As(AreaUnit.SquareDecimeter); + public QuantityValue SquareDecimeters => As(AreaUnit.SquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareFeet => As(AreaUnit.SquareFoot); + public QuantityValue SquareFeet => As(AreaUnit.SquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareInches => As(AreaUnit.SquareInch); + public QuantityValue SquareInches => As(AreaUnit.SquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareKilometers => As(AreaUnit.SquareKilometer); + public QuantityValue SquareKilometers => As(AreaUnit.SquareKilometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareMeters => As(AreaUnit.SquareMeter); + public QuantityValue SquareMeters => As(AreaUnit.SquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareMicrometers => As(AreaUnit.SquareMicrometer); + public QuantityValue SquareMicrometers => As(AreaUnit.SquareMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareMiles => As(AreaUnit.SquareMile); + public QuantityValue SquareMiles => As(AreaUnit.SquareMile); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareMillimeters => As(AreaUnit.SquareMillimeter); + public QuantityValue SquareMillimeters => As(AreaUnit.SquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareNauticalMiles => As(AreaUnit.SquareNauticalMile); + public QuantityValue SquareNauticalMiles => As(AreaUnit.SquareNauticalMile); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareYards => As(AreaUnit.SquareYard); + public QuantityValue SquareYards => As(AreaUnit.SquareYard); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); + public QuantityValue UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); #endregion @@ -359,7 +362,7 @@ public static string GetAbbreviation(AreaUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Area FromAcres(QuantityValue acres) { - double value = (double) acres; + QuantityValue value = (QuantityValue) acres; return new Area(value, AreaUnit.Acre); } @@ -369,7 +372,7 @@ public static Area FromAcres(QuantityValue acres) /// If value is NaN or Infinity. public static Area FromHectares(QuantityValue hectares) { - double value = (double) hectares; + QuantityValue value = (QuantityValue) hectares; return new Area(value, AreaUnit.Hectare); } @@ -379,7 +382,7 @@ public static Area FromHectares(QuantityValue hectares) /// If value is NaN or Infinity. public static Area FromSquareCentimeters(QuantityValue squarecentimeters) { - double value = (double) squarecentimeters; + QuantityValue value = (QuantityValue) squarecentimeters; return new Area(value, AreaUnit.SquareCentimeter); } @@ -389,7 +392,7 @@ public static Area FromSquareCentimeters(QuantityValue squarecentimeters) /// If value is NaN or Infinity. public static Area FromSquareDecimeters(QuantityValue squaredecimeters) { - double value = (double) squaredecimeters; + QuantityValue value = (QuantityValue) squaredecimeters; return new Area(value, AreaUnit.SquareDecimeter); } @@ -399,7 +402,7 @@ public static Area FromSquareDecimeters(QuantityValue squaredecimeters) /// If value is NaN or Infinity. public static Area FromSquareFeet(QuantityValue squarefeet) { - double value = (double) squarefeet; + QuantityValue value = (QuantityValue) squarefeet; return new Area(value, AreaUnit.SquareFoot); } @@ -409,7 +412,7 @@ public static Area FromSquareFeet(QuantityValue squarefeet) /// If value is NaN or Infinity. public static Area FromSquareInches(QuantityValue squareinches) { - double value = (double) squareinches; + QuantityValue value = (QuantityValue) squareinches; return new Area(value, AreaUnit.SquareInch); } @@ -419,7 +422,7 @@ public static Area FromSquareInches(QuantityValue squareinches) /// If value is NaN or Infinity. public static Area FromSquareKilometers(QuantityValue squarekilometers) { - double value = (double) squarekilometers; + QuantityValue value = (QuantityValue) squarekilometers; return new Area(value, AreaUnit.SquareKilometer); } @@ -429,7 +432,7 @@ public static Area FromSquareKilometers(QuantityValue squarekilometers) /// If value is NaN or Infinity. public static Area FromSquareMeters(QuantityValue squaremeters) { - double value = (double) squaremeters; + QuantityValue value = (QuantityValue) squaremeters; return new Area(value, AreaUnit.SquareMeter); } @@ -439,7 +442,7 @@ public static Area FromSquareMeters(QuantityValue squaremeters) /// If value is NaN or Infinity. public static Area FromSquareMicrometers(QuantityValue squaremicrometers) { - double value = (double) squaremicrometers; + QuantityValue value = (QuantityValue) squaremicrometers; return new Area(value, AreaUnit.SquareMicrometer); } @@ -449,7 +452,7 @@ public static Area FromSquareMicrometers(QuantityValue squaremicrometers) /// If value is NaN or Infinity. public static Area FromSquareMiles(QuantityValue squaremiles) { - double value = (double) squaremiles; + QuantityValue value = (QuantityValue) squaremiles; return new Area(value, AreaUnit.SquareMile); } @@ -459,7 +462,7 @@ public static Area FromSquareMiles(QuantityValue squaremiles) /// If value is NaN or Infinity. public static Area FromSquareMillimeters(QuantityValue squaremillimeters) { - double value = (double) squaremillimeters; + QuantityValue value = (QuantityValue) squaremillimeters; return new Area(value, AreaUnit.SquareMillimeter); } @@ -469,7 +472,7 @@ public static Area FromSquareMillimeters(QuantityValue squaremillimeters) /// If value is NaN or Infinity. public static Area FromSquareNauticalMiles(QuantityValue squarenauticalmiles) { - double value = (double) squarenauticalmiles; + QuantityValue value = (QuantityValue) squarenauticalmiles; return new Area(value, AreaUnit.SquareNauticalMile); } @@ -479,7 +482,7 @@ public static Area FromSquareNauticalMiles(QuantityValue squarenauticalmiles) /// If value is NaN or Infinity. public static Area FromSquareYards(QuantityValue squareyards) { - double value = (double) squareyards; + QuantityValue value = (QuantityValue) squareyards; return new Area(value, AreaUnit.SquareYard); } @@ -489,7 +492,7 @@ public static Area FromSquareYards(QuantityValue squareyards) /// If value is NaN or Infinity. public static Area FromUsSurveySquareFeet(QuantityValue ussurveysquarefeet) { - double value = (double) ussurveysquarefeet; + QuantityValue value = (QuantityValue) ussurveysquarefeet; return new Area(value, AreaUnit.UsSurveySquareFoot); } @@ -501,7 +504,7 @@ public static Area FromUsSurveySquareFeet(QuantityValue ussurveysquarefeet) /// Area unit value. public static Area From(QuantityValue value, AreaUnit fromUnit) { - return new Area((double)value, fromUnit); + return new Area((QuantityValue)value, fromUnit); } #endregion @@ -671,25 +674,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaU } /// Get from multiplying value and . - public static Area operator *(double left, Area right) + public static Area operator *(QuantityValue left, Area right) { return new Area(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Area operator *(Area left, double right) + public static Area operator *(Area left, QuantityValue right) { return new Area(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Area operator /(Area left, double right) + public static Area operator /(Area left, QuantityValue right) { return new Area(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Area left, Area right) + public static QuantityValue operator /(Area left, Area right) { return left.SquareMeters / right.SquareMeters; } @@ -722,6 +725,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaU return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Area left, Area right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Area left, Area right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -734,7 +750,29 @@ public int CompareTo(object obj) /// public int CompareTo(Area other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Area objArea)) + return false; + return Equals(objArea); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Area other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -777,13 +815,13 @@ public int CompareTo(Area other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Area other, double tolerance, ComparisonType comparisonType) + public bool Equals(Area other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -794,7 +832,7 @@ public bool Equals(Area other, double tolerance, ComparisonType comparisonType) /// A hash code for the current Area. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -805,17 +843,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(AreaUnit unit) + public QuantityValue As(AreaUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -830,12 +867,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is AreaUnit unitAsAreaUnit)) + if (!(unit is AreaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaUnit)} is supported.", nameof(unit)); - return As(unitAsAreaUnit); + return (QuantityValue)As(typedUnit); } /// @@ -867,7 +904,7 @@ public Area ToUnit(AreaUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Area)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(AreaUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -875,17 +912,17 @@ public Area ToUnit(AreaUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AreaUnit unitAsAreaUnit)) + if (!(unit is AreaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAreaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -912,10 +949,10 @@ public Area ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(AreaUnit unit) + private QuantityValue GetValueAs(AreaUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs index 76e73b46b3..9258a2c16d 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The area density of a two-dimensional object is calculated as the mass per unit area. /// [DataContract] - public partial struct AreaDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct AreaDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -72,9 +72,9 @@ static AreaDensity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public AreaDensity(double value, AreaDensityUnit unit) + public AreaDensity(QuantityValue value, AreaDensityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -86,14 +86,14 @@ public AreaDensity(double value, AreaDensityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public AreaDensity(double value, UnitSystem unitSystem) + public AreaDensity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -134,7 +134,10 @@ public AreaDensity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -157,9 +160,9 @@ public AreaDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); + public QuantityValue KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); #endregion @@ -215,7 +218,7 @@ public static string GetAbbreviation(AreaDensityUnit unit, IFormatProvider? prov /// If value is NaN or Infinity. public static AreaDensity FromKilogramsPerSquareMeter(QuantityValue kilogramspersquaremeter) { - double value = (double) kilogramspersquaremeter; + QuantityValue value = (QuantityValue) kilogramspersquaremeter; return new AreaDensity(value, AreaDensityUnit.KilogramPerSquareMeter); } @@ -227,7 +230,7 @@ public static AreaDensity FromKilogramsPerSquareMeter(QuantityValue kilogramsper /// AreaDensity unit value. public static AreaDensity From(QuantityValue value, AreaDensityUnit fromUnit) { - return new AreaDensity((double)value, fromUnit); + return new AreaDensity((QuantityValue)value, fromUnit); } #endregion @@ -397,25 +400,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaD } /// Get from multiplying value and . - public static AreaDensity operator *(double left, AreaDensity right) + public static AreaDensity operator *(QuantityValue left, AreaDensity right) { return new AreaDensity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static AreaDensity operator *(AreaDensity left, double right) + public static AreaDensity operator *(AreaDensity left, QuantityValue right) { return new AreaDensity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static AreaDensity operator /(AreaDensity left, double right) + public static AreaDensity operator /(AreaDensity left, QuantityValue right) { return new AreaDensity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(AreaDensity left, AreaDensity right) + public static QuantityValue operator /(AreaDensity left, AreaDensity right) { return left.KilogramsPerSquareMeter / right.KilogramsPerSquareMeter; } @@ -448,6 +451,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaD return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(AreaDensity left, AreaDensity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(AreaDensity left, AreaDensity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -460,7 +476,29 @@ public int CompareTo(object obj) /// public int CompareTo(AreaDensity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is AreaDensity objAreaDensity)) + return false; + return Equals(objAreaDensity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(AreaDensity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -503,13 +541,13 @@ public int CompareTo(AreaDensity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AreaDensity other, double tolerance, ComparisonType comparisonType) + public bool Equals(AreaDensity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -520,7 +558,7 @@ public bool Equals(AreaDensity other, double tolerance, ComparisonType compariso /// A hash code for the current AreaDensity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -531,17 +569,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(AreaDensityUnit unit) + public QuantityValue As(AreaDensityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -556,12 +593,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is AreaDensityUnit unitAsAreaDensityUnit)) + if (!(unit is AreaDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaDensityUnit)} is supported.", nameof(unit)); - return As(unitAsAreaDensityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -593,7 +630,7 @@ public AreaDensity ToUnit(AreaDensityUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (AreaDensity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(AreaDensityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -601,17 +638,17 @@ public AreaDensity ToUnit(AreaDensityUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AreaDensityUnit unitAsAreaDensityUnit)) + if (!(unit is AreaDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAreaDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -638,10 +675,10 @@ public AreaDensity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(AreaDensityUnit unit) + private QuantityValue GetValueAs(AreaDensityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs index 26632ad748..80dedcc912 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// A geometric property of an area that reflects how its points are distributed with regard to an axis. /// [DataContract] - public partial struct AreaMomentOfInertia : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct AreaMomentOfInertia : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -77,9 +77,9 @@ static AreaMomentOfInertia() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public AreaMomentOfInertia(double value, AreaMomentOfInertiaUnit unit) + public AreaMomentOfInertia(QuantityValue value, AreaMomentOfInertiaUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -91,14 +91,14 @@ public AreaMomentOfInertia(double value, AreaMomentOfInertiaUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public AreaMomentOfInertia(double value, UnitSystem unitSystem) + public AreaMomentOfInertia(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -139,7 +139,10 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -162,34 +165,34 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); + public QuantityValue CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); + public QuantityValue DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); + public QuantityValue FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); + public QuantityValue InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); + public QuantityValue MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); + public QuantityValue MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); #endregion @@ -260,7 +263,7 @@ public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, IFormatProvid /// If value is NaN or Infinity. public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue centimeterstothefourth) { - double value = (double) centimeterstothefourth; + QuantityValue value = (QuantityValue) centimeterstothefourth; return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); } @@ -270,7 +273,7 @@ public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue centi /// If value is NaN or Infinity. public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue decimeterstothefourth) { - double value = (double) decimeterstothefourth; + QuantityValue value = (QuantityValue) decimeterstothefourth; return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); } @@ -280,7 +283,7 @@ public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue decime /// If value is NaN or Infinity. public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue feettothefourth) { - double value = (double) feettothefourth; + QuantityValue value = (QuantityValue) feettothefourth; return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); } @@ -290,7 +293,7 @@ public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue feettothefou /// If value is NaN or Infinity. public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue inchestothefourth) { - double value = (double) inchestothefourth; + QuantityValue value = (QuantityValue) inchestothefourth; return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); } @@ -300,7 +303,7 @@ public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue inchestoth /// If value is NaN or Infinity. public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue meterstothefourth) { - double value = (double) meterstothefourth; + QuantityValue value = (QuantityValue) meterstothefourth; return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); } @@ -310,7 +313,7 @@ public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue meterstoth /// If value is NaN or Infinity. public static AreaMomentOfInertia FromMillimetersToTheFourth(QuantityValue millimeterstothefourth) { - double value = (double) millimeterstothefourth; + QuantityValue value = (QuantityValue) millimeterstothefourth; return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MillimeterToTheFourth); } @@ -322,7 +325,7 @@ public static AreaMomentOfInertia FromMillimetersToTheFourth(QuantityValue milli /// AreaMomentOfInertia unit value. public static AreaMomentOfInertia From(QuantityValue value, AreaMomentOfInertiaUnit fromUnit) { - return new AreaMomentOfInertia((double)value, fromUnit); + return new AreaMomentOfInertia((QuantityValue)value, fromUnit); } #endregion @@ -492,25 +495,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaM } /// Get from multiplying value and . - public static AreaMomentOfInertia operator *(double left, AreaMomentOfInertia right) + public static AreaMomentOfInertia operator *(QuantityValue left, AreaMomentOfInertia right) { return new AreaMomentOfInertia(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static AreaMomentOfInertia operator *(AreaMomentOfInertia left, double right) + public static AreaMomentOfInertia operator *(AreaMomentOfInertia left, QuantityValue right) { return new AreaMomentOfInertia(left.Value * right, left.Unit); } /// Get from dividing by value. - public static AreaMomentOfInertia operator /(AreaMomentOfInertia left, double right) + public static AreaMomentOfInertia operator /(AreaMomentOfInertia left, QuantityValue right) { return new AreaMomentOfInertia(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(AreaMomentOfInertia left, AreaMomentOfInertia right) + public static QuantityValue operator /(AreaMomentOfInertia left, AreaMomentOfInertia right) { return left.MetersToTheFourth / right.MetersToTheFourth; } @@ -543,6 +546,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaM return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -555,7 +571,29 @@ public int CompareTo(object obj) /// public int CompareTo(AreaMomentOfInertia other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is AreaMomentOfInertia objAreaMomentOfInertia)) + return false; + return Equals(objAreaMomentOfInertia); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(AreaMomentOfInertia other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -598,13 +636,13 @@ public int CompareTo(AreaMomentOfInertia other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AreaMomentOfInertia other, double tolerance, ComparisonType comparisonType) + public bool Equals(AreaMomentOfInertia other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -615,7 +653,7 @@ public bool Equals(AreaMomentOfInertia other, double tolerance, ComparisonType c /// A hash code for the current AreaMomentOfInertia. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -626,17 +664,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(AreaMomentOfInertiaUnit unit) + public QuantityValue As(AreaMomentOfInertiaUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -651,12 +688,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is AreaMomentOfInertiaUnit unitAsAreaMomentOfInertiaUnit)) + if (!(unit is AreaMomentOfInertiaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaMomentOfInertiaUnit)} is supported.", nameof(unit)); - return As(unitAsAreaMomentOfInertiaUnit); + return (QuantityValue)As(typedUnit); } /// @@ -688,7 +725,7 @@ public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit, UnitConverter un var converted = conversionFunction(this); return (AreaMomentOfInertia)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(AreaMomentOfInertiaUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -696,17 +733,17 @@ public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AreaMomentOfInertiaUnit unitAsAreaMomentOfInertiaUnit)) + if (!(unit is AreaMomentOfInertiaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaMomentOfInertiaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsAreaMomentOfInertiaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -733,10 +770,10 @@ public AreaMomentOfInertia ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(AreaMomentOfInertiaUnit unit) + private QuantityValue GetValueAs(AreaMomentOfInertiaUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs index 1ce28dd1dd..cbb22d9243 100644 --- a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Bit_rate /// [DataContract] - public partial struct BitRate : IQuantity, IDecimalQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct BitRate : IQuantity, IDecimalQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly decimal _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -100,7 +100,7 @@ static BitRate() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public BitRate(decimal value, BitRateUnit unit) + public BitRate(QuantityValue value, BitRateUnit unit) { _value = value; _unit = unit; @@ -114,7 +114,7 @@ public BitRate(decimal value, BitRateUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public BitRate(decimal value, UnitSystem unitSystem) + public BitRate(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -162,12 +162,13 @@ public BitRate(decimal value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public decimal Value => _value; + public QuantityValue Value => _value; - double IQuantity.Value => (double) _value; + /// + QuantityValue IQuantity.Value => _value; /// - decimal IDecimalQuantity.Value => _value; + decimal IDecimalQuantity.Value => (decimal)_value; Enum IQuantity.Unit => Unit; @@ -190,134 +191,134 @@ public BitRate(decimal value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BitsPerSecond => As(BitRateUnit.BitPerSecond); + public QuantityValue BitsPerSecond => As(BitRateUnit.BitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BytesPerSecond => As(BitRateUnit.BytePerSecond); + public QuantityValue BytesPerSecond => As(BitRateUnit.BytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); + public QuantityValue ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); + public QuantityValue ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); + public QuantityValue ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); + public QuantityValue ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); + public QuantityValue GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); + public QuantityValue GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); + public QuantityValue GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); + public QuantityValue GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); + public QuantityValue KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); + public QuantityValue KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); + public QuantityValue KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); + public QuantityValue KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); + public QuantityValue MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); + public QuantityValue MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); + public QuantityValue MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); + public QuantityValue MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); + public QuantityValue PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); + public QuantityValue PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); + public QuantityValue PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); + public QuantityValue PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); + public QuantityValue TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); + public QuantityValue TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); + public QuantityValue TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); + public QuantityValue TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); #endregion @@ -448,7 +449,7 @@ public static string GetAbbreviation(BitRateUnit unit, IFormatProvider? provider /// If value is NaN or Infinity. public static BitRate FromBitsPerSecond(QuantityValue bitspersecond) { - decimal value = (decimal) bitspersecond; + QuantityValue value = (QuantityValue) bitspersecond; return new BitRate(value, BitRateUnit.BitPerSecond); } @@ -458,7 +459,7 @@ public static BitRate FromBitsPerSecond(QuantityValue bitspersecond) /// If value is NaN or Infinity. public static BitRate FromBytesPerSecond(QuantityValue bytespersecond) { - decimal value = (decimal) bytespersecond; + QuantityValue value = (QuantityValue) bytespersecond; return new BitRate(value, BitRateUnit.BytePerSecond); } @@ -468,7 +469,7 @@ public static BitRate FromBytesPerSecond(QuantityValue bytespersecond) /// If value is NaN or Infinity. public static BitRate FromExabitsPerSecond(QuantityValue exabitspersecond) { - decimal value = (decimal) exabitspersecond; + QuantityValue value = (QuantityValue) exabitspersecond; return new BitRate(value, BitRateUnit.ExabitPerSecond); } @@ -478,7 +479,7 @@ public static BitRate FromExabitsPerSecond(QuantityValue exabitspersecond) /// If value is NaN or Infinity. public static BitRate FromExabytesPerSecond(QuantityValue exabytespersecond) { - decimal value = (decimal) exabytespersecond; + QuantityValue value = (QuantityValue) exabytespersecond; return new BitRate(value, BitRateUnit.ExabytePerSecond); } @@ -488,7 +489,7 @@ public static BitRate FromExabytesPerSecond(QuantityValue exabytespersecond) /// If value is NaN or Infinity. public static BitRate FromExbibitsPerSecond(QuantityValue exbibitspersecond) { - decimal value = (decimal) exbibitspersecond; + QuantityValue value = (QuantityValue) exbibitspersecond; return new BitRate(value, BitRateUnit.ExbibitPerSecond); } @@ -498,7 +499,7 @@ public static BitRate FromExbibitsPerSecond(QuantityValue exbibitspersecond) /// If value is NaN or Infinity. public static BitRate FromExbibytesPerSecond(QuantityValue exbibytespersecond) { - decimal value = (decimal) exbibytespersecond; + QuantityValue value = (QuantityValue) exbibytespersecond; return new BitRate(value, BitRateUnit.ExbibytePerSecond); } @@ -508,7 +509,7 @@ public static BitRate FromExbibytesPerSecond(QuantityValue exbibytespersecond) /// If value is NaN or Infinity. public static BitRate FromGibibitsPerSecond(QuantityValue gibibitspersecond) { - decimal value = (decimal) gibibitspersecond; + QuantityValue value = (QuantityValue) gibibitspersecond; return new BitRate(value, BitRateUnit.GibibitPerSecond); } @@ -518,7 +519,7 @@ public static BitRate FromGibibitsPerSecond(QuantityValue gibibitspersecond) /// If value is NaN or Infinity. public static BitRate FromGibibytesPerSecond(QuantityValue gibibytespersecond) { - decimal value = (decimal) gibibytespersecond; + QuantityValue value = (QuantityValue) gibibytespersecond; return new BitRate(value, BitRateUnit.GibibytePerSecond); } @@ -528,7 +529,7 @@ public static BitRate FromGibibytesPerSecond(QuantityValue gibibytespersecond) /// If value is NaN or Infinity. public static BitRate FromGigabitsPerSecond(QuantityValue gigabitspersecond) { - decimal value = (decimal) gigabitspersecond; + QuantityValue value = (QuantityValue) gigabitspersecond; return new BitRate(value, BitRateUnit.GigabitPerSecond); } @@ -538,7 +539,7 @@ public static BitRate FromGigabitsPerSecond(QuantityValue gigabitspersecond) /// If value is NaN or Infinity. public static BitRate FromGigabytesPerSecond(QuantityValue gigabytespersecond) { - decimal value = (decimal) gigabytespersecond; + QuantityValue value = (QuantityValue) gigabytespersecond; return new BitRate(value, BitRateUnit.GigabytePerSecond); } @@ -548,7 +549,7 @@ public static BitRate FromGigabytesPerSecond(QuantityValue gigabytespersecond) /// If value is NaN or Infinity. public static BitRate FromKibibitsPerSecond(QuantityValue kibibitspersecond) { - decimal value = (decimal) kibibitspersecond; + QuantityValue value = (QuantityValue) kibibitspersecond; return new BitRate(value, BitRateUnit.KibibitPerSecond); } @@ -558,7 +559,7 @@ public static BitRate FromKibibitsPerSecond(QuantityValue kibibitspersecond) /// If value is NaN or Infinity. public static BitRate FromKibibytesPerSecond(QuantityValue kibibytespersecond) { - decimal value = (decimal) kibibytespersecond; + QuantityValue value = (QuantityValue) kibibytespersecond; return new BitRate(value, BitRateUnit.KibibytePerSecond); } @@ -568,7 +569,7 @@ public static BitRate FromKibibytesPerSecond(QuantityValue kibibytespersecond) /// If value is NaN or Infinity. public static BitRate FromKilobitsPerSecond(QuantityValue kilobitspersecond) { - decimal value = (decimal) kilobitspersecond; + QuantityValue value = (QuantityValue) kilobitspersecond; return new BitRate(value, BitRateUnit.KilobitPerSecond); } @@ -578,7 +579,7 @@ public static BitRate FromKilobitsPerSecond(QuantityValue kilobitspersecond) /// If value is NaN or Infinity. public static BitRate FromKilobytesPerSecond(QuantityValue kilobytespersecond) { - decimal value = (decimal) kilobytespersecond; + QuantityValue value = (QuantityValue) kilobytespersecond; return new BitRate(value, BitRateUnit.KilobytePerSecond); } @@ -588,7 +589,7 @@ public static BitRate FromKilobytesPerSecond(QuantityValue kilobytespersecond) /// If value is NaN or Infinity. public static BitRate FromMebibitsPerSecond(QuantityValue mebibitspersecond) { - decimal value = (decimal) mebibitspersecond; + QuantityValue value = (QuantityValue) mebibitspersecond; return new BitRate(value, BitRateUnit.MebibitPerSecond); } @@ -598,7 +599,7 @@ public static BitRate FromMebibitsPerSecond(QuantityValue mebibitspersecond) /// If value is NaN or Infinity. public static BitRate FromMebibytesPerSecond(QuantityValue mebibytespersecond) { - decimal value = (decimal) mebibytespersecond; + QuantityValue value = (QuantityValue) mebibytespersecond; return new BitRate(value, BitRateUnit.MebibytePerSecond); } @@ -608,7 +609,7 @@ public static BitRate FromMebibytesPerSecond(QuantityValue mebibytespersecond) /// If value is NaN or Infinity. public static BitRate FromMegabitsPerSecond(QuantityValue megabitspersecond) { - decimal value = (decimal) megabitspersecond; + QuantityValue value = (QuantityValue) megabitspersecond; return new BitRate(value, BitRateUnit.MegabitPerSecond); } @@ -618,7 +619,7 @@ public static BitRate FromMegabitsPerSecond(QuantityValue megabitspersecond) /// If value is NaN or Infinity. public static BitRate FromMegabytesPerSecond(QuantityValue megabytespersecond) { - decimal value = (decimal) megabytespersecond; + QuantityValue value = (QuantityValue) megabytespersecond; return new BitRate(value, BitRateUnit.MegabytePerSecond); } @@ -628,7 +629,7 @@ public static BitRate FromMegabytesPerSecond(QuantityValue megabytespersecond) /// If value is NaN or Infinity. public static BitRate FromPebibitsPerSecond(QuantityValue pebibitspersecond) { - decimal value = (decimal) pebibitspersecond; + QuantityValue value = (QuantityValue) pebibitspersecond; return new BitRate(value, BitRateUnit.PebibitPerSecond); } @@ -638,7 +639,7 @@ public static BitRate FromPebibitsPerSecond(QuantityValue pebibitspersecond) /// If value is NaN or Infinity. public static BitRate FromPebibytesPerSecond(QuantityValue pebibytespersecond) { - decimal value = (decimal) pebibytespersecond; + QuantityValue value = (QuantityValue) pebibytespersecond; return new BitRate(value, BitRateUnit.PebibytePerSecond); } @@ -648,7 +649,7 @@ public static BitRate FromPebibytesPerSecond(QuantityValue pebibytespersecond) /// If value is NaN or Infinity. public static BitRate FromPetabitsPerSecond(QuantityValue petabitspersecond) { - decimal value = (decimal) petabitspersecond; + QuantityValue value = (QuantityValue) petabitspersecond; return new BitRate(value, BitRateUnit.PetabitPerSecond); } @@ -658,7 +659,7 @@ public static BitRate FromPetabitsPerSecond(QuantityValue petabitspersecond) /// If value is NaN or Infinity. public static BitRate FromPetabytesPerSecond(QuantityValue petabytespersecond) { - decimal value = (decimal) petabytespersecond; + QuantityValue value = (QuantityValue) petabytespersecond; return new BitRate(value, BitRateUnit.PetabytePerSecond); } @@ -668,7 +669,7 @@ public static BitRate FromPetabytesPerSecond(QuantityValue petabytespersecond) /// If value is NaN or Infinity. public static BitRate FromTebibitsPerSecond(QuantityValue tebibitspersecond) { - decimal value = (decimal) tebibitspersecond; + QuantityValue value = (QuantityValue) tebibitspersecond; return new BitRate(value, BitRateUnit.TebibitPerSecond); } @@ -678,7 +679,7 @@ public static BitRate FromTebibitsPerSecond(QuantityValue tebibitspersecond) /// If value is NaN or Infinity. public static BitRate FromTebibytesPerSecond(QuantityValue tebibytespersecond) { - decimal value = (decimal) tebibytespersecond; + QuantityValue value = (QuantityValue) tebibytespersecond; return new BitRate(value, BitRateUnit.TebibytePerSecond); } @@ -688,7 +689,7 @@ public static BitRate FromTebibytesPerSecond(QuantityValue tebibytespersecond) /// If value is NaN or Infinity. public static BitRate FromTerabitsPerSecond(QuantityValue terabitspersecond) { - decimal value = (decimal) terabitspersecond; + QuantityValue value = (QuantityValue) terabitspersecond; return new BitRate(value, BitRateUnit.TerabitPerSecond); } @@ -698,7 +699,7 @@ public static BitRate FromTerabitsPerSecond(QuantityValue terabitspersecond) /// If value is NaN or Infinity. public static BitRate FromTerabytesPerSecond(QuantityValue terabytespersecond) { - decimal value = (decimal) terabytespersecond; + QuantityValue value = (QuantityValue) terabytespersecond; return new BitRate(value, BitRateUnit.TerabytePerSecond); } @@ -710,7 +711,7 @@ public static BitRate FromTerabytesPerSecond(QuantityValue terabytespersecond) /// BitRate unit value. public static BitRate From(QuantityValue value, BitRateUnit fromUnit) { - return new BitRate((decimal)value, fromUnit); + return new BitRate((QuantityValue)value, fromUnit); } #endregion @@ -880,25 +881,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out BitRa } /// Get from multiplying value and . - public static BitRate operator *(decimal left, BitRate right) + public static BitRate operator *(QuantityValue left, BitRate right) { return new BitRate(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static BitRate operator *(BitRate left, decimal right) + public static BitRate operator *(BitRate left, QuantityValue right) { return new BitRate(left.Value * right, left.Unit); } /// Get from dividing by value. - public static BitRate operator /(BitRate left, decimal right) + public static BitRate operator /(BitRate left, QuantityValue right) { return new BitRate(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(BitRate left, BitRate right) + public static QuantityValue operator /(BitRate left, BitRate right) { return left.BitsPerSecond / right.BitsPerSecond; } @@ -931,6 +932,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out BitRa return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(BitRate left, BitRate right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(BitRate left, BitRate right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -943,7 +957,29 @@ public int CompareTo(object obj) /// public int CompareTo(BitRate other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is BitRate objBitRate)) + return false; + return Equals(objBitRate); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(BitRate other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -986,13 +1022,13 @@ public int CompareTo(BitRate other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(BitRate other, double tolerance, ComparisonType comparisonType) + public bool Equals(BitRate other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1003,7 +1039,7 @@ public bool Equals(BitRate other, double tolerance, ComparisonType comparisonTyp /// A hash code for the current BitRate. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1014,17 +1050,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(BitRateUnit unit) + public QuantityValue As(BitRateUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1039,12 +1074,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is BitRateUnit unitAsBitRateUnit)) + if (!(unit is BitRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BitRateUnit)} is supported.", nameof(unit)); - return As(unitAsBitRateUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1076,7 +1111,7 @@ public BitRate ToUnit(BitRateUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (BitRate)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(BitRateUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1084,17 +1119,17 @@ public BitRate ToUnit(BitRateUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is BitRateUnit unitAsBitRateUnit)) + if (!(unit is BitRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BitRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsBitRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1121,10 +1156,10 @@ public BitRate ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private decimal GetValueAs(BitRateUnit unit) + private QuantityValue GetValueAs(BitRateUnit unit) { var converted = ToUnit(unit); - return (decimal)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs index 22e36e45c1..7c05af6842 100644 --- a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output. /// [DataContract] - public partial struct BrakeSpecificFuelConsumption : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct BrakeSpecificFuelConsumption : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -74,9 +74,9 @@ static BrakeSpecificFuelConsumption() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public BrakeSpecificFuelConsumption(double value, BrakeSpecificFuelConsumptionUnit unit) + public BrakeSpecificFuelConsumption(QuantityValue value, BrakeSpecificFuelConsumptionUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -88,14 +88,14 @@ public BrakeSpecificFuelConsumption(double value, BrakeSpecificFuelConsumptionUn /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) + public BrakeSpecificFuelConsumption(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -136,7 +136,10 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -159,19 +162,19 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + public QuantityValue GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + public QuantityValue KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); + public QuantityValue PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); #endregion @@ -233,7 +236,7 @@ public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, IFor /// If value is NaN or Infinity. public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValue gramsperkilowatthour) { - double value = (double) gramsperkilowatthour; + QuantityValue value = (QuantityValue) gramsperkilowatthour; return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); } @@ -243,7 +246,7 @@ public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValu /// If value is NaN or Infinity. public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue kilogramsperjoule) { - double value = (double) kilogramsperjoule; + QuantityValue value = (QuantityValue) kilogramsperjoule; return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); } @@ -253,7 +256,7 @@ public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue k /// If value is NaN or Infinity. public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(QuantityValue poundspermechanicalhorsepowerhour) { - double value = (double) poundspermechanicalhorsepowerhour; + QuantityValue value = (QuantityValue) poundspermechanicalhorsepowerhour; return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); } @@ -265,7 +268,7 @@ public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour /// BrakeSpecificFuelConsumption unit value. public static BrakeSpecificFuelConsumption From(QuantityValue value, BrakeSpecificFuelConsumptionUnit fromUnit) { - return new BrakeSpecificFuelConsumption((double)value, fromUnit); + return new BrakeSpecificFuelConsumption((QuantityValue)value, fromUnit); } #endregion @@ -435,25 +438,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Brake } /// Get from multiplying value and . - public static BrakeSpecificFuelConsumption operator *(double left, BrakeSpecificFuelConsumption right) + public static BrakeSpecificFuelConsumption operator *(QuantityValue left, BrakeSpecificFuelConsumption right) { return new BrakeSpecificFuelConsumption(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static BrakeSpecificFuelConsumption operator *(BrakeSpecificFuelConsumption left, double right) + public static BrakeSpecificFuelConsumption operator *(BrakeSpecificFuelConsumption left, QuantityValue right) { return new BrakeSpecificFuelConsumption(left.Value * right, left.Unit); } /// Get from dividing by value. - public static BrakeSpecificFuelConsumption operator /(BrakeSpecificFuelConsumption left, double right) + public static BrakeSpecificFuelConsumption operator /(BrakeSpecificFuelConsumption left, QuantityValue right) { return new BrakeSpecificFuelConsumption(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + public static QuantityValue operator /(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { return left.KilogramsPerJoule / right.KilogramsPerJoule; } @@ -486,6 +489,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Brake return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -498,7 +514,29 @@ public int CompareTo(object obj) /// public int CompareTo(BrakeSpecificFuelConsumption other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is BrakeSpecificFuelConsumption objBrakeSpecificFuelConsumption)) + return false; + return Equals(objBrakeSpecificFuelConsumption); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(BrakeSpecificFuelConsumption other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -541,13 +579,13 @@ public int CompareTo(BrakeSpecificFuelConsumption other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(BrakeSpecificFuelConsumption other, double tolerance, ComparisonType comparisonType) + public bool Equals(BrakeSpecificFuelConsumption other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -558,7 +596,7 @@ public bool Equals(BrakeSpecificFuelConsumption other, double tolerance, Compari /// A hash code for the current BrakeSpecificFuelConsumption. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -569,17 +607,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(BrakeSpecificFuelConsumptionUnit unit) + public QuantityValue As(BrakeSpecificFuelConsumptionUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -594,12 +631,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is BrakeSpecificFuelConsumptionUnit unitAsBrakeSpecificFuelConsumptionUnit)) + if (!(unit is BrakeSpecificFuelConsumptionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BrakeSpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - return As(unitAsBrakeSpecificFuelConsumptionUnit); + return (QuantityValue)As(typedUnit); } /// @@ -631,7 +668,7 @@ public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit var converted = conversionFunction(this); return (BrakeSpecificFuelConsumption)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(BrakeSpecificFuelConsumptionUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -639,17 +676,17 @@ public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is BrakeSpecificFuelConsumptionUnit unitAsBrakeSpecificFuelConsumptionUnit)) + if (!(unit is BrakeSpecificFuelConsumptionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BrakeSpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsBrakeSpecificFuelConsumptionUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -676,10 +713,10 @@ public BrakeSpecificFuelConsumption ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(BrakeSpecificFuelConsumptionUnit unit) + private QuantityValue GetValueAs(BrakeSpecificFuelConsumptionUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs index c049929b5a..5ed06c367e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Capacitance /// [DataContract] - public partial struct Capacitance : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Capacitance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -81,9 +81,9 @@ static Capacitance() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Capacitance(double value, CapacitanceUnit unit) + public Capacitance(QuantityValue value, CapacitanceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -95,14 +95,14 @@ public Capacitance(double value, CapacitanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Capacitance(double value, UnitSystem unitSystem) + public Capacitance(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -143,7 +143,10 @@ public Capacitance(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -166,39 +169,39 @@ public Capacitance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Farads => As(CapacitanceUnit.Farad); + public QuantityValue Farads => As(CapacitanceUnit.Farad); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilofarads => As(CapacitanceUnit.Kilofarad); + public QuantityValue Kilofarads => As(CapacitanceUnit.Kilofarad); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megafarads => As(CapacitanceUnit.Megafarad); + public QuantityValue Megafarads => As(CapacitanceUnit.Megafarad); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microfarads => As(CapacitanceUnit.Microfarad); + public QuantityValue Microfarads => As(CapacitanceUnit.Microfarad); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millifarads => As(CapacitanceUnit.Millifarad); + public QuantityValue Millifarads => As(CapacitanceUnit.Millifarad); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanofarads => As(CapacitanceUnit.Nanofarad); + public QuantityValue Nanofarads => As(CapacitanceUnit.Nanofarad); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Picofarads => As(CapacitanceUnit.Picofarad); + public QuantityValue Picofarads => As(CapacitanceUnit.Picofarad); #endregion @@ -272,7 +275,7 @@ public static string GetAbbreviation(CapacitanceUnit unit, IFormatProvider? prov /// If value is NaN or Infinity. public static Capacitance FromFarads(QuantityValue farads) { - double value = (double) farads; + QuantityValue value = (QuantityValue) farads; return new Capacitance(value, CapacitanceUnit.Farad); } @@ -282,7 +285,7 @@ public static Capacitance FromFarads(QuantityValue farads) /// If value is NaN or Infinity. public static Capacitance FromKilofarads(QuantityValue kilofarads) { - double value = (double) kilofarads; + QuantityValue value = (QuantityValue) kilofarads; return new Capacitance(value, CapacitanceUnit.Kilofarad); } @@ -292,7 +295,7 @@ public static Capacitance FromKilofarads(QuantityValue kilofarads) /// If value is NaN or Infinity. public static Capacitance FromMegafarads(QuantityValue megafarads) { - double value = (double) megafarads; + QuantityValue value = (QuantityValue) megafarads; return new Capacitance(value, CapacitanceUnit.Megafarad); } @@ -302,7 +305,7 @@ public static Capacitance FromMegafarads(QuantityValue megafarads) /// If value is NaN or Infinity. public static Capacitance FromMicrofarads(QuantityValue microfarads) { - double value = (double) microfarads; + QuantityValue value = (QuantityValue) microfarads; return new Capacitance(value, CapacitanceUnit.Microfarad); } @@ -312,7 +315,7 @@ public static Capacitance FromMicrofarads(QuantityValue microfarads) /// If value is NaN or Infinity. public static Capacitance FromMillifarads(QuantityValue millifarads) { - double value = (double) millifarads; + QuantityValue value = (QuantityValue) millifarads; return new Capacitance(value, CapacitanceUnit.Millifarad); } @@ -322,7 +325,7 @@ public static Capacitance FromMillifarads(QuantityValue millifarads) /// If value is NaN or Infinity. public static Capacitance FromNanofarads(QuantityValue nanofarads) { - double value = (double) nanofarads; + QuantityValue value = (QuantityValue) nanofarads; return new Capacitance(value, CapacitanceUnit.Nanofarad); } @@ -332,7 +335,7 @@ public static Capacitance FromNanofarads(QuantityValue nanofarads) /// If value is NaN or Infinity. public static Capacitance FromPicofarads(QuantityValue picofarads) { - double value = (double) picofarads; + QuantityValue value = (QuantityValue) picofarads; return new Capacitance(value, CapacitanceUnit.Picofarad); } @@ -344,7 +347,7 @@ public static Capacitance FromPicofarads(QuantityValue picofarads) /// Capacitance unit value. public static Capacitance From(QuantityValue value, CapacitanceUnit fromUnit) { - return new Capacitance((double)value, fromUnit); + return new Capacitance((QuantityValue)value, fromUnit); } #endregion @@ -514,25 +517,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Capac } /// Get from multiplying value and . - public static Capacitance operator *(double left, Capacitance right) + public static Capacitance operator *(QuantityValue left, Capacitance right) { return new Capacitance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Capacitance operator *(Capacitance left, double right) + public static Capacitance operator *(Capacitance left, QuantityValue right) { return new Capacitance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Capacitance operator /(Capacitance left, double right) + public static Capacitance operator /(Capacitance left, QuantityValue right) { return new Capacitance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Capacitance left, Capacitance right) + public static QuantityValue operator /(Capacitance left, Capacitance right) { return left.Farads / right.Farads; } @@ -565,6 +568,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Capac return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Capacitance left, Capacitance right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Capacitance left, Capacitance right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -577,7 +593,29 @@ public int CompareTo(object obj) /// public int CompareTo(Capacitance other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Capacitance objCapacitance)) + return false; + return Equals(objCapacitance); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Capacitance other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -620,13 +658,13 @@ public int CompareTo(Capacitance other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Capacitance other, double tolerance, ComparisonType comparisonType) + public bool Equals(Capacitance other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -637,7 +675,7 @@ public bool Equals(Capacitance other, double tolerance, ComparisonType compariso /// A hash code for the current Capacitance. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -648,17 +686,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(CapacitanceUnit unit) + public QuantityValue As(CapacitanceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -673,12 +710,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is CapacitanceUnit unitAsCapacitanceUnit)) + if (!(unit is CapacitanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CapacitanceUnit)} is supported.", nameof(unit)); - return As(unitAsCapacitanceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -710,7 +747,7 @@ public Capacitance ToUnit(CapacitanceUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Capacitance)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(CapacitanceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -718,17 +755,17 @@ public Capacitance ToUnit(CapacitanceUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is CapacitanceUnit unitAsCapacitanceUnit)) + if (!(unit is CapacitanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CapacitanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsCapacitanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -755,10 +792,10 @@ public Capacitance ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(CapacitanceUnit unit) + private QuantityValue GetValueAs(CapacitanceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs index 1c980e9a81..c00ec02eed 100644 --- a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// A unit that represents a fractional change in size in response to a change in temperature. /// [DataContract] - public partial struct CoefficientOfThermalExpansion : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct CoefficientOfThermalExpansion : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -74,9 +74,9 @@ static CoefficientOfThermalExpansion() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public CoefficientOfThermalExpansion(double value, CoefficientOfThermalExpansionUnit unit) + public CoefficientOfThermalExpansion(QuantityValue value, CoefficientOfThermalExpansionUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -88,14 +88,14 @@ public CoefficientOfThermalExpansion(double value, CoefficientOfThermalExpansion /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) + public CoefficientOfThermalExpansion(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -136,7 +136,10 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -159,19 +162,19 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + public QuantityValue InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + public QuantityValue InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin); + public QuantityValue InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin); #endregion @@ -233,7 +236,7 @@ public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, IFo /// If value is NaN or Infinity. public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(QuantityValue inversedegreecelsius) { - double value = (double) inversedegreecelsius; + QuantityValue value = (QuantityValue) inversedegreecelsius; return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); } @@ -243,7 +246,7 @@ public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(QuantityVal /// If value is NaN or Infinity. public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(QuantityValue inversedegreefahrenheit) { - double value = (double) inversedegreefahrenheit; + QuantityValue value = (QuantityValue) inversedegreefahrenheit; return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); } @@ -253,7 +256,7 @@ public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(Quantity /// If value is NaN or Infinity. public static CoefficientOfThermalExpansion FromInverseKelvin(QuantityValue inversekelvin) { - double value = (double) inversekelvin; + QuantityValue value = (QuantityValue) inversekelvin; return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseKelvin); } @@ -265,7 +268,7 @@ public static CoefficientOfThermalExpansion FromInverseKelvin(QuantityValue inve /// CoefficientOfThermalExpansion unit value. public static CoefficientOfThermalExpansion From(QuantityValue value, CoefficientOfThermalExpansionUnit fromUnit) { - return new CoefficientOfThermalExpansion((double)value, fromUnit); + return new CoefficientOfThermalExpansion((QuantityValue)value, fromUnit); } #endregion @@ -435,25 +438,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Coeff } /// Get from multiplying value and . - public static CoefficientOfThermalExpansion operator *(double left, CoefficientOfThermalExpansion right) + public static CoefficientOfThermalExpansion operator *(QuantityValue left, CoefficientOfThermalExpansion right) { return new CoefficientOfThermalExpansion(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static CoefficientOfThermalExpansion operator *(CoefficientOfThermalExpansion left, double right) + public static CoefficientOfThermalExpansion operator *(CoefficientOfThermalExpansion left, QuantityValue right) { return new CoefficientOfThermalExpansion(left.Value * right, left.Unit); } /// Get from dividing by value. - public static CoefficientOfThermalExpansion operator /(CoefficientOfThermalExpansion left, double right) + public static CoefficientOfThermalExpansion operator /(CoefficientOfThermalExpansion left, QuantityValue right) { return new CoefficientOfThermalExpansion(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + public static QuantityValue operator /(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { return left.InverseKelvin / right.InverseKelvin; } @@ -486,6 +489,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Coeff return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -498,7 +514,29 @@ public int CompareTo(object obj) /// public int CompareTo(CoefficientOfThermalExpansion other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is CoefficientOfThermalExpansion objCoefficientOfThermalExpansion)) + return false; + return Equals(objCoefficientOfThermalExpansion); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(CoefficientOfThermalExpansion other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -541,13 +579,13 @@ public int CompareTo(CoefficientOfThermalExpansion other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(CoefficientOfThermalExpansion other, double tolerance, ComparisonType comparisonType) + public bool Equals(CoefficientOfThermalExpansion other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -558,7 +596,7 @@ public bool Equals(CoefficientOfThermalExpansion other, double tolerance, Compar /// A hash code for the current CoefficientOfThermalExpansion. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -569,17 +607,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(CoefficientOfThermalExpansionUnit unit) + public QuantityValue As(CoefficientOfThermalExpansionUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -594,12 +631,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is CoefficientOfThermalExpansionUnit unitAsCoefficientOfThermalExpansionUnit)) + if (!(unit is CoefficientOfThermalExpansionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit)); - return As(unitAsCoefficientOfThermalExpansionUnit); + return (QuantityValue)As(typedUnit); } /// @@ -631,7 +668,7 @@ public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit un var converted = conversionFunction(this); return (CoefficientOfThermalExpansion)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(CoefficientOfThermalExpansionUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -639,17 +676,17 @@ public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is CoefficientOfThermalExpansionUnit unitAsCoefficientOfThermalExpansionUnit)) + if (!(unit is CoefficientOfThermalExpansionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsCoefficientOfThermalExpansionUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -676,10 +713,10 @@ public CoefficientOfThermalExpansion ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(CoefficientOfThermalExpansionUnit unit) + private QuantityValue GetValueAs(CoefficientOfThermalExpansionUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs index 24755cc1db..c62b2ea809 100644 --- a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// /// [DataContract] - public partial struct Compressibility : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Compressibility : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -78,9 +78,9 @@ static Compressibility() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Compressibility(double value, CompressibilityUnit unit) + public Compressibility(QuantityValue value, CompressibilityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -92,14 +92,14 @@ public Compressibility(double value, CompressibilityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Compressibility(double value, UnitSystem unitSystem) + public Compressibility(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -140,7 +140,10 @@ public Compressibility(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -163,39 +166,39 @@ public Compressibility(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseAtmospheres => As(CompressibilityUnit.InverseAtmosphere); + public QuantityValue InverseAtmospheres => As(CompressibilityUnit.InverseAtmosphere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseBars => As(CompressibilityUnit.InverseBar); + public QuantityValue InverseBars => As(CompressibilityUnit.InverseBar); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseKilopascals => As(CompressibilityUnit.InverseKilopascal); + public QuantityValue InverseKilopascals => As(CompressibilityUnit.InverseKilopascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseMegapascals => As(CompressibilityUnit.InverseMegapascal); + public QuantityValue InverseMegapascals => As(CompressibilityUnit.InverseMegapascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseMillibars => As(CompressibilityUnit.InverseMillibar); + public QuantityValue InverseMillibars => As(CompressibilityUnit.InverseMillibar); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InversePascals => As(CompressibilityUnit.InversePascal); + public QuantityValue InversePascals => As(CompressibilityUnit.InversePascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InversePoundsForcePerSquareInch => As(CompressibilityUnit.InversePoundForcePerSquareInch); + public QuantityValue InversePoundsForcePerSquareInch => As(CompressibilityUnit.InversePoundForcePerSquareInch); #endregion @@ -269,7 +272,7 @@ public static string GetAbbreviation(CompressibilityUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static Compressibility FromInverseAtmospheres(QuantityValue inverseatmospheres) { - double value = (double) inverseatmospheres; + QuantityValue value = (QuantityValue) inverseatmospheres; return new Compressibility(value, CompressibilityUnit.InverseAtmosphere); } @@ -279,7 +282,7 @@ public static Compressibility FromInverseAtmospheres(QuantityValue inverseatmosp /// If value is NaN or Infinity. public static Compressibility FromInverseBars(QuantityValue inversebars) { - double value = (double) inversebars; + QuantityValue value = (QuantityValue) inversebars; return new Compressibility(value, CompressibilityUnit.InverseBar); } @@ -289,7 +292,7 @@ public static Compressibility FromInverseBars(QuantityValue inversebars) /// If value is NaN or Infinity. public static Compressibility FromInverseKilopascals(QuantityValue inversekilopascals) { - double value = (double) inversekilopascals; + QuantityValue value = (QuantityValue) inversekilopascals; return new Compressibility(value, CompressibilityUnit.InverseKilopascal); } @@ -299,7 +302,7 @@ public static Compressibility FromInverseKilopascals(QuantityValue inversekilopa /// If value is NaN or Infinity. public static Compressibility FromInverseMegapascals(QuantityValue inversemegapascals) { - double value = (double) inversemegapascals; + QuantityValue value = (QuantityValue) inversemegapascals; return new Compressibility(value, CompressibilityUnit.InverseMegapascal); } @@ -309,7 +312,7 @@ public static Compressibility FromInverseMegapascals(QuantityValue inversemegapa /// If value is NaN or Infinity. public static Compressibility FromInverseMillibars(QuantityValue inversemillibars) { - double value = (double) inversemillibars; + QuantityValue value = (QuantityValue) inversemillibars; return new Compressibility(value, CompressibilityUnit.InverseMillibar); } @@ -319,7 +322,7 @@ public static Compressibility FromInverseMillibars(QuantityValue inversemillibar /// If value is NaN or Infinity. public static Compressibility FromInversePascals(QuantityValue inversepascals) { - double value = (double) inversepascals; + QuantityValue value = (QuantityValue) inversepascals; return new Compressibility(value, CompressibilityUnit.InversePascal); } @@ -329,7 +332,7 @@ public static Compressibility FromInversePascals(QuantityValue inversepascals) /// If value is NaN or Infinity. public static Compressibility FromInversePoundsForcePerSquareInch(QuantityValue inversepoundsforcepersquareinch) { - double value = (double) inversepoundsforcepersquareinch; + QuantityValue value = (QuantityValue) inversepoundsforcepersquareinch; return new Compressibility(value, CompressibilityUnit.InversePoundForcePerSquareInch); } @@ -341,7 +344,7 @@ public static Compressibility FromInversePoundsForcePerSquareInch(QuantityValue /// Compressibility unit value. public static Compressibility From(QuantityValue value, CompressibilityUnit fromUnit) { - return new Compressibility((double)value, fromUnit); + return new Compressibility((QuantityValue)value, fromUnit); } #endregion @@ -511,25 +514,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Compr } /// Get from multiplying value and . - public static Compressibility operator *(double left, Compressibility right) + public static Compressibility operator *(QuantityValue left, Compressibility right) { return new Compressibility(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Compressibility operator *(Compressibility left, double right) + public static Compressibility operator *(Compressibility left, QuantityValue right) { return new Compressibility(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Compressibility operator /(Compressibility left, double right) + public static Compressibility operator /(Compressibility left, QuantityValue right) { return new Compressibility(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Compressibility left, Compressibility right) + public static QuantityValue operator /(Compressibility left, Compressibility right) { return left.InversePascals / right.InversePascals; } @@ -562,6 +565,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Compr return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Compressibility left, Compressibility right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Compressibility left, Compressibility right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -574,7 +590,29 @@ public int CompareTo(object obj) /// public int CompareTo(Compressibility other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Compressibility objCompressibility)) + return false; + return Equals(objCompressibility); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Compressibility other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -617,13 +655,13 @@ public int CompareTo(Compressibility other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Compressibility other, double tolerance, ComparisonType comparisonType) + public bool Equals(Compressibility other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -634,7 +672,7 @@ public bool Equals(Compressibility other, double tolerance, ComparisonType compa /// A hash code for the current Compressibility. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -645,17 +683,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(CompressibilityUnit unit) + public QuantityValue As(CompressibilityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -670,12 +707,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is CompressibilityUnit unitAsCompressibilityUnit)) + if (!(unit is CompressibilityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CompressibilityUnit)} is supported.", nameof(unit)); - return As(unitAsCompressibilityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -707,7 +744,7 @@ public Compressibility ToUnit(CompressibilityUnit unit, UnitConverter unitConver var converted = conversionFunction(this); return (Compressibility)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(CompressibilityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -715,17 +752,17 @@ public Compressibility ToUnit(CompressibilityUnit unit, UnitConverter unitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is CompressibilityUnit unitAsCompressibilityUnit)) + if (!(unit is CompressibilityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CompressibilityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsCompressibilityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -752,10 +789,10 @@ public Compressibility ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(CompressibilityUnit unit) + private QuantityValue GetValueAs(CompressibilityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Density.g.cs b/UnitsNet/GeneratedCode/Quantities/Density.g.cs index 470717602d..f66631e323 100644 --- a/UnitsNet/GeneratedCode/Quantities/Density.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Density.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Density /// [DataContract] - public partial struct Density : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Density : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -125,9 +125,9 @@ static Density() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Density(double value, DensityUnit unit) + public Density(QuantityValue value, DensityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -139,14 +139,14 @@ public Density(double value, DensityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Density(double value, UnitSystem unitSystem) + public Density(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -187,7 +187,10 @@ public Density(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -210,259 +213,259 @@ public Density(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerDeciLiter => As(DensityUnit.CentigramPerDeciliter); + public QuantityValue CentigramsPerDeciLiter => As(DensityUnit.CentigramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); + public QuantityValue CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); + public QuantityValue CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerDeciLiter => As(DensityUnit.DecigramPerDeciliter); + public QuantityValue DecigramsPerDeciLiter => As(DensityUnit.DecigramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); + public QuantityValue DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); + public QuantityValue DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); + public QuantityValue GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerCubicFoot => As(DensityUnit.GramPerCubicFoot); + public QuantityValue GramsPerCubicFoot => As(DensityUnit.GramPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerCubicInch => As(DensityUnit.GramPerCubicInch); + public QuantityValue GramsPerCubicInch => As(DensityUnit.GramPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); + public QuantityValue GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); + public QuantityValue GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerDeciLiter => As(DensityUnit.GramPerDeciliter); + public QuantityValue GramsPerDeciLiter => As(DensityUnit.GramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerLiter => As(DensityUnit.GramPerLiter); + public QuantityValue GramsPerLiter => As(DensityUnit.GramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); + public QuantityValue GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); + public QuantityValue KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); + public QuantityValue KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); + public QuantityValue KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerLiter => As(DensityUnit.KilogramPerLiter); + public QuantityValue KilogramsPerLiter => As(DensityUnit.KilogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); + public QuantityValue KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); + public QuantityValue KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerCubicMeter => As(DensityUnit.MicrogramPerCubicMeter); + public QuantityValue MicrogramsPerCubicMeter => As(DensityUnit.MicrogramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerDeciLiter => As(DensityUnit.MicrogramPerDeciliter); + public QuantityValue MicrogramsPerDeciLiter => As(DensityUnit.MicrogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); + public QuantityValue MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); + public QuantityValue MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); + public QuantityValue MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerDeciLiter => As(DensityUnit.MilligramPerDeciliter); + public QuantityValue MilligramsPerDeciLiter => As(DensityUnit.MilligramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); + public QuantityValue MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); + public QuantityValue MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerDeciLiter => As(DensityUnit.NanogramPerDeciliter); + public QuantityValue NanogramsPerDeciLiter => As(DensityUnit.NanogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); + public QuantityValue NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); + public QuantityValue NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicogramsPerDeciLiter => As(DensityUnit.PicogramPerDeciliter); + public QuantityValue PicogramsPerDeciLiter => As(DensityUnit.PicogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); + public QuantityValue PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); + public QuantityValue PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerCubicCentimeter => As(DensityUnit.PoundPerCubicCentimeter); + public QuantityValue PoundsPerCubicCentimeter => As(DensityUnit.PoundPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); + public QuantityValue PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); + public QuantityValue PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerCubicMeter => As(DensityUnit.PoundPerCubicMeter); + public QuantityValue PoundsPerCubicMeter => As(DensityUnit.PoundPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerCubicMillimeter => As(DensityUnit.PoundPerCubicMillimeter); + public QuantityValue PoundsPerCubicMillimeter => As(DensityUnit.PoundPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); + public QuantityValue PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); + public QuantityValue PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SlugsPerCubicCentimeter => As(DensityUnit.SlugPerCubicCentimeter); + public QuantityValue SlugsPerCubicCentimeter => As(DensityUnit.SlugPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); + public QuantityValue SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SlugsPerCubicInch => As(DensityUnit.SlugPerCubicInch); + public QuantityValue SlugsPerCubicInch => As(DensityUnit.SlugPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SlugsPerCubicMeter => As(DensityUnit.SlugPerCubicMeter); + public QuantityValue SlugsPerCubicMeter => As(DensityUnit.SlugPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SlugsPerCubicMillimeter => As(DensityUnit.SlugPerCubicMillimeter); + public QuantityValue SlugsPerCubicMillimeter => As(DensityUnit.SlugPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); + public QuantityValue TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerCubicFoot => As(DensityUnit.TonnePerCubicFoot); + public QuantityValue TonnesPerCubicFoot => As(DensityUnit.TonnePerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerCubicInch => As(DensityUnit.TonnePerCubicInch); + public QuantityValue TonnesPerCubicInch => As(DensityUnit.TonnePerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); + public QuantityValue TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); + public QuantityValue TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); #endregion @@ -672,7 +675,7 @@ public static string GetAbbreviation(DensityUnit unit, IFormatProvider? provider /// If value is NaN or Infinity. public static Density FromCentigramsPerDeciLiter(QuantityValue centigramsperdeciliter) { - double value = (double) centigramsperdeciliter; + QuantityValue value = (QuantityValue) centigramsperdeciliter; return new Density(value, DensityUnit.CentigramPerDeciliter); } @@ -682,7 +685,7 @@ public static Density FromCentigramsPerDeciLiter(QuantityValue centigramsperdeci /// If value is NaN or Infinity. public static Density FromCentigramsPerLiter(QuantityValue centigramsperliter) { - double value = (double) centigramsperliter; + QuantityValue value = (QuantityValue) centigramsperliter; return new Density(value, DensityUnit.CentigramPerLiter); } @@ -692,7 +695,7 @@ public static Density FromCentigramsPerLiter(QuantityValue centigramsperliter) /// If value is NaN or Infinity. public static Density FromCentigramsPerMilliliter(QuantityValue centigramspermilliliter) { - double value = (double) centigramspermilliliter; + QuantityValue value = (QuantityValue) centigramspermilliliter; return new Density(value, DensityUnit.CentigramPerMilliliter); } @@ -702,7 +705,7 @@ public static Density FromCentigramsPerMilliliter(QuantityValue centigramspermil /// If value is NaN or Infinity. public static Density FromDecigramsPerDeciLiter(QuantityValue decigramsperdeciliter) { - double value = (double) decigramsperdeciliter; + QuantityValue value = (QuantityValue) decigramsperdeciliter; return new Density(value, DensityUnit.DecigramPerDeciliter); } @@ -712,7 +715,7 @@ public static Density FromDecigramsPerDeciLiter(QuantityValue decigramsperdecili /// If value is NaN or Infinity. public static Density FromDecigramsPerLiter(QuantityValue decigramsperliter) { - double value = (double) decigramsperliter; + QuantityValue value = (QuantityValue) decigramsperliter; return new Density(value, DensityUnit.DecigramPerLiter); } @@ -722,7 +725,7 @@ public static Density FromDecigramsPerLiter(QuantityValue decigramsperliter) /// If value is NaN or Infinity. public static Density FromDecigramsPerMilliliter(QuantityValue decigramspermilliliter) { - double value = (double) decigramspermilliliter; + QuantityValue value = (QuantityValue) decigramspermilliliter; return new Density(value, DensityUnit.DecigramPerMilliliter); } @@ -732,7 +735,7 @@ public static Density FromDecigramsPerMilliliter(QuantityValue decigramspermilli /// If value is NaN or Infinity. public static Density FromGramsPerCubicCentimeter(QuantityValue gramspercubiccentimeter) { - double value = (double) gramspercubiccentimeter; + QuantityValue value = (QuantityValue) gramspercubiccentimeter; return new Density(value, DensityUnit.GramPerCubicCentimeter); } @@ -742,7 +745,7 @@ public static Density FromGramsPerCubicCentimeter(QuantityValue gramspercubiccen /// If value is NaN or Infinity. public static Density FromGramsPerCubicFoot(QuantityValue gramspercubicfoot) { - double value = (double) gramspercubicfoot; + QuantityValue value = (QuantityValue) gramspercubicfoot; return new Density(value, DensityUnit.GramPerCubicFoot); } @@ -752,7 +755,7 @@ public static Density FromGramsPerCubicFoot(QuantityValue gramspercubicfoot) /// If value is NaN or Infinity. public static Density FromGramsPerCubicInch(QuantityValue gramspercubicinch) { - double value = (double) gramspercubicinch; + QuantityValue value = (QuantityValue) gramspercubicinch; return new Density(value, DensityUnit.GramPerCubicInch); } @@ -762,7 +765,7 @@ public static Density FromGramsPerCubicInch(QuantityValue gramspercubicinch) /// If value is NaN or Infinity. public static Density FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) { - double value = (double) gramspercubicmeter; + QuantityValue value = (QuantityValue) gramspercubicmeter; return new Density(value, DensityUnit.GramPerCubicMeter); } @@ -772,7 +775,7 @@ public static Density FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) /// If value is NaN or Infinity. public static Density FromGramsPerCubicMillimeter(QuantityValue gramspercubicmillimeter) { - double value = (double) gramspercubicmillimeter; + QuantityValue value = (QuantityValue) gramspercubicmillimeter; return new Density(value, DensityUnit.GramPerCubicMillimeter); } @@ -782,7 +785,7 @@ public static Density FromGramsPerCubicMillimeter(QuantityValue gramspercubicmil /// If value is NaN or Infinity. public static Density FromGramsPerDeciLiter(QuantityValue gramsperdeciliter) { - double value = (double) gramsperdeciliter; + QuantityValue value = (QuantityValue) gramsperdeciliter; return new Density(value, DensityUnit.GramPerDeciliter); } @@ -792,7 +795,7 @@ public static Density FromGramsPerDeciLiter(QuantityValue gramsperdeciliter) /// If value is NaN or Infinity. public static Density FromGramsPerLiter(QuantityValue gramsperliter) { - double value = (double) gramsperliter; + QuantityValue value = (QuantityValue) gramsperliter; return new Density(value, DensityUnit.GramPerLiter); } @@ -802,7 +805,7 @@ public static Density FromGramsPerLiter(QuantityValue gramsperliter) /// If value is NaN or Infinity. public static Density FromGramsPerMilliliter(QuantityValue gramspermilliliter) { - double value = (double) gramspermilliliter; + QuantityValue value = (QuantityValue) gramspermilliliter; return new Density(value, DensityUnit.GramPerMilliliter); } @@ -812,7 +815,7 @@ public static Density FromGramsPerMilliliter(QuantityValue gramspermilliliter) /// If value is NaN or Infinity. public static Density FromKilogramsPerCubicCentimeter(QuantityValue kilogramspercubiccentimeter) { - double value = (double) kilogramspercubiccentimeter; + QuantityValue value = (QuantityValue) kilogramspercubiccentimeter; return new Density(value, DensityUnit.KilogramPerCubicCentimeter); } @@ -822,7 +825,7 @@ public static Density FromKilogramsPerCubicCentimeter(QuantityValue kilogramsper /// If value is NaN or Infinity. public static Density FromKilogramsPerCubicMeter(QuantityValue kilogramspercubicmeter) { - double value = (double) kilogramspercubicmeter; + QuantityValue value = (QuantityValue) kilogramspercubicmeter; return new Density(value, DensityUnit.KilogramPerCubicMeter); } @@ -832,7 +835,7 @@ public static Density FromKilogramsPerCubicMeter(QuantityValue kilogramspercubic /// If value is NaN or Infinity. public static Density FromKilogramsPerCubicMillimeter(QuantityValue kilogramspercubicmillimeter) { - double value = (double) kilogramspercubicmillimeter; + QuantityValue value = (QuantityValue) kilogramspercubicmillimeter; return new Density(value, DensityUnit.KilogramPerCubicMillimeter); } @@ -842,7 +845,7 @@ public static Density FromKilogramsPerCubicMillimeter(QuantityValue kilogramsper /// If value is NaN or Infinity. public static Density FromKilogramsPerLiter(QuantityValue kilogramsperliter) { - double value = (double) kilogramsperliter; + QuantityValue value = (QuantityValue) kilogramsperliter; return new Density(value, DensityUnit.KilogramPerLiter); } @@ -852,7 +855,7 @@ public static Density FromKilogramsPerLiter(QuantityValue kilogramsperliter) /// If value is NaN or Infinity. public static Density FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubicfoot) { - double value = (double) kilopoundspercubicfoot; + QuantityValue value = (QuantityValue) kilopoundspercubicfoot; return new Density(value, DensityUnit.KilopoundPerCubicFoot); } @@ -862,7 +865,7 @@ public static Density FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubi /// If value is NaN or Infinity. public static Density FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubicinch) { - double value = (double) kilopoundspercubicinch; + QuantityValue value = (QuantityValue) kilopoundspercubicinch; return new Density(value, DensityUnit.KilopoundPerCubicInch); } @@ -872,7 +875,7 @@ public static Density FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubi /// If value is NaN or Infinity. public static Density FromMicrogramsPerCubicMeter(QuantityValue microgramspercubicmeter) { - double value = (double) microgramspercubicmeter; + QuantityValue value = (QuantityValue) microgramspercubicmeter; return new Density(value, DensityUnit.MicrogramPerCubicMeter); } @@ -882,7 +885,7 @@ public static Density FromMicrogramsPerCubicMeter(QuantityValue microgramspercub /// If value is NaN or Infinity. public static Density FromMicrogramsPerDeciLiter(QuantityValue microgramsperdeciliter) { - double value = (double) microgramsperdeciliter; + QuantityValue value = (QuantityValue) microgramsperdeciliter; return new Density(value, DensityUnit.MicrogramPerDeciliter); } @@ -892,7 +895,7 @@ public static Density FromMicrogramsPerDeciLiter(QuantityValue microgramsperdeci /// If value is NaN or Infinity. public static Density FromMicrogramsPerLiter(QuantityValue microgramsperliter) { - double value = (double) microgramsperliter; + QuantityValue value = (QuantityValue) microgramsperliter; return new Density(value, DensityUnit.MicrogramPerLiter); } @@ -902,7 +905,7 @@ public static Density FromMicrogramsPerLiter(QuantityValue microgramsperliter) /// If value is NaN or Infinity. public static Density FromMicrogramsPerMilliliter(QuantityValue microgramspermilliliter) { - double value = (double) microgramspermilliliter; + QuantityValue value = (QuantityValue) microgramspermilliliter; return new Density(value, DensityUnit.MicrogramPerMilliliter); } @@ -912,7 +915,7 @@ public static Density FromMicrogramsPerMilliliter(QuantityValue microgramspermil /// If value is NaN or Infinity. public static Density FromMilligramsPerCubicMeter(QuantityValue milligramspercubicmeter) { - double value = (double) milligramspercubicmeter; + QuantityValue value = (QuantityValue) milligramspercubicmeter; return new Density(value, DensityUnit.MilligramPerCubicMeter); } @@ -922,7 +925,7 @@ public static Density FromMilligramsPerCubicMeter(QuantityValue milligramspercub /// If value is NaN or Infinity. public static Density FromMilligramsPerDeciLiter(QuantityValue milligramsperdeciliter) { - double value = (double) milligramsperdeciliter; + QuantityValue value = (QuantityValue) milligramsperdeciliter; return new Density(value, DensityUnit.MilligramPerDeciliter); } @@ -932,7 +935,7 @@ public static Density FromMilligramsPerDeciLiter(QuantityValue milligramsperdeci /// If value is NaN or Infinity. public static Density FromMilligramsPerLiter(QuantityValue milligramsperliter) { - double value = (double) milligramsperliter; + QuantityValue value = (QuantityValue) milligramsperliter; return new Density(value, DensityUnit.MilligramPerLiter); } @@ -942,7 +945,7 @@ public static Density FromMilligramsPerLiter(QuantityValue milligramsperliter) /// If value is NaN or Infinity. public static Density FromMilligramsPerMilliliter(QuantityValue milligramspermilliliter) { - double value = (double) milligramspermilliliter; + QuantityValue value = (QuantityValue) milligramspermilliliter; return new Density(value, DensityUnit.MilligramPerMilliliter); } @@ -952,7 +955,7 @@ public static Density FromMilligramsPerMilliliter(QuantityValue milligramspermil /// If value is NaN or Infinity. public static Density FromNanogramsPerDeciLiter(QuantityValue nanogramsperdeciliter) { - double value = (double) nanogramsperdeciliter; + QuantityValue value = (QuantityValue) nanogramsperdeciliter; return new Density(value, DensityUnit.NanogramPerDeciliter); } @@ -962,7 +965,7 @@ public static Density FromNanogramsPerDeciLiter(QuantityValue nanogramsperdecili /// If value is NaN or Infinity. public static Density FromNanogramsPerLiter(QuantityValue nanogramsperliter) { - double value = (double) nanogramsperliter; + QuantityValue value = (QuantityValue) nanogramsperliter; return new Density(value, DensityUnit.NanogramPerLiter); } @@ -972,7 +975,7 @@ public static Density FromNanogramsPerLiter(QuantityValue nanogramsperliter) /// If value is NaN or Infinity. public static Density FromNanogramsPerMilliliter(QuantityValue nanogramspermilliliter) { - double value = (double) nanogramspermilliliter; + QuantityValue value = (QuantityValue) nanogramspermilliliter; return new Density(value, DensityUnit.NanogramPerMilliliter); } @@ -982,7 +985,7 @@ public static Density FromNanogramsPerMilliliter(QuantityValue nanogramspermilli /// If value is NaN or Infinity. public static Density FromPicogramsPerDeciLiter(QuantityValue picogramsperdeciliter) { - double value = (double) picogramsperdeciliter; + QuantityValue value = (QuantityValue) picogramsperdeciliter; return new Density(value, DensityUnit.PicogramPerDeciliter); } @@ -992,7 +995,7 @@ public static Density FromPicogramsPerDeciLiter(QuantityValue picogramsperdecili /// If value is NaN or Infinity. public static Density FromPicogramsPerLiter(QuantityValue picogramsperliter) { - double value = (double) picogramsperliter; + QuantityValue value = (QuantityValue) picogramsperliter; return new Density(value, DensityUnit.PicogramPerLiter); } @@ -1002,7 +1005,7 @@ public static Density FromPicogramsPerLiter(QuantityValue picogramsperliter) /// If value is NaN or Infinity. public static Density FromPicogramsPerMilliliter(QuantityValue picogramspermilliliter) { - double value = (double) picogramspermilliliter; + QuantityValue value = (QuantityValue) picogramspermilliliter; return new Density(value, DensityUnit.PicogramPerMilliliter); } @@ -1012,7 +1015,7 @@ public static Density FromPicogramsPerMilliliter(QuantityValue picogramspermilli /// If value is NaN or Infinity. public static Density FromPoundsPerCubicCentimeter(QuantityValue poundspercubiccentimeter) { - double value = (double) poundspercubiccentimeter; + QuantityValue value = (QuantityValue) poundspercubiccentimeter; return new Density(value, DensityUnit.PoundPerCubicCentimeter); } @@ -1022,7 +1025,7 @@ public static Density FromPoundsPerCubicCentimeter(QuantityValue poundspercubicc /// If value is NaN or Infinity. public static Density FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) { - double value = (double) poundspercubicfoot; + QuantityValue value = (QuantityValue) poundspercubicfoot; return new Density(value, DensityUnit.PoundPerCubicFoot); } @@ -1032,7 +1035,7 @@ public static Density FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) /// If value is NaN or Infinity. public static Density FromPoundsPerCubicInch(QuantityValue poundspercubicinch) { - double value = (double) poundspercubicinch; + QuantityValue value = (QuantityValue) poundspercubicinch; return new Density(value, DensityUnit.PoundPerCubicInch); } @@ -1042,7 +1045,7 @@ public static Density FromPoundsPerCubicInch(QuantityValue poundspercubicinch) /// If value is NaN or Infinity. public static Density FromPoundsPerCubicMeter(QuantityValue poundspercubicmeter) { - double value = (double) poundspercubicmeter; + QuantityValue value = (QuantityValue) poundspercubicmeter; return new Density(value, DensityUnit.PoundPerCubicMeter); } @@ -1052,7 +1055,7 @@ public static Density FromPoundsPerCubicMeter(QuantityValue poundspercubicmeter) /// If value is NaN or Infinity. public static Density FromPoundsPerCubicMillimeter(QuantityValue poundspercubicmillimeter) { - double value = (double) poundspercubicmillimeter; + QuantityValue value = (QuantityValue) poundspercubicmillimeter; return new Density(value, DensityUnit.PoundPerCubicMillimeter); } @@ -1062,7 +1065,7 @@ public static Density FromPoundsPerCubicMillimeter(QuantityValue poundspercubicm /// If value is NaN or Infinity. public static Density FromPoundsPerImperialGallon(QuantityValue poundsperimperialgallon) { - double value = (double) poundsperimperialgallon; + QuantityValue value = (QuantityValue) poundsperimperialgallon; return new Density(value, DensityUnit.PoundPerImperialGallon); } @@ -1072,7 +1075,7 @@ public static Density FromPoundsPerImperialGallon(QuantityValue poundsperimperia /// If value is NaN or Infinity. public static Density FromPoundsPerUSGallon(QuantityValue poundsperusgallon) { - double value = (double) poundsperusgallon; + QuantityValue value = (QuantityValue) poundsperusgallon; return new Density(value, DensityUnit.PoundPerUSGallon); } @@ -1082,7 +1085,7 @@ public static Density FromPoundsPerUSGallon(QuantityValue poundsperusgallon) /// If value is NaN or Infinity. public static Density FromSlugsPerCubicCentimeter(QuantityValue slugspercubiccentimeter) { - double value = (double) slugspercubiccentimeter; + QuantityValue value = (QuantityValue) slugspercubiccentimeter; return new Density(value, DensityUnit.SlugPerCubicCentimeter); } @@ -1092,7 +1095,7 @@ public static Density FromSlugsPerCubicCentimeter(QuantityValue slugspercubiccen /// If value is NaN or Infinity. public static Density FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) { - double value = (double) slugspercubicfoot; + QuantityValue value = (QuantityValue) slugspercubicfoot; return new Density(value, DensityUnit.SlugPerCubicFoot); } @@ -1102,7 +1105,7 @@ public static Density FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) /// If value is NaN or Infinity. public static Density FromSlugsPerCubicInch(QuantityValue slugspercubicinch) { - double value = (double) slugspercubicinch; + QuantityValue value = (QuantityValue) slugspercubicinch; return new Density(value, DensityUnit.SlugPerCubicInch); } @@ -1112,7 +1115,7 @@ public static Density FromSlugsPerCubicInch(QuantityValue slugspercubicinch) /// If value is NaN or Infinity. public static Density FromSlugsPerCubicMeter(QuantityValue slugspercubicmeter) { - double value = (double) slugspercubicmeter; + QuantityValue value = (QuantityValue) slugspercubicmeter; return new Density(value, DensityUnit.SlugPerCubicMeter); } @@ -1122,7 +1125,7 @@ public static Density FromSlugsPerCubicMeter(QuantityValue slugspercubicmeter) /// If value is NaN or Infinity. public static Density FromSlugsPerCubicMillimeter(QuantityValue slugspercubicmillimeter) { - double value = (double) slugspercubicmillimeter; + QuantityValue value = (QuantityValue) slugspercubicmillimeter; return new Density(value, DensityUnit.SlugPerCubicMillimeter); } @@ -1132,7 +1135,7 @@ public static Density FromSlugsPerCubicMillimeter(QuantityValue slugspercubicmil /// If value is NaN or Infinity. public static Density FromTonnesPerCubicCentimeter(QuantityValue tonnespercubiccentimeter) { - double value = (double) tonnespercubiccentimeter; + QuantityValue value = (QuantityValue) tonnespercubiccentimeter; return new Density(value, DensityUnit.TonnePerCubicCentimeter); } @@ -1142,7 +1145,7 @@ public static Density FromTonnesPerCubicCentimeter(QuantityValue tonnespercubicc /// If value is NaN or Infinity. public static Density FromTonnesPerCubicFoot(QuantityValue tonnespercubicfoot) { - double value = (double) tonnespercubicfoot; + QuantityValue value = (QuantityValue) tonnespercubicfoot; return new Density(value, DensityUnit.TonnePerCubicFoot); } @@ -1152,7 +1155,7 @@ public static Density FromTonnesPerCubicFoot(QuantityValue tonnespercubicfoot) /// If value is NaN or Infinity. public static Density FromTonnesPerCubicInch(QuantityValue tonnespercubicinch) { - double value = (double) tonnespercubicinch; + QuantityValue value = (QuantityValue) tonnespercubicinch; return new Density(value, DensityUnit.TonnePerCubicInch); } @@ -1162,7 +1165,7 @@ public static Density FromTonnesPerCubicInch(QuantityValue tonnespercubicinch) /// If value is NaN or Infinity. public static Density FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) { - double value = (double) tonnespercubicmeter; + QuantityValue value = (QuantityValue) tonnespercubicmeter; return new Density(value, DensityUnit.TonnePerCubicMeter); } @@ -1172,7 +1175,7 @@ public static Density FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) /// If value is NaN or Infinity. public static Density FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicmillimeter) { - double value = (double) tonnespercubicmillimeter; + QuantityValue value = (QuantityValue) tonnespercubicmillimeter; return new Density(value, DensityUnit.TonnePerCubicMillimeter); } @@ -1184,7 +1187,7 @@ public static Density FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicm /// Density unit value. public static Density From(QuantityValue value, DensityUnit fromUnit) { - return new Density((double)value, fromUnit); + return new Density((QuantityValue)value, fromUnit); } #endregion @@ -1354,25 +1357,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Densi } /// Get from multiplying value and . - public static Density operator *(double left, Density right) + public static Density operator *(QuantityValue left, Density right) { return new Density(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Density operator *(Density left, double right) + public static Density operator *(Density left, QuantityValue right) { return new Density(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Density operator /(Density left, double right) + public static Density operator /(Density left, QuantityValue right) { return new Density(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Density left, Density right) + public static QuantityValue operator /(Density left, Density right) { return left.KilogramsPerCubicMeter / right.KilogramsPerCubicMeter; } @@ -1405,6 +1408,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Densi return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Density left, Density right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Density left, Density right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1417,7 +1433,29 @@ public int CompareTo(object obj) /// public int CompareTo(Density other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Density objDensity)) + return false; + return Equals(objDensity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Density other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1460,13 +1498,13 @@ public int CompareTo(Density other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Density other, double tolerance, ComparisonType comparisonType) + public bool Equals(Density other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1477,7 +1515,7 @@ public bool Equals(Density other, double tolerance, ComparisonType comparisonTyp /// A hash code for the current Density. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1488,17 +1526,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(DensityUnit unit) + public QuantityValue As(DensityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1513,12 +1550,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is DensityUnit unitAsDensityUnit)) + if (!(unit is DensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DensityUnit)} is supported.", nameof(unit)); - return As(unitAsDensityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1550,7 +1587,7 @@ public Density ToUnit(DensityUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Density)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(DensityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1558,17 +1595,17 @@ public Density ToUnit(DensityUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is DensityUnit unitAsDensityUnit)) + if (!(unit is DensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1595,10 +1632,10 @@ public Density ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(DensityUnit unit) + private QuantityValue GetValueAs(DensityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs index 31dfb5c9b9..3119b90332 100644 --- a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them. /// [DataContract] - public partial struct Duration : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Duration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -82,9 +82,9 @@ static Duration() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Duration(double value, DurationUnit unit) + public Duration(QuantityValue value, DurationUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -96,14 +96,14 @@ public Duration(double value, DurationUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Duration(double value, UnitSystem unitSystem) + public Duration(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -144,7 +144,10 @@ public Duration(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -167,59 +170,59 @@ public Duration(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Days => As(DurationUnit.Day); + public QuantityValue Days => As(DurationUnit.Day); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Hours => As(DurationUnit.Hour); + public QuantityValue Hours => As(DurationUnit.Hour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JulianYears => As(DurationUnit.JulianYear); + public QuantityValue JulianYears => As(DurationUnit.JulianYear); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microseconds => As(DurationUnit.Microsecond); + public QuantityValue Microseconds => As(DurationUnit.Microsecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milliseconds => As(DurationUnit.Millisecond); + public QuantityValue Milliseconds => As(DurationUnit.Millisecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Minutes => As(DurationUnit.Minute); + public QuantityValue Minutes => As(DurationUnit.Minute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Months30 => As(DurationUnit.Month30); + public QuantityValue Months30 => As(DurationUnit.Month30); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanoseconds => As(DurationUnit.Nanosecond); + public QuantityValue Nanoseconds => As(DurationUnit.Nanosecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Seconds => As(DurationUnit.Second); + public QuantityValue Seconds => As(DurationUnit.Second); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Weeks => As(DurationUnit.Week); + public QuantityValue Weeks => As(DurationUnit.Week); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Years365 => As(DurationUnit.Year365); + public QuantityValue Years365 => As(DurationUnit.Year365); #endregion @@ -315,7 +318,7 @@ public static string GetAbbreviation(DurationUnit unit, IFormatProvider? provide /// If value is NaN or Infinity. public static Duration FromDays(QuantityValue days) { - double value = (double) days; + QuantityValue value = (QuantityValue) days; return new Duration(value, DurationUnit.Day); } @@ -325,7 +328,7 @@ public static Duration FromDays(QuantityValue days) /// If value is NaN or Infinity. public static Duration FromHours(QuantityValue hours) { - double value = (double) hours; + QuantityValue value = (QuantityValue) hours; return new Duration(value, DurationUnit.Hour); } @@ -335,7 +338,7 @@ public static Duration FromHours(QuantityValue hours) /// If value is NaN or Infinity. public static Duration FromJulianYears(QuantityValue julianyears) { - double value = (double) julianyears; + QuantityValue value = (QuantityValue) julianyears; return new Duration(value, DurationUnit.JulianYear); } @@ -345,7 +348,7 @@ public static Duration FromJulianYears(QuantityValue julianyears) /// If value is NaN or Infinity. public static Duration FromMicroseconds(QuantityValue microseconds) { - double value = (double) microseconds; + QuantityValue value = (QuantityValue) microseconds; return new Duration(value, DurationUnit.Microsecond); } @@ -355,7 +358,7 @@ public static Duration FromMicroseconds(QuantityValue microseconds) /// If value is NaN or Infinity. public static Duration FromMilliseconds(QuantityValue milliseconds) { - double value = (double) milliseconds; + QuantityValue value = (QuantityValue) milliseconds; return new Duration(value, DurationUnit.Millisecond); } @@ -365,7 +368,7 @@ public static Duration FromMilliseconds(QuantityValue milliseconds) /// If value is NaN or Infinity. public static Duration FromMinutes(QuantityValue minutes) { - double value = (double) minutes; + QuantityValue value = (QuantityValue) minutes; return new Duration(value, DurationUnit.Minute); } @@ -375,7 +378,7 @@ public static Duration FromMinutes(QuantityValue minutes) /// If value is NaN or Infinity. public static Duration FromMonths30(QuantityValue months30) { - double value = (double) months30; + QuantityValue value = (QuantityValue) months30; return new Duration(value, DurationUnit.Month30); } @@ -385,7 +388,7 @@ public static Duration FromMonths30(QuantityValue months30) /// If value is NaN or Infinity. public static Duration FromNanoseconds(QuantityValue nanoseconds) { - double value = (double) nanoseconds; + QuantityValue value = (QuantityValue) nanoseconds; return new Duration(value, DurationUnit.Nanosecond); } @@ -395,7 +398,7 @@ public static Duration FromNanoseconds(QuantityValue nanoseconds) /// If value is NaN or Infinity. public static Duration FromSeconds(QuantityValue seconds) { - double value = (double) seconds; + QuantityValue value = (QuantityValue) seconds; return new Duration(value, DurationUnit.Second); } @@ -405,7 +408,7 @@ public static Duration FromSeconds(QuantityValue seconds) /// If value is NaN or Infinity. public static Duration FromWeeks(QuantityValue weeks) { - double value = (double) weeks; + QuantityValue value = (QuantityValue) weeks; return new Duration(value, DurationUnit.Week); } @@ -415,7 +418,7 @@ public static Duration FromWeeks(QuantityValue weeks) /// If value is NaN or Infinity. public static Duration FromYears365(QuantityValue years365) { - double value = (double) years365; + QuantityValue value = (QuantityValue) years365; return new Duration(value, DurationUnit.Year365); } @@ -427,7 +430,7 @@ public static Duration FromYears365(QuantityValue years365) /// Duration unit value. public static Duration From(QuantityValue value, DurationUnit fromUnit) { - return new Duration((double)value, fromUnit); + return new Duration((QuantityValue)value, fromUnit); } #endregion @@ -597,25 +600,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Durat } /// Get from multiplying value and . - public static Duration operator *(double left, Duration right) + public static Duration operator *(QuantityValue left, Duration right) { return new Duration(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Duration operator *(Duration left, double right) + public static Duration operator *(Duration left, QuantityValue right) { return new Duration(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Duration operator /(Duration left, double right) + public static Duration operator /(Duration left, QuantityValue right) { return new Duration(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Duration left, Duration right) + public static QuantityValue operator /(Duration left, Duration right) { return left.Seconds / right.Seconds; } @@ -648,6 +651,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Durat return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Duration left, Duration right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Duration left, Duration right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -660,7 +676,29 @@ public int CompareTo(object obj) /// public int CompareTo(Duration other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Duration objDuration)) + return false; + return Equals(objDuration); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Duration other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -703,13 +741,13 @@ public int CompareTo(Duration other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Duration other, double tolerance, ComparisonType comparisonType) + public bool Equals(Duration other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -720,7 +758,7 @@ public bool Equals(Duration other, double tolerance, ComparisonType comparisonTy /// A hash code for the current Duration. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -731,17 +769,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(DurationUnit unit) + public QuantityValue As(DurationUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -756,12 +793,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is DurationUnit unitAsDurationUnit)) + if (!(unit is DurationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DurationUnit)} is supported.", nameof(unit)); - return As(unitAsDurationUnit); + return (QuantityValue)As(typedUnit); } /// @@ -793,7 +830,7 @@ public Duration ToUnit(DurationUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Duration)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(DurationUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -801,17 +838,17 @@ public Duration ToUnit(DurationUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is DurationUnit unitAsDurationUnit)) + if (!(unit is DurationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DurationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsDurationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -838,10 +875,10 @@ public Duration ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(DurationUnit unit) + private QuantityValue GetValueAs(DurationUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs index ec17be7043..90cee77932 100644 --- a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity /// [DataContract] - public partial struct DynamicViscosity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct DynamicViscosity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -84,9 +84,9 @@ static DynamicViscosity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public DynamicViscosity(double value, DynamicViscosityUnit unit) + public DynamicViscosity(QuantityValue value, DynamicViscosityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -98,14 +98,14 @@ public DynamicViscosity(double value, DynamicViscosityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public DynamicViscosity(double value, UnitSystem unitSystem) + public DynamicViscosity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -146,7 +146,10 @@ public DynamicViscosity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -169,54 +172,54 @@ public DynamicViscosity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Centipoise => As(DynamicViscosityUnit.Centipoise); + public QuantityValue Centipoise => As(DynamicViscosityUnit.Centipoise); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); + public QuantityValue MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); + public QuantityValue MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); + public QuantityValue NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PascalSeconds => As(DynamicViscosityUnit.PascalSecond); + public QuantityValue PascalSeconds => As(DynamicViscosityUnit.PascalSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Poise => As(DynamicViscosityUnit.Poise); + public QuantityValue Poise => As(DynamicViscosityUnit.Poise); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForceSecondPerSquareFoot => As(DynamicViscosityUnit.PoundForceSecondPerSquareFoot); + public QuantityValue PoundsForceSecondPerSquareFoot => As(DynamicViscosityUnit.PoundForceSecondPerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForceSecondPerSquareInch => As(DynamicViscosityUnit.PoundForceSecondPerSquareInch); + public QuantityValue PoundsForceSecondPerSquareInch => As(DynamicViscosityUnit.PoundForceSecondPerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerFootSecond => As(DynamicViscosityUnit.PoundPerFootSecond); + public QuantityValue PoundsPerFootSecond => As(DynamicViscosityUnit.PoundPerFootSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Reyns => As(DynamicViscosityUnit.Reyn); + public QuantityValue Reyns => As(DynamicViscosityUnit.Reyn); #endregion @@ -299,7 +302,7 @@ public static string GetAbbreviation(DynamicViscosityUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static DynamicViscosity FromCentipoise(QuantityValue centipoise) { - double value = (double) centipoise; + QuantityValue value = (QuantityValue) centipoise; return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); } @@ -309,7 +312,7 @@ public static DynamicViscosity FromCentipoise(QuantityValue centipoise) /// If value is NaN or Infinity. public static DynamicViscosity FromMicropascalSeconds(QuantityValue micropascalseconds) { - double value = (double) micropascalseconds; + QuantityValue value = (QuantityValue) micropascalseconds; return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); } @@ -319,7 +322,7 @@ public static DynamicViscosity FromMicropascalSeconds(QuantityValue micropascals /// If value is NaN or Infinity. public static DynamicViscosity FromMillipascalSeconds(QuantityValue millipascalseconds) { - double value = (double) millipascalseconds; + QuantityValue value = (QuantityValue) millipascalseconds; return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); } @@ -329,7 +332,7 @@ public static DynamicViscosity FromMillipascalSeconds(QuantityValue millipascals /// If value is NaN or Infinity. public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue newtonsecondspermetersquared) { - double value = (double) newtonsecondspermetersquared; + QuantityValue value = (QuantityValue) newtonsecondspermetersquared; return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); } @@ -339,7 +342,7 @@ public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue ne /// If value is NaN or Infinity. public static DynamicViscosity FromPascalSeconds(QuantityValue pascalseconds) { - double value = (double) pascalseconds; + QuantityValue value = (QuantityValue) pascalseconds; return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); } @@ -349,7 +352,7 @@ public static DynamicViscosity FromPascalSeconds(QuantityValue pascalseconds) /// If value is NaN or Infinity. public static DynamicViscosity FromPoise(QuantityValue poise) { - double value = (double) poise; + QuantityValue value = (QuantityValue) poise; return new DynamicViscosity(value, DynamicViscosityUnit.Poise); } @@ -359,7 +362,7 @@ public static DynamicViscosity FromPoise(QuantityValue poise) /// If value is NaN or Infinity. public static DynamicViscosity FromPoundsForceSecondPerSquareFoot(QuantityValue poundsforcesecondpersquarefoot) { - double value = (double) poundsforcesecondpersquarefoot; + QuantityValue value = (QuantityValue) poundsforcesecondpersquarefoot; return new DynamicViscosity(value, DynamicViscosityUnit.PoundForceSecondPerSquareFoot); } @@ -369,7 +372,7 @@ public static DynamicViscosity FromPoundsForceSecondPerSquareFoot(QuantityValue /// If value is NaN or Infinity. public static DynamicViscosity FromPoundsForceSecondPerSquareInch(QuantityValue poundsforcesecondpersquareinch) { - double value = (double) poundsforcesecondpersquareinch; + QuantityValue value = (QuantityValue) poundsforcesecondpersquareinch; return new DynamicViscosity(value, DynamicViscosityUnit.PoundForceSecondPerSquareInch); } @@ -379,7 +382,7 @@ public static DynamicViscosity FromPoundsForceSecondPerSquareInch(QuantityValue /// If value is NaN or Infinity. public static DynamicViscosity FromPoundsPerFootSecond(QuantityValue poundsperfootsecond) { - double value = (double) poundsperfootsecond; + QuantityValue value = (QuantityValue) poundsperfootsecond; return new DynamicViscosity(value, DynamicViscosityUnit.PoundPerFootSecond); } @@ -389,7 +392,7 @@ public static DynamicViscosity FromPoundsPerFootSecond(QuantityValue poundsperfo /// If value is NaN or Infinity. public static DynamicViscosity FromReyns(QuantityValue reyns) { - double value = (double) reyns; + QuantityValue value = (QuantityValue) reyns; return new DynamicViscosity(value, DynamicViscosityUnit.Reyn); } @@ -401,7 +404,7 @@ public static DynamicViscosity FromReyns(QuantityValue reyns) /// DynamicViscosity unit value. public static DynamicViscosity From(QuantityValue value, DynamicViscosityUnit fromUnit) { - return new DynamicViscosity((double)value, fromUnit); + return new DynamicViscosity((QuantityValue)value, fromUnit); } #endregion @@ -571,25 +574,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Dynam } /// Get from multiplying value and . - public static DynamicViscosity operator *(double left, DynamicViscosity right) + public static DynamicViscosity operator *(QuantityValue left, DynamicViscosity right) { return new DynamicViscosity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static DynamicViscosity operator *(DynamicViscosity left, double right) + public static DynamicViscosity operator *(DynamicViscosity left, QuantityValue right) { return new DynamicViscosity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static DynamicViscosity operator /(DynamicViscosity left, double right) + public static DynamicViscosity operator /(DynamicViscosity left, QuantityValue right) { return new DynamicViscosity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(DynamicViscosity left, DynamicViscosity right) + public static QuantityValue operator /(DynamicViscosity left, DynamicViscosity right) { return left.NewtonSecondsPerMeterSquared / right.NewtonSecondsPerMeterSquared; } @@ -622,6 +625,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Dynam return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(DynamicViscosity left, DynamicViscosity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(DynamicViscosity left, DynamicViscosity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -634,7 +650,29 @@ public int CompareTo(object obj) /// public int CompareTo(DynamicViscosity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is DynamicViscosity objDynamicViscosity)) + return false; + return Equals(objDynamicViscosity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(DynamicViscosity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -677,13 +715,13 @@ public int CompareTo(DynamicViscosity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(DynamicViscosity other, double tolerance, ComparisonType comparisonType) + public bool Equals(DynamicViscosity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -694,7 +732,7 @@ public bool Equals(DynamicViscosity other, double tolerance, ComparisonType comp /// A hash code for the current DynamicViscosity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -705,17 +743,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(DynamicViscosityUnit unit) + public QuantityValue As(DynamicViscosityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -730,12 +767,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is DynamicViscosityUnit unitAsDynamicViscosityUnit)) + if (!(unit is DynamicViscosityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DynamicViscosityUnit)} is supported.", nameof(unit)); - return As(unitAsDynamicViscosityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -767,7 +804,7 @@ public DynamicViscosity ToUnit(DynamicViscosityUnit unit, UnitConverter unitConv var converted = conversionFunction(this); return (DynamicViscosity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(DynamicViscosityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -775,17 +812,17 @@ public DynamicViscosity ToUnit(DynamicViscosityUnit unit, UnitConverter unitConv } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is DynamicViscosityUnit unitAsDynamicViscosityUnit)) + if (!(unit is DynamicViscosityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DynamicViscosityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsDynamicViscosityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -812,10 +849,10 @@ public DynamicViscosity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(DynamicViscosityUnit unit) + private QuantityValue GetValueAs(DynamicViscosityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs index 5f6f688ac8..5cab50ab8c 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S). /// [DataContract] - public partial struct ElectricAdmittance : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricAdmittance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static ElectricAdmittance() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricAdmittance(double value, ElectricAdmittanceUnit unit) + public ElectricAdmittance(QuantityValue value, ElectricAdmittanceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public ElectricAdmittance(double value, ElectricAdmittanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricAdmittance(double value, UnitSystem unitSystem) + public ElectricAdmittance(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,24 +163,24 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); + public QuantityValue Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); + public QuantityValue Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); + public QuantityValue Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Siemens => As(ElectricAdmittanceUnit.Siemens); + public QuantityValue Siemens => As(ElectricAdmittanceUnit.Siemens); #endregion @@ -242,7 +245,7 @@ public static string GetAbbreviation(ElectricAdmittanceUnit unit, IFormatProvide /// If value is NaN or Infinity. public static ElectricAdmittance FromMicrosiemens(QuantityValue microsiemens) { - double value = (double) microsiemens; + QuantityValue value = (QuantityValue) microsiemens; return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); } @@ -252,7 +255,7 @@ public static ElectricAdmittance FromMicrosiemens(QuantityValue microsiemens) /// If value is NaN or Infinity. public static ElectricAdmittance FromMillisiemens(QuantityValue millisiemens) { - double value = (double) millisiemens; + QuantityValue value = (QuantityValue) millisiemens; return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); } @@ -262,7 +265,7 @@ public static ElectricAdmittance FromMillisiemens(QuantityValue millisiemens) /// If value is NaN or Infinity. public static ElectricAdmittance FromNanosiemens(QuantityValue nanosiemens) { - double value = (double) nanosiemens; + QuantityValue value = (QuantityValue) nanosiemens; return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); } @@ -272,7 +275,7 @@ public static ElectricAdmittance FromNanosiemens(QuantityValue nanosiemens) /// If value is NaN or Infinity. public static ElectricAdmittance FromSiemens(QuantityValue siemens) { - double value = (double) siemens; + QuantityValue value = (QuantityValue) siemens; return new ElectricAdmittance(value, ElectricAdmittanceUnit.Siemens); } @@ -284,7 +287,7 @@ public static ElectricAdmittance FromSiemens(QuantityValue siemens) /// ElectricAdmittance unit value. public static ElectricAdmittance From(QuantityValue value, ElectricAdmittanceUnit fromUnit) { - return new ElectricAdmittance((double)value, fromUnit); + return new ElectricAdmittance((QuantityValue)value, fromUnit); } #endregion @@ -454,25 +457,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricAdmittance operator *(double left, ElectricAdmittance right) + public static ElectricAdmittance operator *(QuantityValue left, ElectricAdmittance right) { return new ElectricAdmittance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricAdmittance operator *(ElectricAdmittance left, double right) + public static ElectricAdmittance operator *(ElectricAdmittance left, QuantityValue right) { return new ElectricAdmittance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricAdmittance operator /(ElectricAdmittance left, double right) + public static ElectricAdmittance operator /(ElectricAdmittance left, QuantityValue right) { return new ElectricAdmittance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricAdmittance left, ElectricAdmittance right) + public static QuantityValue operator /(ElectricAdmittance left, ElectricAdmittance right) { return left.Siemens / right.Siemens; } @@ -505,6 +508,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricAdmittance left, ElectricAdmittance right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -517,7 +533,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricAdmittance other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricAdmittance objElectricAdmittance)) + return false; + return Equals(objElectricAdmittance); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricAdmittance other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -560,13 +598,13 @@ public int CompareTo(ElectricAdmittance other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricAdmittance other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricAdmittance other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -577,7 +615,7 @@ public bool Equals(ElectricAdmittance other, double tolerance, ComparisonType co /// A hash code for the current ElectricAdmittance. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -588,17 +626,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricAdmittanceUnit unit) + public QuantityValue As(ElectricAdmittanceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -613,12 +650,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricAdmittanceUnit unitAsElectricAdmittanceUnit)) + if (!(unit is ElectricAdmittanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricAdmittanceUnit)} is supported.", nameof(unit)); - return As(unitAsElectricAdmittanceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -650,7 +687,7 @@ public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit, UnitConverter unit var converted = conversionFunction(this); return (ElectricAdmittance)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricAdmittanceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -658,17 +695,17 @@ public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit, UnitConverter unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricAdmittanceUnit unitAsElectricAdmittanceUnit)) + if (!(unit is ElectricAdmittanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricAdmittanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricAdmittanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -695,10 +732,10 @@ public ElectricAdmittance ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricAdmittanceUnit unit) + private QuantityValue GetValueAs(ElectricAdmittanceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs index efdcf152cd..088da970dd 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electric_charge /// [DataContract] - public partial struct ElectricCharge : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricCharge : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -79,9 +79,9 @@ static ElectricCharge() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricCharge(double value, ElectricChargeUnit unit) + public ElectricCharge(QuantityValue value, ElectricChargeUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -93,14 +93,14 @@ public ElectricCharge(double value, ElectricChargeUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricCharge(double value, UnitSystem unitSystem) + public ElectricCharge(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -141,7 +141,10 @@ public ElectricCharge(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -164,29 +167,29 @@ public ElectricCharge(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AmpereHours => As(ElectricChargeUnit.AmpereHour); + public QuantityValue AmpereHours => As(ElectricChargeUnit.AmpereHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Coulombs => As(ElectricChargeUnit.Coulomb); + public QuantityValue Coulombs => As(ElectricChargeUnit.Coulomb); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KiloampereHours => As(ElectricChargeUnit.KiloampereHour); + public QuantityValue KiloampereHours => As(ElectricChargeUnit.KiloampereHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegaampereHours => As(ElectricChargeUnit.MegaampereHour); + public QuantityValue MegaampereHours => As(ElectricChargeUnit.MegaampereHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliampereHours => As(ElectricChargeUnit.MilliampereHour); + public QuantityValue MilliampereHours => As(ElectricChargeUnit.MilliampereHour); #endregion @@ -254,7 +257,7 @@ public static string GetAbbreviation(ElectricChargeUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static ElectricCharge FromAmpereHours(QuantityValue amperehours) { - double value = (double) amperehours; + QuantityValue value = (QuantityValue) amperehours; return new ElectricCharge(value, ElectricChargeUnit.AmpereHour); } @@ -264,7 +267,7 @@ public static ElectricCharge FromAmpereHours(QuantityValue amperehours) /// If value is NaN or Infinity. public static ElectricCharge FromCoulombs(QuantityValue coulombs) { - double value = (double) coulombs; + QuantityValue value = (QuantityValue) coulombs; return new ElectricCharge(value, ElectricChargeUnit.Coulomb); } @@ -274,7 +277,7 @@ public static ElectricCharge FromCoulombs(QuantityValue coulombs) /// If value is NaN or Infinity. public static ElectricCharge FromKiloampereHours(QuantityValue kiloamperehours) { - double value = (double) kiloamperehours; + QuantityValue value = (QuantityValue) kiloamperehours; return new ElectricCharge(value, ElectricChargeUnit.KiloampereHour); } @@ -284,7 +287,7 @@ public static ElectricCharge FromKiloampereHours(QuantityValue kiloamperehours) /// If value is NaN or Infinity. public static ElectricCharge FromMegaampereHours(QuantityValue megaamperehours) { - double value = (double) megaamperehours; + QuantityValue value = (QuantityValue) megaamperehours; return new ElectricCharge(value, ElectricChargeUnit.MegaampereHour); } @@ -294,7 +297,7 @@ public static ElectricCharge FromMegaampereHours(QuantityValue megaamperehours) /// If value is NaN or Infinity. public static ElectricCharge FromMilliampereHours(QuantityValue milliamperehours) { - double value = (double) milliamperehours; + QuantityValue value = (QuantityValue) milliamperehours; return new ElectricCharge(value, ElectricChargeUnit.MilliampereHour); } @@ -306,7 +309,7 @@ public static ElectricCharge FromMilliampereHours(QuantityValue milliamperehours /// ElectricCharge unit value. public static ElectricCharge From(QuantityValue value, ElectricChargeUnit fromUnit) { - return new ElectricCharge((double)value, fromUnit); + return new ElectricCharge((QuantityValue)value, fromUnit); } #endregion @@ -476,25 +479,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricCharge operator *(double left, ElectricCharge right) + public static ElectricCharge operator *(QuantityValue left, ElectricCharge right) { return new ElectricCharge(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricCharge operator *(ElectricCharge left, double right) + public static ElectricCharge operator *(ElectricCharge left, QuantityValue right) { return new ElectricCharge(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricCharge operator /(ElectricCharge left, double right) + public static ElectricCharge operator /(ElectricCharge left, QuantityValue right) { return new ElectricCharge(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricCharge left, ElectricCharge right) + public static QuantityValue operator /(ElectricCharge left, ElectricCharge right) { return left.Coulombs / right.Coulombs; } @@ -527,6 +530,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricCharge left, ElectricCharge right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricCharge left, ElectricCharge right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -539,7 +555,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricCharge other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricCharge objElectricCharge)) + return false; + return Equals(objElectricCharge); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricCharge other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -582,13 +620,13 @@ public int CompareTo(ElectricCharge other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCharge other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricCharge other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -599,7 +637,7 @@ public bool Equals(ElectricCharge other, double tolerance, ComparisonType compar /// A hash code for the current ElectricCharge. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -610,17 +648,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricChargeUnit unit) + public QuantityValue As(ElectricChargeUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -635,12 +672,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricChargeUnit unitAsElectricChargeUnit)) + if (!(unit is ElectricChargeUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeUnit)} is supported.", nameof(unit)); - return As(unitAsElectricChargeUnit); + return (QuantityValue)As(typedUnit); } /// @@ -672,7 +709,7 @@ public ElectricCharge ToUnit(ElectricChargeUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (ElectricCharge)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricChargeUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -680,17 +717,17 @@ public ElectricCharge ToUnit(ElectricChargeUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricChargeUnit unitAsElectricChargeUnit)) + if (!(unit is ElectricChargeUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricChargeUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -717,10 +754,10 @@ public ElectricCharge ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricChargeUnit unit) + private QuantityValue GetValueAs(ElectricChargeUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs index 4538e7e215..470af68bd9 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Charge_density /// [DataContract] - public partial struct ElectricChargeDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricChargeDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static ElectricChargeDensity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricChargeDensity(double value, ElectricChargeDensityUnit unit) + public ElectricChargeDensity(QuantityValue value, ElectricChargeDensityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public ElectricChargeDensity(double value, ElectricChargeDensityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricChargeDensity(double value, UnitSystem unitSystem) + public ElectricChargeDensity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); + public QuantityValue CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(ElectricChargeDensityUnit unit, IFormatProv /// If value is NaN or Infinity. public static ElectricChargeDensity FromCoulombsPerCubicMeter(QuantityValue coulombspercubicmeter) { - double value = (double) coulombspercubicmeter; + QuantityValue value = (QuantityValue) coulombspercubicmeter; return new ElectricChargeDensity(value, ElectricChargeDensityUnit.CoulombPerCubicMeter); } @@ -230,7 +233,7 @@ public static ElectricChargeDensity FromCoulombsPerCubicMeter(QuantityValue coul /// ElectricChargeDensity unit value. public static ElectricChargeDensity From(QuantityValue value, ElectricChargeDensityUnit fromUnit) { - return new ElectricChargeDensity((double)value, fromUnit); + return new ElectricChargeDensity((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricChargeDensity operator *(double left, ElectricChargeDensity right) + public static ElectricChargeDensity operator *(QuantityValue left, ElectricChargeDensity right) { return new ElectricChargeDensity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricChargeDensity operator *(ElectricChargeDensity left, double right) + public static ElectricChargeDensity operator *(ElectricChargeDensity left, QuantityValue right) { return new ElectricChargeDensity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricChargeDensity operator /(ElectricChargeDensity left, double right) + public static ElectricChargeDensity operator /(ElectricChargeDensity left, QuantityValue right) { return new ElectricChargeDensity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricChargeDensity left, ElectricChargeDensity right) + public static QuantityValue operator /(ElectricChargeDensity left, ElectricChargeDensity right) { return left.CoulombsPerCubicMeter / right.CoulombsPerCubicMeter; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricChargeDensity left, ElectricChargeDensity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricChargeDensity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricChargeDensity objElectricChargeDensity)) + return false; + return Equals(objElectricChargeDensity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricChargeDensity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(ElectricChargeDensity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricChargeDensity other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricChargeDensity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(ElectricChargeDensity other, double tolerance, ComparisonType /// A hash code for the current ElectricChargeDensity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricChargeDensityUnit unit) + public QuantityValue As(ElectricChargeDensityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricChargeDensityUnit unitAsElectricChargeDensityUnit)) + if (!(unit is ElectricChargeDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeDensityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricChargeDensityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit, UnitConverte var converted = conversionFunction(this); return (ElectricChargeDensity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricChargeDensityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit, UnitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricChargeDensityUnit unitAsElectricChargeDensityUnit)) + if (!(unit is ElectricChargeDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricChargeDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public ElectricChargeDensity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricChargeDensityUnit unit) + private QuantityValue GetValueAs(ElectricChargeDensityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs index f9f766a99d..885748e77b 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance /// [DataContract] - public partial struct ElectricConductance : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricConductance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -77,9 +77,9 @@ static ElectricConductance() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricConductance(double value, ElectricConductanceUnit unit) + public ElectricConductance(QuantityValue value, ElectricConductanceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -91,14 +91,14 @@ public ElectricConductance(double value, ElectricConductanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricConductance(double value, UnitSystem unitSystem) + public ElectricConductance(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -139,7 +139,10 @@ public ElectricConductance(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -162,19 +165,19 @@ public ElectricConductance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microsiemens => As(ElectricConductanceUnit.Microsiemens); + public QuantityValue Microsiemens => As(ElectricConductanceUnit.Microsiemens); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millisiemens => As(ElectricConductanceUnit.Millisiemens); + public QuantityValue Millisiemens => As(ElectricConductanceUnit.Millisiemens); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Siemens => As(ElectricConductanceUnit.Siemens); + public QuantityValue Siemens => As(ElectricConductanceUnit.Siemens); #endregion @@ -236,7 +239,7 @@ public static string GetAbbreviation(ElectricConductanceUnit unit, IFormatProvid /// If value is NaN or Infinity. public static ElectricConductance FromMicrosiemens(QuantityValue microsiemens) { - double value = (double) microsiemens; + QuantityValue value = (QuantityValue) microsiemens; return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); } @@ -246,7 +249,7 @@ public static ElectricConductance FromMicrosiemens(QuantityValue microsiemens) /// If value is NaN or Infinity. public static ElectricConductance FromMillisiemens(QuantityValue millisiemens) { - double value = (double) millisiemens; + QuantityValue value = (QuantityValue) millisiemens; return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); } @@ -256,7 +259,7 @@ public static ElectricConductance FromMillisiemens(QuantityValue millisiemens) /// If value is NaN or Infinity. public static ElectricConductance FromSiemens(QuantityValue siemens) { - double value = (double) siemens; + QuantityValue value = (QuantityValue) siemens; return new ElectricConductance(value, ElectricConductanceUnit.Siemens); } @@ -268,7 +271,7 @@ public static ElectricConductance FromSiemens(QuantityValue siemens) /// ElectricConductance unit value. public static ElectricConductance From(QuantityValue value, ElectricConductanceUnit fromUnit) { - return new ElectricConductance((double)value, fromUnit); + return new ElectricConductance((QuantityValue)value, fromUnit); } #endregion @@ -438,25 +441,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricConductance operator *(double left, ElectricConductance right) + public static ElectricConductance operator *(QuantityValue left, ElectricConductance right) { return new ElectricConductance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricConductance operator *(ElectricConductance left, double right) + public static ElectricConductance operator *(ElectricConductance left, QuantityValue right) { return new ElectricConductance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricConductance operator /(ElectricConductance left, double right) + public static ElectricConductance operator /(ElectricConductance left, QuantityValue right) { return new ElectricConductance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricConductance left, ElectricConductance right) + public static QuantityValue operator /(ElectricConductance left, ElectricConductance right) { return left.Siemens / right.Siemens; } @@ -489,6 +492,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricConductance left, ElectricConductance right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricConductance left, ElectricConductance right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -501,7 +517,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricConductance other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricConductance objElectricConductance)) + return false; + return Equals(objElectricConductance); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricConductance other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -544,13 +582,13 @@ public int CompareTo(ElectricConductance other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricConductance other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricConductance other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -561,7 +599,7 @@ public bool Equals(ElectricConductance other, double tolerance, ComparisonType c /// A hash code for the current ElectricConductance. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -572,17 +610,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricConductanceUnit unit) + public QuantityValue As(ElectricConductanceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -597,12 +634,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricConductanceUnit unitAsElectricConductanceUnit)) + if (!(unit is ElectricConductanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductanceUnit)} is supported.", nameof(unit)); - return As(unitAsElectricConductanceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -634,7 +671,7 @@ public ElectricConductance ToUnit(ElectricConductanceUnit unit, UnitConverter un var converted = conversionFunction(this); return (ElectricConductance)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricConductanceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -642,17 +679,17 @@ public ElectricConductance ToUnit(ElectricConductanceUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricConductanceUnit unitAsElectricConductanceUnit)) + if (!(unit is ElectricConductanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricConductanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -679,10 +716,10 @@ public ElectricConductance ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricConductanceUnit unit) + private QuantityValue GetValueAs(ElectricConductanceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs index 8b7f49777a..50efdddf94 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity /// [DataContract] - public partial struct ElectricConductivity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricConductivity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -77,9 +77,9 @@ static ElectricConductivity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricConductivity(double value, ElectricConductivityUnit unit) + public ElectricConductivity(QuantityValue value, ElectricConductivityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -91,14 +91,14 @@ public ElectricConductivity(double value, ElectricConductivityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricConductivity(double value, UnitSystem unitSystem) + public ElectricConductivity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -139,7 +139,10 @@ public ElectricConductivity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -162,19 +165,19 @@ public ElectricConductivity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SiemensPerFoot => As(ElectricConductivityUnit.SiemensPerFoot); + public QuantityValue SiemensPerFoot => As(ElectricConductivityUnit.SiemensPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SiemensPerInch => As(ElectricConductivityUnit.SiemensPerInch); + public QuantityValue SiemensPerInch => As(ElectricConductivityUnit.SiemensPerInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); + public QuantityValue SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); #endregion @@ -236,7 +239,7 @@ public static string GetAbbreviation(ElectricConductivityUnit unit, IFormatProvi /// If value is NaN or Infinity. public static ElectricConductivity FromSiemensPerFoot(QuantityValue siemensperfoot) { - double value = (double) siemensperfoot; + QuantityValue value = (QuantityValue) siemensperfoot; return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerFoot); } @@ -246,7 +249,7 @@ public static ElectricConductivity FromSiemensPerFoot(QuantityValue siemensperfo /// If value is NaN or Infinity. public static ElectricConductivity FromSiemensPerInch(QuantityValue siemensperinch) { - double value = (double) siemensperinch; + QuantityValue value = (QuantityValue) siemensperinch; return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerInch); } @@ -256,7 +259,7 @@ public static ElectricConductivity FromSiemensPerInch(QuantityValue siemensperin /// If value is NaN or Infinity. public static ElectricConductivity FromSiemensPerMeter(QuantityValue siemenspermeter) { - double value = (double) siemenspermeter; + QuantityValue value = (QuantityValue) siemenspermeter; return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerMeter); } @@ -268,7 +271,7 @@ public static ElectricConductivity FromSiemensPerMeter(QuantityValue siemensperm /// ElectricConductivity unit value. public static ElectricConductivity From(QuantityValue value, ElectricConductivityUnit fromUnit) { - return new ElectricConductivity((double)value, fromUnit); + return new ElectricConductivity((QuantityValue)value, fromUnit); } #endregion @@ -438,25 +441,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricConductivity operator *(double left, ElectricConductivity right) + public static ElectricConductivity operator *(QuantityValue left, ElectricConductivity right) { return new ElectricConductivity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricConductivity operator *(ElectricConductivity left, double right) + public static ElectricConductivity operator *(ElectricConductivity left, QuantityValue right) { return new ElectricConductivity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricConductivity operator /(ElectricConductivity left, double right) + public static ElectricConductivity operator /(ElectricConductivity left, QuantityValue right) { return new ElectricConductivity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricConductivity left, ElectricConductivity right) + public static QuantityValue operator /(ElectricConductivity left, ElectricConductivity right) { return left.SiemensPerMeter / right.SiemensPerMeter; } @@ -489,6 +492,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricConductivity left, ElectricConductivity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricConductivity left, ElectricConductivity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -501,7 +517,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricConductivity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricConductivity objElectricConductivity)) + return false; + return Equals(objElectricConductivity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricConductivity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -544,13 +582,13 @@ public int CompareTo(ElectricConductivity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricConductivity other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricConductivity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -561,7 +599,7 @@ public bool Equals(ElectricConductivity other, double tolerance, ComparisonType /// A hash code for the current ElectricConductivity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -572,17 +610,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricConductivityUnit unit) + public QuantityValue As(ElectricConductivityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -597,12 +634,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricConductivityUnit unitAsElectricConductivityUnit)) + if (!(unit is ElectricConductivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductivityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricConductivityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -634,7 +671,7 @@ public ElectricConductivity ToUnit(ElectricConductivityUnit unit, UnitConverter var converted = conversionFunction(this); return (ElectricConductivity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricConductivityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -642,17 +679,17 @@ public ElectricConductivity ToUnit(ElectricConductivityUnit unit, UnitConverter } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricConductivityUnit unitAsElectricConductivityUnit)) + if (!(unit is ElectricConductivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductivityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricConductivityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -679,10 +716,10 @@ public ElectricConductivity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricConductivityUnit unit) + private QuantityValue GetValueAs(ElectricConductivityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs index 0485881539..a370f87e7e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma. /// [DataContract] - public partial struct ElectricCurrent : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricCurrent : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -79,9 +79,9 @@ static ElectricCurrent() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricCurrent(double value, ElectricCurrentUnit unit) + public ElectricCurrent(QuantityValue value, ElectricCurrentUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -93,14 +93,14 @@ public ElectricCurrent(double value, ElectricCurrentUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricCurrent(double value, UnitSystem unitSystem) + public ElectricCurrent(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -141,7 +141,10 @@ public ElectricCurrent(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -164,44 +167,44 @@ public ElectricCurrent(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Amperes => As(ElectricCurrentUnit.Ampere); + public QuantityValue Amperes => As(ElectricCurrentUnit.Ampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Centiamperes => As(ElectricCurrentUnit.Centiampere); + public QuantityValue Centiamperes => As(ElectricCurrentUnit.Centiampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kiloamperes => As(ElectricCurrentUnit.Kiloampere); + public QuantityValue Kiloamperes => As(ElectricCurrentUnit.Kiloampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megaamperes => As(ElectricCurrentUnit.Megaampere); + public QuantityValue Megaamperes => As(ElectricCurrentUnit.Megaampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microamperes => As(ElectricCurrentUnit.Microampere); + public QuantityValue Microamperes => As(ElectricCurrentUnit.Microampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milliamperes => As(ElectricCurrentUnit.Milliampere); + public QuantityValue Milliamperes => As(ElectricCurrentUnit.Milliampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanoamperes => As(ElectricCurrentUnit.Nanoampere); + public QuantityValue Nanoamperes => As(ElectricCurrentUnit.Nanoampere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Picoamperes => As(ElectricCurrentUnit.Picoampere); + public QuantityValue Picoamperes => As(ElectricCurrentUnit.Picoampere); #endregion @@ -278,7 +281,7 @@ public static string GetAbbreviation(ElectricCurrentUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static ElectricCurrent FromAmperes(QuantityValue amperes) { - double value = (double) amperes; + QuantityValue value = (QuantityValue) amperes; return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); } @@ -288,7 +291,7 @@ public static ElectricCurrent FromAmperes(QuantityValue amperes) /// If value is NaN or Infinity. public static ElectricCurrent FromCentiamperes(QuantityValue centiamperes) { - double value = (double) centiamperes; + QuantityValue value = (QuantityValue) centiamperes; return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); } @@ -298,7 +301,7 @@ public static ElectricCurrent FromCentiamperes(QuantityValue centiamperes) /// If value is NaN or Infinity. public static ElectricCurrent FromKiloamperes(QuantityValue kiloamperes) { - double value = (double) kiloamperes; + QuantityValue value = (QuantityValue) kiloamperes; return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); } @@ -308,7 +311,7 @@ public static ElectricCurrent FromKiloamperes(QuantityValue kiloamperes) /// If value is NaN or Infinity. public static ElectricCurrent FromMegaamperes(QuantityValue megaamperes) { - double value = (double) megaamperes; + QuantityValue value = (QuantityValue) megaamperes; return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); } @@ -318,7 +321,7 @@ public static ElectricCurrent FromMegaamperes(QuantityValue megaamperes) /// If value is NaN or Infinity. public static ElectricCurrent FromMicroamperes(QuantityValue microamperes) { - double value = (double) microamperes; + QuantityValue value = (QuantityValue) microamperes; return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); } @@ -328,7 +331,7 @@ public static ElectricCurrent FromMicroamperes(QuantityValue microamperes) /// If value is NaN or Infinity. public static ElectricCurrent FromMilliamperes(QuantityValue milliamperes) { - double value = (double) milliamperes; + QuantityValue value = (QuantityValue) milliamperes; return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); } @@ -338,7 +341,7 @@ public static ElectricCurrent FromMilliamperes(QuantityValue milliamperes) /// If value is NaN or Infinity. public static ElectricCurrent FromNanoamperes(QuantityValue nanoamperes) { - double value = (double) nanoamperes; + QuantityValue value = (QuantityValue) nanoamperes; return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); } @@ -348,7 +351,7 @@ public static ElectricCurrent FromNanoamperes(QuantityValue nanoamperes) /// If value is NaN or Infinity. public static ElectricCurrent FromPicoamperes(QuantityValue picoamperes) { - double value = (double) picoamperes; + QuantityValue value = (QuantityValue) picoamperes; return new ElectricCurrent(value, ElectricCurrentUnit.Picoampere); } @@ -360,7 +363,7 @@ public static ElectricCurrent FromPicoamperes(QuantityValue picoamperes) /// ElectricCurrent unit value. public static ElectricCurrent From(QuantityValue value, ElectricCurrentUnit fromUnit) { - return new ElectricCurrent((double)value, fromUnit); + return new ElectricCurrent((QuantityValue)value, fromUnit); } #endregion @@ -530,25 +533,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricCurrent operator *(double left, ElectricCurrent right) + public static ElectricCurrent operator *(QuantityValue left, ElectricCurrent right) { return new ElectricCurrent(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricCurrent operator *(ElectricCurrent left, double right) + public static ElectricCurrent operator *(ElectricCurrent left, QuantityValue right) { return new ElectricCurrent(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricCurrent operator /(ElectricCurrent left, double right) + public static ElectricCurrent operator /(ElectricCurrent left, QuantityValue right) { return new ElectricCurrent(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricCurrent left, ElectricCurrent right) + public static QuantityValue operator /(ElectricCurrent left, ElectricCurrent right) { return left.Amperes / right.Amperes; } @@ -581,6 +584,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricCurrent left, ElectricCurrent right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricCurrent left, ElectricCurrent right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -593,7 +609,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricCurrent other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricCurrent objElectricCurrent)) + return false; + return Equals(objElectricCurrent); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricCurrent other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -636,13 +674,13 @@ public int CompareTo(ElectricCurrent other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCurrent other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricCurrent other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -653,7 +691,7 @@ public bool Equals(ElectricCurrent other, double tolerance, ComparisonType compa /// A hash code for the current ElectricCurrent. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -664,17 +702,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricCurrentUnit unit) + public QuantityValue As(ElectricCurrentUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -689,12 +726,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricCurrentUnit unitAsElectricCurrentUnit)) + if (!(unit is ElectricCurrentUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentUnit)} is supported.", nameof(unit)); - return As(unitAsElectricCurrentUnit); + return (QuantityValue)As(typedUnit); } /// @@ -726,7 +763,7 @@ public ElectricCurrent ToUnit(ElectricCurrentUnit unit, UnitConverter unitConver var converted = conversionFunction(this); return (ElectricCurrent)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricCurrentUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -734,17 +771,17 @@ public ElectricCurrent ToUnit(ElectricCurrentUnit unit, UnitConverter unitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricCurrentUnit unitAsElectricCurrentUnit)) + if (!(unit is ElectricCurrentUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricCurrentUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -771,10 +808,10 @@ public ElectricCurrent ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricCurrentUnit unit) + private QuantityValue GetValueAs(ElectricCurrentUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs index 8a8989cb79..52214a6462 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Current_density /// [DataContract] - public partial struct ElectricCurrentDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricCurrentDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -77,9 +77,9 @@ static ElectricCurrentDensity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricCurrentDensity(double value, ElectricCurrentDensityUnit unit) + public ElectricCurrentDensity(QuantityValue value, ElectricCurrentDensityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -91,14 +91,14 @@ public ElectricCurrentDensity(double value, ElectricCurrentDensityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricCurrentDensity(double value, UnitSystem unitSystem) + public ElectricCurrentDensity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -139,7 +139,10 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -162,19 +165,19 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AmperesPerSquareFoot => As(ElectricCurrentDensityUnit.AmperePerSquareFoot); + public QuantityValue AmperesPerSquareFoot => As(ElectricCurrentDensityUnit.AmperePerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AmperesPerSquareInch => As(ElectricCurrentDensityUnit.AmperePerSquareInch); + public QuantityValue AmperesPerSquareInch => As(ElectricCurrentDensityUnit.AmperePerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); + public QuantityValue AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); #endregion @@ -236,7 +239,7 @@ public static string GetAbbreviation(ElectricCurrentDensityUnit unit, IFormatPro /// If value is NaN or Infinity. public static ElectricCurrentDensity FromAmperesPerSquareFoot(QuantityValue amperespersquarefoot) { - double value = (double) amperespersquarefoot; + QuantityValue value = (QuantityValue) amperespersquarefoot; return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareFoot); } @@ -246,7 +249,7 @@ public static ElectricCurrentDensity FromAmperesPerSquareFoot(QuantityValue ampe /// If value is NaN or Infinity. public static ElectricCurrentDensity FromAmperesPerSquareInch(QuantityValue amperespersquareinch) { - double value = (double) amperespersquareinch; + QuantityValue value = (QuantityValue) amperespersquareinch; return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareInch); } @@ -256,7 +259,7 @@ public static ElectricCurrentDensity FromAmperesPerSquareInch(QuantityValue ampe /// If value is NaN or Infinity. public static ElectricCurrentDensity FromAmperesPerSquareMeter(QuantityValue amperespersquaremeter) { - double value = (double) amperespersquaremeter; + QuantityValue value = (QuantityValue) amperespersquaremeter; return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareMeter); } @@ -268,7 +271,7 @@ public static ElectricCurrentDensity FromAmperesPerSquareMeter(QuantityValue amp /// ElectricCurrentDensity unit value. public static ElectricCurrentDensity From(QuantityValue value, ElectricCurrentDensityUnit fromUnit) { - return new ElectricCurrentDensity((double)value, fromUnit); + return new ElectricCurrentDensity((QuantityValue)value, fromUnit); } #endregion @@ -438,25 +441,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricCurrentDensity operator *(double left, ElectricCurrentDensity right) + public static ElectricCurrentDensity operator *(QuantityValue left, ElectricCurrentDensity right) { return new ElectricCurrentDensity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricCurrentDensity operator *(ElectricCurrentDensity left, double right) + public static ElectricCurrentDensity operator *(ElectricCurrentDensity left, QuantityValue right) { return new ElectricCurrentDensity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricCurrentDensity operator /(ElectricCurrentDensity left, double right) + public static ElectricCurrentDensity operator /(ElectricCurrentDensity left, QuantityValue right) { return new ElectricCurrentDensity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricCurrentDensity left, ElectricCurrentDensity right) + public static QuantityValue operator /(ElectricCurrentDensity left, ElectricCurrentDensity right) { return left.AmperesPerSquareMeter / right.AmperesPerSquareMeter; } @@ -489,6 +492,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -501,7 +517,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricCurrentDensity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricCurrentDensity objElectricCurrentDensity)) + return false; + return Equals(objElectricCurrentDensity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricCurrentDensity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -544,13 +582,13 @@ public int CompareTo(ElectricCurrentDensity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCurrentDensity other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricCurrentDensity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -561,7 +599,7 @@ public bool Equals(ElectricCurrentDensity other, double tolerance, ComparisonTyp /// A hash code for the current ElectricCurrentDensity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -572,17 +610,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricCurrentDensityUnit unit) + public QuantityValue As(ElectricCurrentDensityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -597,12 +634,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricCurrentDensityUnit unitAsElectricCurrentDensityUnit)) + if (!(unit is ElectricCurrentDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentDensityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricCurrentDensityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -634,7 +671,7 @@ public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit, UnitConver var converted = conversionFunction(this); return (ElectricCurrentDensity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricCurrentDensityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -642,17 +679,17 @@ public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit, UnitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricCurrentDensityUnit unitAsElectricCurrentDensityUnit)) + if (!(unit is ElectricCurrentDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricCurrentDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -679,10 +716,10 @@ public ElectricCurrentDensity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricCurrentDensityUnit unit) + private QuantityValue GetValueAs(ElectricCurrentDensityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs index c5b8587e27..7f2103c3e8 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In electromagnetism, the current gradient describes how the current changes in time. /// [DataContract] - public partial struct ElectricCurrentGradient : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricCurrentGradient : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static ElectricCurrentGradient() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricCurrentGradient(double value, ElectricCurrentGradientUnit unit) + public ElectricCurrentGradient(QuantityValue value, ElectricCurrentGradientUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public ElectricCurrentGradient(double value, ElectricCurrentGradientUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricCurrentGradient(double value, UnitSystem unitSystem) + public ElectricCurrentGradient(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,24 +163,24 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AmperesPerMicrosecond => As(ElectricCurrentGradientUnit.AmperePerMicrosecond); + public QuantityValue AmperesPerMicrosecond => As(ElectricCurrentGradientUnit.AmperePerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AmperesPerMillisecond => As(ElectricCurrentGradientUnit.AmperePerMillisecond); + public QuantityValue AmperesPerMillisecond => As(ElectricCurrentGradientUnit.AmperePerMillisecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AmperesPerNanosecond => As(ElectricCurrentGradientUnit.AmperePerNanosecond); + public QuantityValue AmperesPerNanosecond => As(ElectricCurrentGradientUnit.AmperePerNanosecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); + public QuantityValue AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); #endregion @@ -242,7 +245,7 @@ public static string GetAbbreviation(ElectricCurrentGradientUnit unit, IFormatPr /// If value is NaN or Infinity. public static ElectricCurrentGradient FromAmperesPerMicrosecond(QuantityValue amperespermicrosecond) { - double value = (double) amperespermicrosecond; + QuantityValue value = (QuantityValue) amperespermicrosecond; return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerMicrosecond); } @@ -252,7 +255,7 @@ public static ElectricCurrentGradient FromAmperesPerMicrosecond(QuantityValue am /// If value is NaN or Infinity. public static ElectricCurrentGradient FromAmperesPerMillisecond(QuantityValue amperespermillisecond) { - double value = (double) amperespermillisecond; + QuantityValue value = (QuantityValue) amperespermillisecond; return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerMillisecond); } @@ -262,7 +265,7 @@ public static ElectricCurrentGradient FromAmperesPerMillisecond(QuantityValue am /// If value is NaN or Infinity. public static ElectricCurrentGradient FromAmperesPerNanosecond(QuantityValue amperespernanosecond) { - double value = (double) amperespernanosecond; + QuantityValue value = (QuantityValue) amperespernanosecond; return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerNanosecond); } @@ -272,7 +275,7 @@ public static ElectricCurrentGradient FromAmperesPerNanosecond(QuantityValue amp /// If value is NaN or Infinity. public static ElectricCurrentGradient FromAmperesPerSecond(QuantityValue amperespersecond) { - double value = (double) amperespersecond; + QuantityValue value = (QuantityValue) amperespersecond; return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerSecond); } @@ -284,7 +287,7 @@ public static ElectricCurrentGradient FromAmperesPerSecond(QuantityValue amperes /// ElectricCurrentGradient unit value. public static ElectricCurrentGradient From(QuantityValue value, ElectricCurrentGradientUnit fromUnit) { - return new ElectricCurrentGradient((double)value, fromUnit); + return new ElectricCurrentGradient((QuantityValue)value, fromUnit); } #endregion @@ -454,25 +457,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricCurrentGradient operator *(double left, ElectricCurrentGradient right) + public static ElectricCurrentGradient operator *(QuantityValue left, ElectricCurrentGradient right) { return new ElectricCurrentGradient(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricCurrentGradient operator *(ElectricCurrentGradient left, double right) + public static ElectricCurrentGradient operator *(ElectricCurrentGradient left, QuantityValue right) { return new ElectricCurrentGradient(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricCurrentGradient operator /(ElectricCurrentGradient left, double right) + public static ElectricCurrentGradient operator /(ElectricCurrentGradient left, QuantityValue right) { return new ElectricCurrentGradient(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricCurrentGradient left, ElectricCurrentGradient right) + public static QuantityValue operator /(ElectricCurrentGradient left, ElectricCurrentGradient right) { return left.AmperesPerSecond / right.AmperesPerSecond; } @@ -505,6 +508,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -517,7 +533,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricCurrentGradient other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricCurrentGradient objElectricCurrentGradient)) + return false; + return Equals(objElectricCurrentGradient); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricCurrentGradient other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -560,13 +598,13 @@ public int CompareTo(ElectricCurrentGradient other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCurrentGradient other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricCurrentGradient other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -577,7 +615,7 @@ public bool Equals(ElectricCurrentGradient other, double tolerance, ComparisonTy /// A hash code for the current ElectricCurrentGradient. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -588,17 +626,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricCurrentGradientUnit unit) + public QuantityValue As(ElectricCurrentGradientUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -613,12 +650,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricCurrentGradientUnit unitAsElectricCurrentGradientUnit)) + if (!(unit is ElectricCurrentGradientUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentGradientUnit)} is supported.", nameof(unit)); - return As(unitAsElectricCurrentGradientUnit); + return (QuantityValue)As(typedUnit); } /// @@ -650,7 +687,7 @@ public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit, UnitConv var converted = conversionFunction(this); return (ElectricCurrentGradient)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricCurrentGradientUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -658,17 +695,17 @@ public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit, UnitConv } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricCurrentGradientUnit unitAsElectricCurrentGradientUnit)) + if (!(unit is ElectricCurrentGradientUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentGradientUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricCurrentGradientUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -695,10 +732,10 @@ public ElectricCurrentGradient ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricCurrentGradientUnit unit) + private QuantityValue GetValueAs(ElectricCurrentGradientUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs index d49e4be72a..29e68a9570 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electric_field /// [DataContract] - public partial struct ElectricField : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricField : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static ElectricField() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricField(double value, ElectricFieldUnit unit) + public ElectricField(QuantityValue value, ElectricFieldUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public ElectricField(double value, ElectricFieldUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricField(double value, UnitSystem unitSystem) + public ElectricField(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public ElectricField(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public ElectricField(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); + public QuantityValue VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(ElectricFieldUnit unit, IFormatProvider? pr /// If value is NaN or Infinity. public static ElectricField FromVoltsPerMeter(QuantityValue voltspermeter) { - double value = (double) voltspermeter; + QuantityValue value = (QuantityValue) voltspermeter; return new ElectricField(value, ElectricFieldUnit.VoltPerMeter); } @@ -230,7 +233,7 @@ public static ElectricField FromVoltsPerMeter(QuantityValue voltspermeter) /// ElectricField unit value. public static ElectricField From(QuantityValue value, ElectricFieldUnit fromUnit) { - return new ElectricField((double)value, fromUnit); + return new ElectricField((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricField operator *(double left, ElectricField right) + public static ElectricField operator *(QuantityValue left, ElectricField right) { return new ElectricField(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricField operator *(ElectricField left, double right) + public static ElectricField operator *(ElectricField left, QuantityValue right) { return new ElectricField(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricField operator /(ElectricField left, double right) + public static ElectricField operator /(ElectricField left, QuantityValue right) { return new ElectricField(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricField left, ElectricField right) + public static QuantityValue operator /(ElectricField left, ElectricField right) { return left.VoltsPerMeter / right.VoltsPerMeter; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricField left, ElectricField right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricField left, ElectricField right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricField other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricField objElectricField)) + return false; + return Equals(objElectricField); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricField other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(ElectricField other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricField other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricField other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(ElectricField other, double tolerance, ComparisonType compari /// A hash code for the current ElectricField. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricFieldUnit unit) + public QuantityValue As(ElectricFieldUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricFieldUnit unitAsElectricFieldUnit)) + if (!(unit is ElectricFieldUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricFieldUnit)} is supported.", nameof(unit)); - return As(unitAsElectricFieldUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public ElectricField ToUnit(ElectricFieldUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (ElectricField)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricFieldUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public ElectricField ToUnit(ElectricFieldUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricFieldUnit unitAsElectricFieldUnit)) + if (!(unit is ElectricFieldUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricFieldUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricFieldUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public ElectricField ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricFieldUnit unit) + private QuantityValue GetValueAs(ElectricFieldUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs index fb2435cdce..82eabf7fac 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Inductance /// [DataContract] - public partial struct ElectricInductance : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricInductance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -78,9 +78,9 @@ static ElectricInductance() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricInductance(double value, ElectricInductanceUnit unit) + public ElectricInductance(QuantityValue value, ElectricInductanceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -92,14 +92,14 @@ public ElectricInductance(double value, ElectricInductanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricInductance(double value, UnitSystem unitSystem) + public ElectricInductance(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -140,7 +140,10 @@ public ElectricInductance(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -163,24 +166,24 @@ public ElectricInductance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Henries => As(ElectricInductanceUnit.Henry); + public QuantityValue Henries => As(ElectricInductanceUnit.Henry); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microhenries => As(ElectricInductanceUnit.Microhenry); + public QuantityValue Microhenries => As(ElectricInductanceUnit.Microhenry); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millihenries => As(ElectricInductanceUnit.Millihenry); + public QuantityValue Millihenries => As(ElectricInductanceUnit.Millihenry); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanohenries => As(ElectricInductanceUnit.Nanohenry); + public QuantityValue Nanohenries => As(ElectricInductanceUnit.Nanohenry); #endregion @@ -245,7 +248,7 @@ public static string GetAbbreviation(ElectricInductanceUnit unit, IFormatProvide /// If value is NaN or Infinity. public static ElectricInductance FromHenries(QuantityValue henries) { - double value = (double) henries; + QuantityValue value = (QuantityValue) henries; return new ElectricInductance(value, ElectricInductanceUnit.Henry); } @@ -255,7 +258,7 @@ public static ElectricInductance FromHenries(QuantityValue henries) /// If value is NaN or Infinity. public static ElectricInductance FromMicrohenries(QuantityValue microhenries) { - double value = (double) microhenries; + QuantityValue value = (QuantityValue) microhenries; return new ElectricInductance(value, ElectricInductanceUnit.Microhenry); } @@ -265,7 +268,7 @@ public static ElectricInductance FromMicrohenries(QuantityValue microhenries) /// If value is NaN or Infinity. public static ElectricInductance FromMillihenries(QuantityValue millihenries) { - double value = (double) millihenries; + QuantityValue value = (QuantityValue) millihenries; return new ElectricInductance(value, ElectricInductanceUnit.Millihenry); } @@ -275,7 +278,7 @@ public static ElectricInductance FromMillihenries(QuantityValue millihenries) /// If value is NaN or Infinity. public static ElectricInductance FromNanohenries(QuantityValue nanohenries) { - double value = (double) nanohenries; + QuantityValue value = (QuantityValue) nanohenries; return new ElectricInductance(value, ElectricInductanceUnit.Nanohenry); } @@ -287,7 +290,7 @@ public static ElectricInductance FromNanohenries(QuantityValue nanohenries) /// ElectricInductance unit value. public static ElectricInductance From(QuantityValue value, ElectricInductanceUnit fromUnit) { - return new ElectricInductance((double)value, fromUnit); + return new ElectricInductance((QuantityValue)value, fromUnit); } #endregion @@ -457,25 +460,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricInductance operator *(double left, ElectricInductance right) + public static ElectricInductance operator *(QuantityValue left, ElectricInductance right) { return new ElectricInductance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricInductance operator *(ElectricInductance left, double right) + public static ElectricInductance operator *(ElectricInductance left, QuantityValue right) { return new ElectricInductance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricInductance operator /(ElectricInductance left, double right) + public static ElectricInductance operator /(ElectricInductance left, QuantityValue right) { return new ElectricInductance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricInductance left, ElectricInductance right) + public static QuantityValue operator /(ElectricInductance left, ElectricInductance right) { return left.Henries / right.Henries; } @@ -508,6 +511,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricInductance left, ElectricInductance right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricInductance left, ElectricInductance right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -520,7 +536,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricInductance other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricInductance objElectricInductance)) + return false; + return Equals(objElectricInductance); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricInductance other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -563,13 +601,13 @@ public int CompareTo(ElectricInductance other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricInductance other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricInductance other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -580,7 +618,7 @@ public bool Equals(ElectricInductance other, double tolerance, ComparisonType co /// A hash code for the current ElectricInductance. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -591,17 +629,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricInductanceUnit unit) + public QuantityValue As(ElectricInductanceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -616,12 +653,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricInductanceUnit unitAsElectricInductanceUnit)) + if (!(unit is ElectricInductanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricInductanceUnit)} is supported.", nameof(unit)); - return As(unitAsElectricInductanceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -653,7 +690,7 @@ public ElectricInductance ToUnit(ElectricInductanceUnit unit, UnitConverter unit var converted = conversionFunction(this); return (ElectricInductance)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricInductanceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -661,17 +698,17 @@ public ElectricInductance ToUnit(ElectricInductanceUnit unit, UnitConverter unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricInductanceUnit unitAsElectricInductanceUnit)) + if (!(unit is ElectricInductanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricInductanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricInductanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -698,10 +735,10 @@ public ElectricInductance ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricInductanceUnit unit) + private QuantityValue GetValueAs(ElectricInductanceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs index 3c413afc86..f549a30e62 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point. /// [DataContract] - public partial struct ElectricPotential : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricPotential : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -76,9 +76,9 @@ static ElectricPotential() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricPotential(double value, ElectricPotentialUnit unit) + public ElectricPotential(QuantityValue value, ElectricPotentialUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -90,14 +90,14 @@ public ElectricPotential(double value, ElectricPotentialUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricPotential(double value, UnitSystem unitSystem) + public ElectricPotential(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -138,7 +138,10 @@ public ElectricPotential(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -161,29 +164,29 @@ public ElectricPotential(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilovolts => As(ElectricPotentialUnit.Kilovolt); + public QuantityValue Kilovolts => As(ElectricPotentialUnit.Kilovolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megavolts => As(ElectricPotentialUnit.Megavolt); + public QuantityValue Megavolts => As(ElectricPotentialUnit.Megavolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microvolts => As(ElectricPotentialUnit.Microvolt); + public QuantityValue Microvolts => As(ElectricPotentialUnit.Microvolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millivolts => As(ElectricPotentialUnit.Millivolt); + public QuantityValue Millivolts => As(ElectricPotentialUnit.Millivolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Volts => As(ElectricPotentialUnit.Volt); + public QuantityValue Volts => As(ElectricPotentialUnit.Volt); #endregion @@ -256,7 +259,7 @@ public static string GetAbbreviation(ElectricPotentialUnit unit, IFormatProvider /// If value is NaN or Infinity. public static ElectricPotential FromKilovolts(QuantityValue kilovolts) { - double value = (double) kilovolts; + QuantityValue value = (QuantityValue) kilovolts; return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); } @@ -266,7 +269,7 @@ public static ElectricPotential FromKilovolts(QuantityValue kilovolts) /// If value is NaN or Infinity. public static ElectricPotential FromMegavolts(QuantityValue megavolts) { - double value = (double) megavolts; + QuantityValue value = (QuantityValue) megavolts; return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); } @@ -276,7 +279,7 @@ public static ElectricPotential FromMegavolts(QuantityValue megavolts) /// If value is NaN or Infinity. public static ElectricPotential FromMicrovolts(QuantityValue microvolts) { - double value = (double) microvolts; + QuantityValue value = (QuantityValue) microvolts; return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); } @@ -286,7 +289,7 @@ public static ElectricPotential FromMicrovolts(QuantityValue microvolts) /// If value is NaN or Infinity. public static ElectricPotential FromMillivolts(QuantityValue millivolts) { - double value = (double) millivolts; + QuantityValue value = (QuantityValue) millivolts; return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); } @@ -296,7 +299,7 @@ public static ElectricPotential FromMillivolts(QuantityValue millivolts) /// If value is NaN or Infinity. public static ElectricPotential FromVolts(QuantityValue volts) { - double value = (double) volts; + QuantityValue value = (QuantityValue) volts; return new ElectricPotential(value, ElectricPotentialUnit.Volt); } @@ -308,7 +311,7 @@ public static ElectricPotential FromVolts(QuantityValue volts) /// ElectricPotential unit value. public static ElectricPotential From(QuantityValue value, ElectricPotentialUnit fromUnit) { - return new ElectricPotential((double)value, fromUnit); + return new ElectricPotential((QuantityValue)value, fromUnit); } #endregion @@ -478,25 +481,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricPotential operator *(double left, ElectricPotential right) + public static ElectricPotential operator *(QuantityValue left, ElectricPotential right) { return new ElectricPotential(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricPotential operator *(ElectricPotential left, double right) + public static ElectricPotential operator *(ElectricPotential left, QuantityValue right) { return new ElectricPotential(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricPotential operator /(ElectricPotential left, double right) + public static ElectricPotential operator /(ElectricPotential left, QuantityValue right) { return new ElectricPotential(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricPotential left, ElectricPotential right) + public static QuantityValue operator /(ElectricPotential left, ElectricPotential right) { return left.Volts / right.Volts; } @@ -529,6 +532,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricPotential left, ElectricPotential right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricPotential left, ElectricPotential right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -541,7 +557,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricPotential other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricPotential objElectricPotential)) + return false; + return Equals(objElectricPotential); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricPotential other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -584,13 +622,13 @@ public int CompareTo(ElectricPotential other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotential other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricPotential other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -601,7 +639,7 @@ public bool Equals(ElectricPotential other, double tolerance, ComparisonType com /// A hash code for the current ElectricPotential. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -612,17 +650,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricPotentialUnit unit) + public QuantityValue As(ElectricPotentialUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -637,12 +674,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricPotentialUnit unitAsElectricPotentialUnit)) + if (!(unit is ElectricPotentialUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialUnit)} is supported.", nameof(unit)); - return As(unitAsElectricPotentialUnit); + return (QuantityValue)As(typedUnit); } /// @@ -674,7 +711,7 @@ public ElectricPotential ToUnit(ElectricPotentialUnit unit, UnitConverter unitCo var converted = conversionFunction(this); return (ElectricPotential)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricPotentialUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -682,17 +719,17 @@ public ElectricPotential ToUnit(ElectricPotentialUnit unit, UnitConverter unitCo } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricPotentialUnit unitAsElectricPotentialUnit)) + if (!(unit is ElectricPotentialUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricPotentialUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -719,10 +756,10 @@ public ElectricPotential ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricPotentialUnit unit) + private QuantityValue GetValueAs(ElectricPotentialUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs index fa988ad89a..bea9b49b8a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The Electric Potential of a system known to use Alternating Current. /// [DataContract] - public partial struct ElectricPotentialAc : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricPotentialAc : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -76,9 +76,9 @@ static ElectricPotentialAc() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricPotentialAc(double value, ElectricPotentialAcUnit unit) + public ElectricPotentialAc(QuantityValue value, ElectricPotentialAcUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -90,14 +90,14 @@ public ElectricPotentialAc(double value, ElectricPotentialAcUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricPotentialAc(double value, UnitSystem unitSystem) + public ElectricPotentialAc(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -138,7 +138,10 @@ public ElectricPotentialAc(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -161,29 +164,29 @@ public ElectricPotentialAc(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc); + public QuantityValue KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc); + public QuantityValue MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc); + public QuantityValue MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc); + public QuantityValue MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltsAc => As(ElectricPotentialAcUnit.VoltAc); + public QuantityValue VoltsAc => As(ElectricPotentialAcUnit.VoltAc); #endregion @@ -251,7 +254,7 @@ public static string GetAbbreviation(ElectricPotentialAcUnit unit, IFormatProvid /// If value is NaN or Infinity. public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac) { - double value = (double) kilovoltsac; + QuantityValue value = (QuantityValue) kilovoltsac; return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); } @@ -261,7 +264,7 @@ public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac) /// If value is NaN or Infinity. public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac) { - double value = (double) megavoltsac; + QuantityValue value = (QuantityValue) megavoltsac; return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); } @@ -271,7 +274,7 @@ public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac) /// If value is NaN or Infinity. public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac) { - double value = (double) microvoltsac; + QuantityValue value = (QuantityValue) microvoltsac; return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); } @@ -281,7 +284,7 @@ public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac) /// If value is NaN or Infinity. public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac) { - double value = (double) millivoltsac; + QuantityValue value = (QuantityValue) millivoltsac; return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); } @@ -291,7 +294,7 @@ public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac) /// If value is NaN or Infinity. public static ElectricPotentialAc FromVoltsAc(QuantityValue voltsac) { - double value = (double) voltsac; + QuantityValue value = (QuantityValue) voltsac; return new ElectricPotentialAc(value, ElectricPotentialAcUnit.VoltAc); } @@ -303,7 +306,7 @@ public static ElectricPotentialAc FromVoltsAc(QuantityValue voltsac) /// ElectricPotentialAc unit value. public static ElectricPotentialAc From(QuantityValue value, ElectricPotentialAcUnit fromUnit) { - return new ElectricPotentialAc((double)value, fromUnit); + return new ElectricPotentialAc((QuantityValue)value, fromUnit); } #endregion @@ -473,25 +476,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricPotentialAc operator *(double left, ElectricPotentialAc right) + public static ElectricPotentialAc operator *(QuantityValue left, ElectricPotentialAc right) { return new ElectricPotentialAc(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricPotentialAc operator *(ElectricPotentialAc left, double right) + public static ElectricPotentialAc operator *(ElectricPotentialAc left, QuantityValue right) { return new ElectricPotentialAc(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricPotentialAc operator /(ElectricPotentialAc left, double right) + public static ElectricPotentialAc operator /(ElectricPotentialAc left, QuantityValue right) { return new ElectricPotentialAc(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricPotentialAc left, ElectricPotentialAc right) + public static QuantityValue operator /(ElectricPotentialAc left, ElectricPotentialAc right) { return left.VoltsAc / right.VoltsAc; } @@ -524,6 +527,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricPotentialAc left, ElectricPotentialAc right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -536,7 +552,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricPotentialAc other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricPotentialAc objElectricPotentialAc)) + return false; + return Equals(objElectricPotentialAc); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricPotentialAc other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -579,13 +617,13 @@ public int CompareTo(ElectricPotentialAc other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotentialAc other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricPotentialAc other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -596,7 +634,7 @@ public bool Equals(ElectricPotentialAc other, double tolerance, ComparisonType c /// A hash code for the current ElectricPotentialAc. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -607,17 +645,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricPotentialAcUnit unit) + public QuantityValue As(ElectricPotentialAcUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -632,12 +669,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricPotentialAcUnit unitAsElectricPotentialAcUnit)) + if (!(unit is ElectricPotentialAcUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialAcUnit)} is supported.", nameof(unit)); - return As(unitAsElectricPotentialAcUnit); + return (QuantityValue)As(typedUnit); } /// @@ -669,7 +706,7 @@ public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit, UnitConverter un var converted = conversionFunction(this); return (ElectricPotentialAc)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricPotentialAcUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -677,17 +714,17 @@ public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricPotentialAcUnit unitAsElectricPotentialAcUnit)) + if (!(unit is ElectricPotentialAcUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialAcUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricPotentialAcUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -714,10 +751,10 @@ public ElectricPotentialAc ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricPotentialAcUnit unit) + private QuantityValue GetValueAs(ElectricPotentialAcUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs index 9cc91d8d27..d35fd6041b 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// ElectricPotential change rate is the ratio of the electric potential change to the time during which the change occurred (value of electric potential changes per unit time). /// [DataContract] - public partial struct ElectricPotentialChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricPotentialChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -91,9 +91,9 @@ static ElectricPotentialChangeRate() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricPotentialChangeRate(double value, ElectricPotentialChangeRateUnit unit) + public ElectricPotentialChangeRate(QuantityValue value, ElectricPotentialChangeRateUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -105,14 +105,14 @@ public ElectricPotentialChangeRate(double value, ElectricPotentialChangeRateUnit /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) + public ElectricPotentialChangeRate(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -153,7 +153,10 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -176,104 +179,104 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilovoltsPerHours => As(ElectricPotentialChangeRateUnit.KilovoltPerHour); + public QuantityValue KilovoltsPerHours => As(ElectricPotentialChangeRateUnit.KilovoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilovoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); + public QuantityValue KilovoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilovoltsPerMinutes => As(ElectricPotentialChangeRateUnit.KilovoltPerMinute); + public QuantityValue KilovoltsPerMinutes => As(ElectricPotentialChangeRateUnit.KilovoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilovoltsPerSeconds => As(ElectricPotentialChangeRateUnit.KilovoltPerSecond); + public QuantityValue KilovoltsPerSeconds => As(ElectricPotentialChangeRateUnit.KilovoltPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegavoltsPerHours => As(ElectricPotentialChangeRateUnit.MegavoltPerHour); + public QuantityValue MegavoltsPerHours => As(ElectricPotentialChangeRateUnit.MegavoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegavoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); + public QuantityValue MegavoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegavoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MegavoltPerMinute); + public QuantityValue MegavoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MegavoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegavoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MegavoltPerSecond); + public QuantityValue MegavoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MegavoltPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrovoltsPerHours => As(ElectricPotentialChangeRateUnit.MicrovoltPerHour); + public QuantityValue MicrovoltsPerHours => As(ElectricPotentialChangeRateUnit.MicrovoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrovoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); + public QuantityValue MicrovoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrovoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MicrovoltPerMinute); + public QuantityValue MicrovoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MicrovoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrovoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MicrovoltPerSecond); + public QuantityValue MicrovoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MicrovoltPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillivoltsPerHours => As(ElectricPotentialChangeRateUnit.MillivoltPerHour); + public QuantityValue MillivoltsPerHours => As(ElectricPotentialChangeRateUnit.MillivoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillivoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); + public QuantityValue MillivoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillivoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MillivoltPerMinute); + public QuantityValue MillivoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MillivoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillivoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MillivoltPerSecond); + public QuantityValue MillivoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MillivoltPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltsPerHours => As(ElectricPotentialChangeRateUnit.VoltPerHour); + public QuantityValue VoltsPerHours => As(ElectricPotentialChangeRateUnit.VoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.VoltPerMicrosecond); + public QuantityValue VoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.VoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltsPerMinutes => As(ElectricPotentialChangeRateUnit.VoltPerMinute); + public QuantityValue VoltsPerMinutes => As(ElectricPotentialChangeRateUnit.VoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltsPerSeconds => As(ElectricPotentialChangeRateUnit.VoltPerSecond); + public QuantityValue VoltsPerSeconds => As(ElectricPotentialChangeRateUnit.VoltPerSecond); #endregion @@ -386,7 +389,7 @@ public static string GetAbbreviation(ElectricPotentialChangeRateUnit unit, IForm /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromKilovoltsPerHours(QuantityValue kilovoltsperhours) { - double value = (double) kilovoltsperhours; + QuantityValue value = (QuantityValue) kilovoltsperhours; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerHour); } @@ -396,7 +399,7 @@ public static ElectricPotentialChangeRate FromKilovoltsPerHours(QuantityValue ki /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromKilovoltsPerMicroseconds(QuantityValue kilovoltspermicroseconds) { - double value = (double) kilovoltspermicroseconds; + QuantityValue value = (QuantityValue) kilovoltspermicroseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); } @@ -406,7 +409,7 @@ public static ElectricPotentialChangeRate FromKilovoltsPerMicroseconds(QuantityV /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromKilovoltsPerMinutes(QuantityValue kilovoltsperminutes) { - double value = (double) kilovoltsperminutes; + QuantityValue value = (QuantityValue) kilovoltsperminutes; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerMinute); } @@ -416,7 +419,7 @@ public static ElectricPotentialChangeRate FromKilovoltsPerMinutes(QuantityValue /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromKilovoltsPerSeconds(QuantityValue kilovoltsperseconds) { - double value = (double) kilovoltsperseconds; + QuantityValue value = (QuantityValue) kilovoltsperseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerSecond); } @@ -426,7 +429,7 @@ public static ElectricPotentialChangeRate FromKilovoltsPerSeconds(QuantityValue /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMegavoltsPerHours(QuantityValue megavoltsperhours) { - double value = (double) megavoltsperhours; + QuantityValue value = (QuantityValue) megavoltsperhours; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerHour); } @@ -436,7 +439,7 @@ public static ElectricPotentialChangeRate FromMegavoltsPerHours(QuantityValue me /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMegavoltsPerMicroseconds(QuantityValue megavoltspermicroseconds) { - double value = (double) megavoltspermicroseconds; + QuantityValue value = (QuantityValue) megavoltspermicroseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); } @@ -446,7 +449,7 @@ public static ElectricPotentialChangeRate FromMegavoltsPerMicroseconds(QuantityV /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMegavoltsPerMinutes(QuantityValue megavoltsperminutes) { - double value = (double) megavoltsperminutes; + QuantityValue value = (QuantityValue) megavoltsperminutes; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerMinute); } @@ -456,7 +459,7 @@ public static ElectricPotentialChangeRate FromMegavoltsPerMinutes(QuantityValue /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMegavoltsPerSeconds(QuantityValue megavoltsperseconds) { - double value = (double) megavoltsperseconds; + QuantityValue value = (QuantityValue) megavoltsperseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerSecond); } @@ -466,7 +469,7 @@ public static ElectricPotentialChangeRate FromMegavoltsPerSeconds(QuantityValue /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMicrovoltsPerHours(QuantityValue microvoltsperhours) { - double value = (double) microvoltsperhours; + QuantityValue value = (QuantityValue) microvoltsperhours; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerHour); } @@ -476,7 +479,7 @@ public static ElectricPotentialChangeRate FromMicrovoltsPerHours(QuantityValue m /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMicrovoltsPerMicroseconds(QuantityValue microvoltspermicroseconds) { - double value = (double) microvoltspermicroseconds; + QuantityValue value = (QuantityValue) microvoltspermicroseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); } @@ -486,7 +489,7 @@ public static ElectricPotentialChangeRate FromMicrovoltsPerMicroseconds(Quantity /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMicrovoltsPerMinutes(QuantityValue microvoltsperminutes) { - double value = (double) microvoltsperminutes; + QuantityValue value = (QuantityValue) microvoltsperminutes; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerMinute); } @@ -496,7 +499,7 @@ public static ElectricPotentialChangeRate FromMicrovoltsPerMinutes(QuantityValue /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMicrovoltsPerSeconds(QuantityValue microvoltsperseconds) { - double value = (double) microvoltsperseconds; + QuantityValue value = (QuantityValue) microvoltsperseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerSecond); } @@ -506,7 +509,7 @@ public static ElectricPotentialChangeRate FromMicrovoltsPerSeconds(QuantityValue /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMillivoltsPerHours(QuantityValue millivoltsperhours) { - double value = (double) millivoltsperhours; + QuantityValue value = (QuantityValue) millivoltsperhours; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerHour); } @@ -516,7 +519,7 @@ public static ElectricPotentialChangeRate FromMillivoltsPerHours(QuantityValue m /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMillivoltsPerMicroseconds(QuantityValue millivoltspermicroseconds) { - double value = (double) millivoltspermicroseconds; + QuantityValue value = (QuantityValue) millivoltspermicroseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); } @@ -526,7 +529,7 @@ public static ElectricPotentialChangeRate FromMillivoltsPerMicroseconds(Quantity /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMillivoltsPerMinutes(QuantityValue millivoltsperminutes) { - double value = (double) millivoltsperminutes; + QuantityValue value = (QuantityValue) millivoltsperminutes; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerMinute); } @@ -536,7 +539,7 @@ public static ElectricPotentialChangeRate FromMillivoltsPerMinutes(QuantityValue /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromMillivoltsPerSeconds(QuantityValue millivoltsperseconds) { - double value = (double) millivoltsperseconds; + QuantityValue value = (QuantityValue) millivoltsperseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerSecond); } @@ -546,7 +549,7 @@ public static ElectricPotentialChangeRate FromMillivoltsPerSeconds(QuantityValue /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromVoltsPerHours(QuantityValue voltsperhours) { - double value = (double) voltsperhours; + QuantityValue value = (QuantityValue) voltsperhours; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerHour); } @@ -556,7 +559,7 @@ public static ElectricPotentialChangeRate FromVoltsPerHours(QuantityValue voltsp /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromVoltsPerMicroseconds(QuantityValue voltspermicroseconds) { - double value = (double) voltspermicroseconds; + QuantityValue value = (QuantityValue) voltspermicroseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerMicrosecond); } @@ -566,7 +569,7 @@ public static ElectricPotentialChangeRate FromVoltsPerMicroseconds(QuantityValue /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromVoltsPerMinutes(QuantityValue voltsperminutes) { - double value = (double) voltsperminutes; + QuantityValue value = (QuantityValue) voltsperminutes; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerMinute); } @@ -576,7 +579,7 @@ public static ElectricPotentialChangeRate FromVoltsPerMinutes(QuantityValue volt /// If value is NaN or Infinity. public static ElectricPotentialChangeRate FromVoltsPerSeconds(QuantityValue voltsperseconds) { - double value = (double) voltsperseconds; + QuantityValue value = (QuantityValue) voltsperseconds; return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerSecond); } @@ -588,7 +591,7 @@ public static ElectricPotentialChangeRate FromVoltsPerSeconds(QuantityValue volt /// ElectricPotentialChangeRate unit value. public static ElectricPotentialChangeRate From(QuantityValue value, ElectricPotentialChangeRateUnit fromUnit) { - return new ElectricPotentialChangeRate((double)value, fromUnit); + return new ElectricPotentialChangeRate((QuantityValue)value, fromUnit); } #endregion @@ -758,25 +761,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricPotentialChangeRate operator *(double left, ElectricPotentialChangeRate right) + public static ElectricPotentialChangeRate operator *(QuantityValue left, ElectricPotentialChangeRate right) { return new ElectricPotentialChangeRate(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricPotentialChangeRate operator *(ElectricPotentialChangeRate left, double right) + public static ElectricPotentialChangeRate operator *(ElectricPotentialChangeRate left, QuantityValue right) { return new ElectricPotentialChangeRate(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricPotentialChangeRate operator /(ElectricPotentialChangeRate left, double right) + public static ElectricPotentialChangeRate operator /(ElectricPotentialChangeRate left, QuantityValue right) { return new ElectricPotentialChangeRate(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + public static QuantityValue operator /(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) { return left.VoltsPerSeconds / right.VoltsPerSeconds; } @@ -809,6 +812,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -821,7 +837,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricPotentialChangeRate other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricPotentialChangeRate objElectricPotentialChangeRate)) + return false; + return Equals(objElectricPotentialChangeRate); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricPotentialChangeRate other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -864,13 +902,13 @@ public int CompareTo(ElectricPotentialChangeRate other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotentialChangeRate other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricPotentialChangeRate other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -881,7 +919,7 @@ public bool Equals(ElectricPotentialChangeRate other, double tolerance, Comparis /// A hash code for the current ElectricPotentialChangeRate. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -892,17 +930,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricPotentialChangeRateUnit unit) + public QuantityValue As(ElectricPotentialChangeRateUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -917,12 +954,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricPotentialChangeRateUnit unitAsElectricPotentialChangeRateUnit)) + if (!(unit is ElectricPotentialChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsElectricPotentialChangeRateUnit); + return (QuantityValue)As(typedUnit); } /// @@ -954,7 +991,7 @@ public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit, var converted = conversionFunction(this); return (ElectricPotentialChangeRate)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricPotentialChangeRateUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -962,17 +999,17 @@ public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit, } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricPotentialChangeRateUnit unitAsElectricPotentialChangeRateUnit)) + if (!(unit is ElectricPotentialChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricPotentialChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -999,10 +1036,10 @@ public ElectricPotentialChangeRate ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricPotentialChangeRateUnit unit) + private QuantityValue GetValueAs(ElectricPotentialChangeRateUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs index 787d8e5f5e..5f73469a2c 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The Electric Potential of a system known to use Direct Current. /// [DataContract] - public partial struct ElectricPotentialDc : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricPotentialDc : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -76,9 +76,9 @@ static ElectricPotentialDc() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricPotentialDc(double value, ElectricPotentialDcUnit unit) + public ElectricPotentialDc(QuantityValue value, ElectricPotentialDcUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -90,14 +90,14 @@ public ElectricPotentialDc(double value, ElectricPotentialDcUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricPotentialDc(double value, UnitSystem unitSystem) + public ElectricPotentialDc(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -138,7 +138,10 @@ public ElectricPotentialDc(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -161,29 +164,29 @@ public ElectricPotentialDc(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilovoltsDc => As(ElectricPotentialDcUnit.KilovoltDc); + public QuantityValue KilovoltsDc => As(ElectricPotentialDcUnit.KilovoltDc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegavoltsDc => As(ElectricPotentialDcUnit.MegavoltDc); + public QuantityValue MegavoltsDc => As(ElectricPotentialDcUnit.MegavoltDc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrovoltsDc => As(ElectricPotentialDcUnit.MicrovoltDc); + public QuantityValue MicrovoltsDc => As(ElectricPotentialDcUnit.MicrovoltDc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillivoltsDc => As(ElectricPotentialDcUnit.MillivoltDc); + public QuantityValue MillivoltsDc => As(ElectricPotentialDcUnit.MillivoltDc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltsDc => As(ElectricPotentialDcUnit.VoltDc); + public QuantityValue VoltsDc => As(ElectricPotentialDcUnit.VoltDc); #endregion @@ -251,7 +254,7 @@ public static string GetAbbreviation(ElectricPotentialDcUnit unit, IFormatProvid /// If value is NaN or Infinity. public static ElectricPotentialDc FromKilovoltsDc(QuantityValue kilovoltsdc) { - double value = (double) kilovoltsdc; + QuantityValue value = (QuantityValue) kilovoltsdc; return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); } @@ -261,7 +264,7 @@ public static ElectricPotentialDc FromKilovoltsDc(QuantityValue kilovoltsdc) /// If value is NaN or Infinity. public static ElectricPotentialDc FromMegavoltsDc(QuantityValue megavoltsdc) { - double value = (double) megavoltsdc; + QuantityValue value = (QuantityValue) megavoltsdc; return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); } @@ -271,7 +274,7 @@ public static ElectricPotentialDc FromMegavoltsDc(QuantityValue megavoltsdc) /// If value is NaN or Infinity. public static ElectricPotentialDc FromMicrovoltsDc(QuantityValue microvoltsdc) { - double value = (double) microvoltsdc; + QuantityValue value = (QuantityValue) microvoltsdc; return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); } @@ -281,7 +284,7 @@ public static ElectricPotentialDc FromMicrovoltsDc(QuantityValue microvoltsdc) /// If value is NaN or Infinity. public static ElectricPotentialDc FromMillivoltsDc(QuantityValue millivoltsdc) { - double value = (double) millivoltsdc; + QuantityValue value = (QuantityValue) millivoltsdc; return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); } @@ -291,7 +294,7 @@ public static ElectricPotentialDc FromMillivoltsDc(QuantityValue millivoltsdc) /// If value is NaN or Infinity. public static ElectricPotentialDc FromVoltsDc(QuantityValue voltsdc) { - double value = (double) voltsdc; + QuantityValue value = (QuantityValue) voltsdc; return new ElectricPotentialDc(value, ElectricPotentialDcUnit.VoltDc); } @@ -303,7 +306,7 @@ public static ElectricPotentialDc FromVoltsDc(QuantityValue voltsdc) /// ElectricPotentialDc unit value. public static ElectricPotentialDc From(QuantityValue value, ElectricPotentialDcUnit fromUnit) { - return new ElectricPotentialDc((double)value, fromUnit); + return new ElectricPotentialDc((QuantityValue)value, fromUnit); } #endregion @@ -473,25 +476,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricPotentialDc operator *(double left, ElectricPotentialDc right) + public static ElectricPotentialDc operator *(QuantityValue left, ElectricPotentialDc right) { return new ElectricPotentialDc(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricPotentialDc operator *(ElectricPotentialDc left, double right) + public static ElectricPotentialDc operator *(ElectricPotentialDc left, QuantityValue right) { return new ElectricPotentialDc(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricPotentialDc operator /(ElectricPotentialDc left, double right) + public static ElectricPotentialDc operator /(ElectricPotentialDc left, QuantityValue right) { return new ElectricPotentialDc(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricPotentialDc left, ElectricPotentialDc right) + public static QuantityValue operator /(ElectricPotentialDc left, ElectricPotentialDc right) { return left.VoltsDc / right.VoltsDc; } @@ -524,6 +527,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricPotentialDc left, ElectricPotentialDc right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -536,7 +552,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricPotentialDc other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricPotentialDc objElectricPotentialDc)) + return false; + return Equals(objElectricPotentialDc); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricPotentialDc other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -579,13 +617,13 @@ public int CompareTo(ElectricPotentialDc other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotentialDc other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricPotentialDc other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -596,7 +634,7 @@ public bool Equals(ElectricPotentialDc other, double tolerance, ComparisonType c /// A hash code for the current ElectricPotentialDc. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -607,17 +645,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricPotentialDcUnit unit) + public QuantityValue As(ElectricPotentialDcUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -632,12 +669,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricPotentialDcUnit unitAsElectricPotentialDcUnit)) + if (!(unit is ElectricPotentialDcUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialDcUnit)} is supported.", nameof(unit)); - return As(unitAsElectricPotentialDcUnit); + return (QuantityValue)As(typedUnit); } /// @@ -669,7 +706,7 @@ public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit, UnitConverter un var converted = conversionFunction(this); return (ElectricPotentialDc)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricPotentialDcUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -677,17 +714,17 @@ public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricPotentialDcUnit unitAsElectricPotentialDcUnit)) + if (!(unit is ElectricPotentialDcUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialDcUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricPotentialDcUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -714,10 +751,10 @@ public ElectricPotentialDc ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricPotentialDcUnit unit) + private QuantityValue GetValueAs(ElectricPotentialDcUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs index 29810c8529..a90307d171 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor. /// [DataContract] - public partial struct ElectricResistance : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricResistance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -77,9 +77,9 @@ static ElectricResistance() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricResistance(double value, ElectricResistanceUnit unit) + public ElectricResistance(QuantityValue value, ElectricResistanceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -91,14 +91,14 @@ public ElectricResistance(double value, ElectricResistanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricResistance(double value, UnitSystem unitSystem) + public ElectricResistance(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -139,7 +139,10 @@ public ElectricResistance(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -162,34 +165,34 @@ public ElectricResistance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gigaohms => As(ElectricResistanceUnit.Gigaohm); + public QuantityValue Gigaohms => As(ElectricResistanceUnit.Gigaohm); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kiloohms => As(ElectricResistanceUnit.Kiloohm); + public QuantityValue Kiloohms => As(ElectricResistanceUnit.Kiloohm); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megaohms => As(ElectricResistanceUnit.Megaohm); + public QuantityValue Megaohms => As(ElectricResistanceUnit.Megaohm); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microohms => As(ElectricResistanceUnit.Microohm); + public QuantityValue Microohms => As(ElectricResistanceUnit.Microohm); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milliohms => As(ElectricResistanceUnit.Milliohm); + public QuantityValue Milliohms => As(ElectricResistanceUnit.Milliohm); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Ohms => As(ElectricResistanceUnit.Ohm); + public QuantityValue Ohms => As(ElectricResistanceUnit.Ohm); #endregion @@ -260,7 +263,7 @@ public static string GetAbbreviation(ElectricResistanceUnit unit, IFormatProvide /// If value is NaN or Infinity. public static ElectricResistance FromGigaohms(QuantityValue gigaohms) { - double value = (double) gigaohms; + QuantityValue value = (QuantityValue) gigaohms; return new ElectricResistance(value, ElectricResistanceUnit.Gigaohm); } @@ -270,7 +273,7 @@ public static ElectricResistance FromGigaohms(QuantityValue gigaohms) /// If value is NaN or Infinity. public static ElectricResistance FromKiloohms(QuantityValue kiloohms) { - double value = (double) kiloohms; + QuantityValue value = (QuantityValue) kiloohms; return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); } @@ -280,7 +283,7 @@ public static ElectricResistance FromKiloohms(QuantityValue kiloohms) /// If value is NaN or Infinity. public static ElectricResistance FromMegaohms(QuantityValue megaohms) { - double value = (double) megaohms; + QuantityValue value = (QuantityValue) megaohms; return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); } @@ -290,7 +293,7 @@ public static ElectricResistance FromMegaohms(QuantityValue megaohms) /// If value is NaN or Infinity. public static ElectricResistance FromMicroohms(QuantityValue microohms) { - double value = (double) microohms; + QuantityValue value = (QuantityValue) microohms; return new ElectricResistance(value, ElectricResistanceUnit.Microohm); } @@ -300,7 +303,7 @@ public static ElectricResistance FromMicroohms(QuantityValue microohms) /// If value is NaN or Infinity. public static ElectricResistance FromMilliohms(QuantityValue milliohms) { - double value = (double) milliohms; + QuantityValue value = (QuantityValue) milliohms; return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); } @@ -310,7 +313,7 @@ public static ElectricResistance FromMilliohms(QuantityValue milliohms) /// If value is NaN or Infinity. public static ElectricResistance FromOhms(QuantityValue ohms) { - double value = (double) ohms; + QuantityValue value = (QuantityValue) ohms; return new ElectricResistance(value, ElectricResistanceUnit.Ohm); } @@ -322,7 +325,7 @@ public static ElectricResistance FromOhms(QuantityValue ohms) /// ElectricResistance unit value. public static ElectricResistance From(QuantityValue value, ElectricResistanceUnit fromUnit) { - return new ElectricResistance((double)value, fromUnit); + return new ElectricResistance((QuantityValue)value, fromUnit); } #endregion @@ -492,25 +495,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricResistance operator *(double left, ElectricResistance right) + public static ElectricResistance operator *(QuantityValue left, ElectricResistance right) { return new ElectricResistance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricResistance operator *(ElectricResistance left, double right) + public static ElectricResistance operator *(ElectricResistance left, QuantityValue right) { return new ElectricResistance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricResistance operator /(ElectricResistance left, double right) + public static ElectricResistance operator /(ElectricResistance left, QuantityValue right) { return new ElectricResistance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricResistance left, ElectricResistance right) + public static QuantityValue operator /(ElectricResistance left, ElectricResistance right) { return left.Ohms / right.Ohms; } @@ -543,6 +546,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricResistance left, ElectricResistance right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricResistance left, ElectricResistance right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -555,7 +571,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricResistance other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricResistance objElectricResistance)) + return false; + return Equals(objElectricResistance); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricResistance other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -598,13 +636,13 @@ public int CompareTo(ElectricResistance other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricResistance other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricResistance other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -615,7 +653,7 @@ public bool Equals(ElectricResistance other, double tolerance, ComparisonType co /// A hash code for the current ElectricResistance. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -626,17 +664,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricResistanceUnit unit) + public QuantityValue As(ElectricResistanceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -651,12 +688,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricResistanceUnit unitAsElectricResistanceUnit)) + if (!(unit is ElectricResistanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit)); - return As(unitAsElectricResistanceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -688,7 +725,7 @@ public ElectricResistance ToUnit(ElectricResistanceUnit unit, UnitConverter unit var converted = conversionFunction(this); return (ElectricResistance)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricResistanceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -696,17 +733,17 @@ public ElectricResistance ToUnit(ElectricResistanceUnit unit, UnitConverter unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricResistanceUnit unitAsElectricResistanceUnit)) + if (!(unit is ElectricResistanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricResistanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -733,10 +770,10 @@ public ElectricResistance ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricResistanceUnit unit) + private QuantityValue GetValueAs(ElectricResistanceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs index 9fa380d492..4fb77ebee4 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity /// [DataContract] - public partial struct ElectricResistivity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricResistivity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -88,9 +88,9 @@ static ElectricResistivity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricResistivity(double value, ElectricResistivityUnit unit) + public ElectricResistivity(QuantityValue value, ElectricResistivityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -102,14 +102,14 @@ public ElectricResistivity(double value, ElectricResistivityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricResistivity(double value, UnitSystem unitSystem) + public ElectricResistivity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -150,7 +150,10 @@ public ElectricResistivity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -173,74 +176,74 @@ public ElectricResistivity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KiloohmsCentimeter => As(ElectricResistivityUnit.KiloohmCentimeter); + public QuantityValue KiloohmsCentimeter => As(ElectricResistivityUnit.KiloohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KiloohmMeters => As(ElectricResistivityUnit.KiloohmMeter); + public QuantityValue KiloohmMeters => As(ElectricResistivityUnit.KiloohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegaohmsCentimeter => As(ElectricResistivityUnit.MegaohmCentimeter); + public QuantityValue MegaohmsCentimeter => As(ElectricResistivityUnit.MegaohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegaohmMeters => As(ElectricResistivityUnit.MegaohmMeter); + public QuantityValue MegaohmMeters => As(ElectricResistivityUnit.MegaohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicroohmsCentimeter => As(ElectricResistivityUnit.MicroohmCentimeter); + public QuantityValue MicroohmsCentimeter => As(ElectricResistivityUnit.MicroohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); + public QuantityValue MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliohmsCentimeter => As(ElectricResistivityUnit.MilliohmCentimeter); + public QuantityValue MilliohmsCentimeter => As(ElectricResistivityUnit.MilliohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); + public QuantityValue MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanoohmsCentimeter => As(ElectricResistivityUnit.NanoohmCentimeter); + public QuantityValue NanoohmsCentimeter => As(ElectricResistivityUnit.NanoohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); + public QuantityValue NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OhmsCentimeter => As(ElectricResistivityUnit.OhmCentimeter); + public QuantityValue OhmsCentimeter => As(ElectricResistivityUnit.OhmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OhmMeters => As(ElectricResistivityUnit.OhmMeter); + public QuantityValue OhmMeters => As(ElectricResistivityUnit.OhmMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicoohmsCentimeter => As(ElectricResistivityUnit.PicoohmCentimeter); + public QuantityValue PicoohmsCentimeter => As(ElectricResistivityUnit.PicoohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicoohmMeters => As(ElectricResistivityUnit.PicoohmMeter); + public QuantityValue PicoohmMeters => As(ElectricResistivityUnit.PicoohmMeter); #endregion @@ -335,7 +338,7 @@ public static string GetAbbreviation(ElectricResistivityUnit unit, IFormatProvid /// If value is NaN or Infinity. public static ElectricResistivity FromKiloohmsCentimeter(QuantityValue kiloohmscentimeter) { - double value = (double) kiloohmscentimeter; + QuantityValue value = (QuantityValue) kiloohmscentimeter; return new ElectricResistivity(value, ElectricResistivityUnit.KiloohmCentimeter); } @@ -345,7 +348,7 @@ public static ElectricResistivity FromKiloohmsCentimeter(QuantityValue kiloohmsc /// If value is NaN or Infinity. public static ElectricResistivity FromKiloohmMeters(QuantityValue kiloohmmeters) { - double value = (double) kiloohmmeters; + QuantityValue value = (QuantityValue) kiloohmmeters; return new ElectricResistivity(value, ElectricResistivityUnit.KiloohmMeter); } @@ -355,7 +358,7 @@ public static ElectricResistivity FromKiloohmMeters(QuantityValue kiloohmmeters) /// If value is NaN or Infinity. public static ElectricResistivity FromMegaohmsCentimeter(QuantityValue megaohmscentimeter) { - double value = (double) megaohmscentimeter; + QuantityValue value = (QuantityValue) megaohmscentimeter; return new ElectricResistivity(value, ElectricResistivityUnit.MegaohmCentimeter); } @@ -365,7 +368,7 @@ public static ElectricResistivity FromMegaohmsCentimeter(QuantityValue megaohmsc /// If value is NaN or Infinity. public static ElectricResistivity FromMegaohmMeters(QuantityValue megaohmmeters) { - double value = (double) megaohmmeters; + QuantityValue value = (QuantityValue) megaohmmeters; return new ElectricResistivity(value, ElectricResistivityUnit.MegaohmMeter); } @@ -375,7 +378,7 @@ public static ElectricResistivity FromMegaohmMeters(QuantityValue megaohmmeters) /// If value is NaN or Infinity. public static ElectricResistivity FromMicroohmsCentimeter(QuantityValue microohmscentimeter) { - double value = (double) microohmscentimeter; + QuantityValue value = (QuantityValue) microohmscentimeter; return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmCentimeter); } @@ -385,7 +388,7 @@ public static ElectricResistivity FromMicroohmsCentimeter(QuantityValue microohm /// If value is NaN or Infinity. public static ElectricResistivity FromMicroohmMeters(QuantityValue microohmmeters) { - double value = (double) microohmmeters; + QuantityValue value = (QuantityValue) microohmmeters; return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); } @@ -395,7 +398,7 @@ public static ElectricResistivity FromMicroohmMeters(QuantityValue microohmmeter /// If value is NaN or Infinity. public static ElectricResistivity FromMilliohmsCentimeter(QuantityValue milliohmscentimeter) { - double value = (double) milliohmscentimeter; + QuantityValue value = (QuantityValue) milliohmscentimeter; return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmCentimeter); } @@ -405,7 +408,7 @@ public static ElectricResistivity FromMilliohmsCentimeter(QuantityValue milliohm /// If value is NaN or Infinity. public static ElectricResistivity FromMilliohmMeters(QuantityValue milliohmmeters) { - double value = (double) milliohmmeters; + QuantityValue value = (QuantityValue) milliohmmeters; return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); } @@ -415,7 +418,7 @@ public static ElectricResistivity FromMilliohmMeters(QuantityValue milliohmmeter /// If value is NaN or Infinity. public static ElectricResistivity FromNanoohmsCentimeter(QuantityValue nanoohmscentimeter) { - double value = (double) nanoohmscentimeter; + QuantityValue value = (QuantityValue) nanoohmscentimeter; return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmCentimeter); } @@ -425,7 +428,7 @@ public static ElectricResistivity FromNanoohmsCentimeter(QuantityValue nanoohmsc /// If value is NaN or Infinity. public static ElectricResistivity FromNanoohmMeters(QuantityValue nanoohmmeters) { - double value = (double) nanoohmmeters; + QuantityValue value = (QuantityValue) nanoohmmeters; return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); } @@ -435,7 +438,7 @@ public static ElectricResistivity FromNanoohmMeters(QuantityValue nanoohmmeters) /// If value is NaN or Infinity. public static ElectricResistivity FromOhmsCentimeter(QuantityValue ohmscentimeter) { - double value = (double) ohmscentimeter; + QuantityValue value = (QuantityValue) ohmscentimeter; return new ElectricResistivity(value, ElectricResistivityUnit.OhmCentimeter); } @@ -445,7 +448,7 @@ public static ElectricResistivity FromOhmsCentimeter(QuantityValue ohmscentimete /// If value is NaN or Infinity. public static ElectricResistivity FromOhmMeters(QuantityValue ohmmeters) { - double value = (double) ohmmeters; + QuantityValue value = (QuantityValue) ohmmeters; return new ElectricResistivity(value, ElectricResistivityUnit.OhmMeter); } @@ -455,7 +458,7 @@ public static ElectricResistivity FromOhmMeters(QuantityValue ohmmeters) /// If value is NaN or Infinity. public static ElectricResistivity FromPicoohmsCentimeter(QuantityValue picoohmscentimeter) { - double value = (double) picoohmscentimeter; + QuantityValue value = (QuantityValue) picoohmscentimeter; return new ElectricResistivity(value, ElectricResistivityUnit.PicoohmCentimeter); } @@ -465,7 +468,7 @@ public static ElectricResistivity FromPicoohmsCentimeter(QuantityValue picoohmsc /// If value is NaN or Infinity. public static ElectricResistivity FromPicoohmMeters(QuantityValue picoohmmeters) { - double value = (double) picoohmmeters; + QuantityValue value = (QuantityValue) picoohmmeters; return new ElectricResistivity(value, ElectricResistivityUnit.PicoohmMeter); } @@ -477,7 +480,7 @@ public static ElectricResistivity FromPicoohmMeters(QuantityValue picoohmmeters) /// ElectricResistivity unit value. public static ElectricResistivity From(QuantityValue value, ElectricResistivityUnit fromUnit) { - return new ElectricResistivity((double)value, fromUnit); + return new ElectricResistivity((QuantityValue)value, fromUnit); } #endregion @@ -647,25 +650,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricResistivity operator *(double left, ElectricResistivity right) + public static ElectricResistivity operator *(QuantityValue left, ElectricResistivity right) { return new ElectricResistivity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricResistivity operator *(ElectricResistivity left, double right) + public static ElectricResistivity operator *(ElectricResistivity left, QuantityValue right) { return new ElectricResistivity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricResistivity operator /(ElectricResistivity left, double right) + public static ElectricResistivity operator /(ElectricResistivity left, QuantityValue right) { return new ElectricResistivity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricResistivity left, ElectricResistivity right) + public static QuantityValue operator /(ElectricResistivity left, ElectricResistivity right) { return left.OhmMeters / right.OhmMeters; } @@ -698,6 +701,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricResistivity left, ElectricResistivity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricResistivity left, ElectricResistivity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -710,7 +726,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricResistivity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricResistivity objElectricResistivity)) + return false; + return Equals(objElectricResistivity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricResistivity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -753,13 +791,13 @@ public int CompareTo(ElectricResistivity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricResistivity other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricResistivity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -770,7 +808,7 @@ public bool Equals(ElectricResistivity other, double tolerance, ComparisonType c /// A hash code for the current ElectricResistivity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -781,17 +819,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricResistivityUnit unit) + public QuantityValue As(ElectricResistivityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -806,12 +843,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricResistivityUnit unitAsElectricResistivityUnit)) + if (!(unit is ElectricResistivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistivityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricResistivityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -843,7 +880,7 @@ public ElectricResistivity ToUnit(ElectricResistivityUnit unit, UnitConverter un var converted = conversionFunction(this); return (ElectricResistivity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricResistivityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -851,17 +888,17 @@ public ElectricResistivity ToUnit(ElectricResistivityUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricResistivityUnit unitAsElectricResistivityUnit)) + if (!(unit is ElectricResistivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistivityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricResistivityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -888,10 +925,10 @@ public ElectricResistivity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricResistivityUnit unit) + private QuantityValue GetValueAs(ElectricResistivityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs index a5e94ca602..39a5166bad 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Charge_density /// [DataContract] - public partial struct ElectricSurfaceChargeDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ElectricSurfaceChargeDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -77,9 +77,9 @@ static ElectricSurfaceChargeDensity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ElectricSurfaceChargeDensity(double value, ElectricSurfaceChargeDensityUnit unit) + public ElectricSurfaceChargeDensity(QuantityValue value, ElectricSurfaceChargeDensityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -91,14 +91,14 @@ public ElectricSurfaceChargeDensity(double value, ElectricSurfaceChargeDensityUn /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) + public ElectricSurfaceChargeDensity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -139,7 +139,10 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -162,19 +165,19 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CoulombsPerSquareCentimeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); + public QuantityValue CoulombsPerSquareCentimeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CoulombsPerSquareInch => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); + public QuantityValue CoulombsPerSquareInch => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CoulombsPerSquareMeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); + public QuantityValue CoulombsPerSquareMeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); #endregion @@ -236,7 +239,7 @@ public static string GetAbbreviation(ElectricSurfaceChargeDensityUnit unit, IFor /// If value is NaN or Infinity. public static ElectricSurfaceChargeDensity FromCoulombsPerSquareCentimeter(QuantityValue coulombspersquarecentimeter) { - double value = (double) coulombspersquarecentimeter; + QuantityValue value = (QuantityValue) coulombspersquarecentimeter; return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); } @@ -246,7 +249,7 @@ public static ElectricSurfaceChargeDensity FromCoulombsPerSquareCentimeter(Quant /// If value is NaN or Infinity. public static ElectricSurfaceChargeDensity FromCoulombsPerSquareInch(QuantityValue coulombspersquareinch) { - double value = (double) coulombspersquareinch; + QuantityValue value = (QuantityValue) coulombspersquareinch; return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); } @@ -256,7 +259,7 @@ public static ElectricSurfaceChargeDensity FromCoulombsPerSquareInch(QuantityVal /// If value is NaN or Infinity. public static ElectricSurfaceChargeDensity FromCoulombsPerSquareMeter(QuantityValue coulombspersquaremeter) { - double value = (double) coulombspersquaremeter; + QuantityValue value = (QuantityValue) coulombspersquaremeter; return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); } @@ -268,7 +271,7 @@ public static ElectricSurfaceChargeDensity FromCoulombsPerSquareMeter(QuantityVa /// ElectricSurfaceChargeDensity unit value. public static ElectricSurfaceChargeDensity From(QuantityValue value, ElectricSurfaceChargeDensityUnit fromUnit) { - return new ElectricSurfaceChargeDensity((double)value, fromUnit); + return new ElectricSurfaceChargeDensity((QuantityValue)value, fromUnit); } #endregion @@ -438,25 +441,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect } /// Get from multiplying value and . - public static ElectricSurfaceChargeDensity operator *(double left, ElectricSurfaceChargeDensity right) + public static ElectricSurfaceChargeDensity operator *(QuantityValue left, ElectricSurfaceChargeDensity right) { return new ElectricSurfaceChargeDensity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricSurfaceChargeDensity operator *(ElectricSurfaceChargeDensity left, double right) + public static ElectricSurfaceChargeDensity operator *(ElectricSurfaceChargeDensity left, QuantityValue right) { return new ElectricSurfaceChargeDensity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricSurfaceChargeDensity operator /(ElectricSurfaceChargeDensity left, double right) + public static ElectricSurfaceChargeDensity operator /(ElectricSurfaceChargeDensity left, QuantityValue right) { return new ElectricSurfaceChargeDensity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + public static QuantityValue operator /(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) { return left.CoulombsPerSquareMeter / right.CoulombsPerSquareMeter; } @@ -489,6 +492,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -501,7 +517,29 @@ public int CompareTo(object obj) /// public int CompareTo(ElectricSurfaceChargeDensity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ElectricSurfaceChargeDensity objElectricSurfaceChargeDensity)) + return false; + return Equals(objElectricSurfaceChargeDensity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ElectricSurfaceChargeDensity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -544,13 +582,13 @@ public int CompareTo(ElectricSurfaceChargeDensity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricSurfaceChargeDensity other, double tolerance, ComparisonType comparisonType) + public bool Equals(ElectricSurfaceChargeDensity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -561,7 +599,7 @@ public bool Equals(ElectricSurfaceChargeDensity other, double tolerance, Compari /// A hash code for the current ElectricSurfaceChargeDensity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -572,17 +610,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ElectricSurfaceChargeDensityUnit unit) + public QuantityValue As(ElectricSurfaceChargeDensityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -597,12 +634,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ElectricSurfaceChargeDensityUnit unitAsElectricSurfaceChargeDensityUnit)) + if (!(unit is ElectricSurfaceChargeDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSurfaceChargeDensityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricSurfaceChargeDensityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -634,7 +671,7 @@ public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit var converted = conversionFunction(this); return (ElectricSurfaceChargeDensity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ElectricSurfaceChargeDensityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -642,17 +679,17 @@ public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricSurfaceChargeDensityUnit unitAsElectricSurfaceChargeDensityUnit)) + if (!(unit is ElectricSurfaceChargeDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSurfaceChargeDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsElectricSurfaceChargeDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -679,10 +716,10 @@ public ElectricSurfaceChargeDensity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ElectricSurfaceChargeDensityUnit unit) + private QuantityValue GetValueAs(ElectricSurfaceChargeDensityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs index d8d04ae1af..60e31f0113 100644 --- a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used. /// [DataContract] - public partial struct Energy : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Energy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -107,9 +107,9 @@ static Energy() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Energy(double value, EnergyUnit unit) + public Energy(QuantityValue value, EnergyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -121,14 +121,14 @@ public Energy(double value, EnergyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Energy(double value, UnitSystem unitSystem) + public Energy(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -169,7 +169,10 @@ public Energy(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -192,184 +195,184 @@ public Energy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); + public QuantityValue BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Calories => As(EnergyUnit.Calorie); + public QuantityValue Calories => As(EnergyUnit.Calorie); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecathermsEc => As(EnergyUnit.DecathermEc); + public QuantityValue DecathermsEc => As(EnergyUnit.DecathermEc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecathermsImperial => As(EnergyUnit.DecathermImperial); + public QuantityValue DecathermsImperial => As(EnergyUnit.DecathermImperial); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecathermsUs => As(EnergyUnit.DecathermUs); + public QuantityValue DecathermsUs => As(EnergyUnit.DecathermUs); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ElectronVolts => As(EnergyUnit.ElectronVolt); + public QuantityValue ElectronVolts => As(EnergyUnit.ElectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Ergs => As(EnergyUnit.Erg); + public QuantityValue Ergs => As(EnergyUnit.Erg); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FootPounds => As(EnergyUnit.FootPound); + public QuantityValue FootPounds => As(EnergyUnit.FootPound); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); + public QuantityValue GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigaelectronVolts => As(EnergyUnit.GigaelectronVolt); + public QuantityValue GigaelectronVolts => As(EnergyUnit.GigaelectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gigajoules => As(EnergyUnit.Gigajoule); + public QuantityValue Gigajoules => As(EnergyUnit.Gigajoule); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattDays => As(EnergyUnit.GigawattDay); + public QuantityValue GigawattDays => As(EnergyUnit.GigawattDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattHours => As(EnergyUnit.GigawattHour); + public QuantityValue GigawattHours => As(EnergyUnit.GigawattHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HorsepowerHours => As(EnergyUnit.HorsepowerHour); + public QuantityValue HorsepowerHours => As(EnergyUnit.HorsepowerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Joules => As(EnergyUnit.Joule); + public QuantityValue Joules => As(EnergyUnit.Joule); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); + public QuantityValue KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilocalories => As(EnergyUnit.Kilocalorie); + public QuantityValue Kilocalories => As(EnergyUnit.Kilocalorie); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KiloelectronVolts => As(EnergyUnit.KiloelectronVolt); + public QuantityValue KiloelectronVolts => As(EnergyUnit.KiloelectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilojoules => As(EnergyUnit.Kilojoule); + public QuantityValue Kilojoules => As(EnergyUnit.Kilojoule); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattDays => As(EnergyUnit.KilowattDay); + public QuantityValue KilowattDays => As(EnergyUnit.KilowattDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattHours => As(EnergyUnit.KilowattHour); + public QuantityValue KilowattHours => As(EnergyUnit.KilowattHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); + public QuantityValue MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megacalories => As(EnergyUnit.Megacalorie); + public QuantityValue Megacalories => As(EnergyUnit.Megacalorie); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegaelectronVolts => As(EnergyUnit.MegaelectronVolt); + public QuantityValue MegaelectronVolts => As(EnergyUnit.MegaelectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megajoules => As(EnergyUnit.Megajoule); + public QuantityValue Megajoules => As(EnergyUnit.Megajoule); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattDays => As(EnergyUnit.MegawattDay); + public QuantityValue MegawattDays => As(EnergyUnit.MegawattDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattHours => As(EnergyUnit.MegawattHour); + public QuantityValue MegawattHours => As(EnergyUnit.MegawattHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millijoules => As(EnergyUnit.Millijoule); + public QuantityValue Millijoules => As(EnergyUnit.Millijoule); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TeraelectronVolts => As(EnergyUnit.TeraelectronVolt); + public QuantityValue TeraelectronVolts => As(EnergyUnit.TeraelectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerawattDays => As(EnergyUnit.TerawattDay); + public QuantityValue TerawattDays => As(EnergyUnit.TerawattDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerawattHours => As(EnergyUnit.TerawattHour); + public QuantityValue TerawattHours => As(EnergyUnit.TerawattHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ThermsEc => As(EnergyUnit.ThermEc); + public QuantityValue ThermsEc => As(EnergyUnit.ThermEc); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ThermsImperial => As(EnergyUnit.ThermImperial); + public QuantityValue ThermsImperial => As(EnergyUnit.ThermImperial); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ThermsUs => As(EnergyUnit.ThermUs); + public QuantityValue ThermsUs => As(EnergyUnit.ThermUs); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattDays => As(EnergyUnit.WattDay); + public QuantityValue WattDays => As(EnergyUnit.WattDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattHours => As(EnergyUnit.WattHour); + public QuantityValue WattHours => As(EnergyUnit.WattHour); #endregion @@ -551,7 +554,7 @@ public static string GetAbbreviation(EnergyUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Energy FromBritishThermalUnits(QuantityValue britishthermalunits) { - double value = (double) britishthermalunits; + QuantityValue value = (QuantityValue) britishthermalunits; return new Energy(value, EnergyUnit.BritishThermalUnit); } @@ -561,7 +564,7 @@ public static Energy FromBritishThermalUnits(QuantityValue britishthermalunits) /// If value is NaN or Infinity. public static Energy FromCalories(QuantityValue calories) { - double value = (double) calories; + QuantityValue value = (QuantityValue) calories; return new Energy(value, EnergyUnit.Calorie); } @@ -571,7 +574,7 @@ public static Energy FromCalories(QuantityValue calories) /// If value is NaN or Infinity. public static Energy FromDecathermsEc(QuantityValue decathermsec) { - double value = (double) decathermsec; + QuantityValue value = (QuantityValue) decathermsec; return new Energy(value, EnergyUnit.DecathermEc); } @@ -581,7 +584,7 @@ public static Energy FromDecathermsEc(QuantityValue decathermsec) /// If value is NaN or Infinity. public static Energy FromDecathermsImperial(QuantityValue decathermsimperial) { - double value = (double) decathermsimperial; + QuantityValue value = (QuantityValue) decathermsimperial; return new Energy(value, EnergyUnit.DecathermImperial); } @@ -591,7 +594,7 @@ public static Energy FromDecathermsImperial(QuantityValue decathermsimperial) /// If value is NaN or Infinity. public static Energy FromDecathermsUs(QuantityValue decathermsus) { - double value = (double) decathermsus; + QuantityValue value = (QuantityValue) decathermsus; return new Energy(value, EnergyUnit.DecathermUs); } @@ -601,7 +604,7 @@ public static Energy FromDecathermsUs(QuantityValue decathermsus) /// If value is NaN or Infinity. public static Energy FromElectronVolts(QuantityValue electronvolts) { - double value = (double) electronvolts; + QuantityValue value = (QuantityValue) electronvolts; return new Energy(value, EnergyUnit.ElectronVolt); } @@ -611,7 +614,7 @@ public static Energy FromElectronVolts(QuantityValue electronvolts) /// If value is NaN or Infinity. public static Energy FromErgs(QuantityValue ergs) { - double value = (double) ergs; + QuantityValue value = (QuantityValue) ergs; return new Energy(value, EnergyUnit.Erg); } @@ -621,7 +624,7 @@ public static Energy FromErgs(QuantityValue ergs) /// If value is NaN or Infinity. public static Energy FromFootPounds(QuantityValue footpounds) { - double value = (double) footpounds; + QuantityValue value = (QuantityValue) footpounds; return new Energy(value, EnergyUnit.FootPound); } @@ -631,7 +634,7 @@ public static Energy FromFootPounds(QuantityValue footpounds) /// If value is NaN or Infinity. public static Energy FromGigabritishThermalUnits(QuantityValue gigabritishthermalunits) { - double value = (double) gigabritishthermalunits; + QuantityValue value = (QuantityValue) gigabritishthermalunits; return new Energy(value, EnergyUnit.GigabritishThermalUnit); } @@ -641,7 +644,7 @@ public static Energy FromGigabritishThermalUnits(QuantityValue gigabritishtherma /// If value is NaN or Infinity. public static Energy FromGigaelectronVolts(QuantityValue gigaelectronvolts) { - double value = (double) gigaelectronvolts; + QuantityValue value = (QuantityValue) gigaelectronvolts; return new Energy(value, EnergyUnit.GigaelectronVolt); } @@ -651,7 +654,7 @@ public static Energy FromGigaelectronVolts(QuantityValue gigaelectronvolts) /// If value is NaN or Infinity. public static Energy FromGigajoules(QuantityValue gigajoules) { - double value = (double) gigajoules; + QuantityValue value = (QuantityValue) gigajoules; return new Energy(value, EnergyUnit.Gigajoule); } @@ -661,7 +664,7 @@ public static Energy FromGigajoules(QuantityValue gigajoules) /// If value is NaN or Infinity. public static Energy FromGigawattDays(QuantityValue gigawattdays) { - double value = (double) gigawattdays; + QuantityValue value = (QuantityValue) gigawattdays; return new Energy(value, EnergyUnit.GigawattDay); } @@ -671,7 +674,7 @@ public static Energy FromGigawattDays(QuantityValue gigawattdays) /// If value is NaN or Infinity. public static Energy FromGigawattHours(QuantityValue gigawatthours) { - double value = (double) gigawatthours; + QuantityValue value = (QuantityValue) gigawatthours; return new Energy(value, EnergyUnit.GigawattHour); } @@ -681,7 +684,7 @@ public static Energy FromGigawattHours(QuantityValue gigawatthours) /// If value is NaN or Infinity. public static Energy FromHorsepowerHours(QuantityValue horsepowerhours) { - double value = (double) horsepowerhours; + QuantityValue value = (QuantityValue) horsepowerhours; return new Energy(value, EnergyUnit.HorsepowerHour); } @@ -691,7 +694,7 @@ public static Energy FromHorsepowerHours(QuantityValue horsepowerhours) /// If value is NaN or Infinity. public static Energy FromJoules(QuantityValue joules) { - double value = (double) joules; + QuantityValue value = (QuantityValue) joules; return new Energy(value, EnergyUnit.Joule); } @@ -701,7 +704,7 @@ public static Energy FromJoules(QuantityValue joules) /// If value is NaN or Infinity. public static Energy FromKilobritishThermalUnits(QuantityValue kilobritishthermalunits) { - double value = (double) kilobritishthermalunits; + QuantityValue value = (QuantityValue) kilobritishthermalunits; return new Energy(value, EnergyUnit.KilobritishThermalUnit); } @@ -711,7 +714,7 @@ public static Energy FromKilobritishThermalUnits(QuantityValue kilobritishtherma /// If value is NaN or Infinity. public static Energy FromKilocalories(QuantityValue kilocalories) { - double value = (double) kilocalories; + QuantityValue value = (QuantityValue) kilocalories; return new Energy(value, EnergyUnit.Kilocalorie); } @@ -721,7 +724,7 @@ public static Energy FromKilocalories(QuantityValue kilocalories) /// If value is NaN or Infinity. public static Energy FromKiloelectronVolts(QuantityValue kiloelectronvolts) { - double value = (double) kiloelectronvolts; + QuantityValue value = (QuantityValue) kiloelectronvolts; return new Energy(value, EnergyUnit.KiloelectronVolt); } @@ -731,7 +734,7 @@ public static Energy FromKiloelectronVolts(QuantityValue kiloelectronvolts) /// If value is NaN or Infinity. public static Energy FromKilojoules(QuantityValue kilojoules) { - double value = (double) kilojoules; + QuantityValue value = (QuantityValue) kilojoules; return new Energy(value, EnergyUnit.Kilojoule); } @@ -741,7 +744,7 @@ public static Energy FromKilojoules(QuantityValue kilojoules) /// If value is NaN or Infinity. public static Energy FromKilowattDays(QuantityValue kilowattdays) { - double value = (double) kilowattdays; + QuantityValue value = (QuantityValue) kilowattdays; return new Energy(value, EnergyUnit.KilowattDay); } @@ -751,7 +754,7 @@ public static Energy FromKilowattDays(QuantityValue kilowattdays) /// If value is NaN or Infinity. public static Energy FromKilowattHours(QuantityValue kilowatthours) { - double value = (double) kilowatthours; + QuantityValue value = (QuantityValue) kilowatthours; return new Energy(value, EnergyUnit.KilowattHour); } @@ -761,7 +764,7 @@ public static Energy FromKilowattHours(QuantityValue kilowatthours) /// If value is NaN or Infinity. public static Energy FromMegabritishThermalUnits(QuantityValue megabritishthermalunits) { - double value = (double) megabritishthermalunits; + QuantityValue value = (QuantityValue) megabritishthermalunits; return new Energy(value, EnergyUnit.MegabritishThermalUnit); } @@ -771,7 +774,7 @@ public static Energy FromMegabritishThermalUnits(QuantityValue megabritishtherma /// If value is NaN or Infinity. public static Energy FromMegacalories(QuantityValue megacalories) { - double value = (double) megacalories; + QuantityValue value = (QuantityValue) megacalories; return new Energy(value, EnergyUnit.Megacalorie); } @@ -781,7 +784,7 @@ public static Energy FromMegacalories(QuantityValue megacalories) /// If value is NaN or Infinity. public static Energy FromMegaelectronVolts(QuantityValue megaelectronvolts) { - double value = (double) megaelectronvolts; + QuantityValue value = (QuantityValue) megaelectronvolts; return new Energy(value, EnergyUnit.MegaelectronVolt); } @@ -791,7 +794,7 @@ public static Energy FromMegaelectronVolts(QuantityValue megaelectronvolts) /// If value is NaN or Infinity. public static Energy FromMegajoules(QuantityValue megajoules) { - double value = (double) megajoules; + QuantityValue value = (QuantityValue) megajoules; return new Energy(value, EnergyUnit.Megajoule); } @@ -801,7 +804,7 @@ public static Energy FromMegajoules(QuantityValue megajoules) /// If value is NaN or Infinity. public static Energy FromMegawattDays(QuantityValue megawattdays) { - double value = (double) megawattdays; + QuantityValue value = (QuantityValue) megawattdays; return new Energy(value, EnergyUnit.MegawattDay); } @@ -811,7 +814,7 @@ public static Energy FromMegawattDays(QuantityValue megawattdays) /// If value is NaN or Infinity. public static Energy FromMegawattHours(QuantityValue megawatthours) { - double value = (double) megawatthours; + QuantityValue value = (QuantityValue) megawatthours; return new Energy(value, EnergyUnit.MegawattHour); } @@ -821,7 +824,7 @@ public static Energy FromMegawattHours(QuantityValue megawatthours) /// If value is NaN or Infinity. public static Energy FromMillijoules(QuantityValue millijoules) { - double value = (double) millijoules; + QuantityValue value = (QuantityValue) millijoules; return new Energy(value, EnergyUnit.Millijoule); } @@ -831,7 +834,7 @@ public static Energy FromMillijoules(QuantityValue millijoules) /// If value is NaN or Infinity. public static Energy FromTeraelectronVolts(QuantityValue teraelectronvolts) { - double value = (double) teraelectronvolts; + QuantityValue value = (QuantityValue) teraelectronvolts; return new Energy(value, EnergyUnit.TeraelectronVolt); } @@ -841,7 +844,7 @@ public static Energy FromTeraelectronVolts(QuantityValue teraelectronvolts) /// If value is NaN or Infinity. public static Energy FromTerawattDays(QuantityValue terawattdays) { - double value = (double) terawattdays; + QuantityValue value = (QuantityValue) terawattdays; return new Energy(value, EnergyUnit.TerawattDay); } @@ -851,7 +854,7 @@ public static Energy FromTerawattDays(QuantityValue terawattdays) /// If value is NaN or Infinity. public static Energy FromTerawattHours(QuantityValue terawatthours) { - double value = (double) terawatthours; + QuantityValue value = (QuantityValue) terawatthours; return new Energy(value, EnergyUnit.TerawattHour); } @@ -861,7 +864,7 @@ public static Energy FromTerawattHours(QuantityValue terawatthours) /// If value is NaN or Infinity. public static Energy FromThermsEc(QuantityValue thermsec) { - double value = (double) thermsec; + QuantityValue value = (QuantityValue) thermsec; return new Energy(value, EnergyUnit.ThermEc); } @@ -871,7 +874,7 @@ public static Energy FromThermsEc(QuantityValue thermsec) /// If value is NaN or Infinity. public static Energy FromThermsImperial(QuantityValue thermsimperial) { - double value = (double) thermsimperial; + QuantityValue value = (QuantityValue) thermsimperial; return new Energy(value, EnergyUnit.ThermImperial); } @@ -881,7 +884,7 @@ public static Energy FromThermsImperial(QuantityValue thermsimperial) /// If value is NaN or Infinity. public static Energy FromThermsUs(QuantityValue thermsus) { - double value = (double) thermsus; + QuantityValue value = (QuantityValue) thermsus; return new Energy(value, EnergyUnit.ThermUs); } @@ -891,7 +894,7 @@ public static Energy FromThermsUs(QuantityValue thermsus) /// If value is NaN or Infinity. public static Energy FromWattDays(QuantityValue wattdays) { - double value = (double) wattdays; + QuantityValue value = (QuantityValue) wattdays; return new Energy(value, EnergyUnit.WattDay); } @@ -901,7 +904,7 @@ public static Energy FromWattDays(QuantityValue wattdays) /// If value is NaN or Infinity. public static Energy FromWattHours(QuantityValue watthours) { - double value = (double) watthours; + QuantityValue value = (QuantityValue) watthours; return new Energy(value, EnergyUnit.WattHour); } @@ -913,7 +916,7 @@ public static Energy FromWattHours(QuantityValue watthours) /// Energy unit value. public static Energy From(QuantityValue value, EnergyUnit fromUnit) { - return new Energy((double)value, fromUnit); + return new Energy((QuantityValue)value, fromUnit); } #endregion @@ -1083,25 +1086,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Energ } /// Get from multiplying value and . - public static Energy operator *(double left, Energy right) + public static Energy operator *(QuantityValue left, Energy right) { return new Energy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Energy operator *(Energy left, double right) + public static Energy operator *(Energy left, QuantityValue right) { return new Energy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Energy operator /(Energy left, double right) + public static Energy operator /(Energy left, QuantityValue right) { return new Energy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Energy left, Energy right) + public static QuantityValue operator /(Energy left, Energy right) { return left.Joules / right.Joules; } @@ -1134,6 +1137,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Energ return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Energy left, Energy right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Energy left, Energy right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1146,7 +1162,29 @@ public int CompareTo(object obj) /// public int CompareTo(Energy other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Energy objEnergy)) + return false; + return Equals(objEnergy); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Energy other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1189,13 +1227,13 @@ public int CompareTo(Energy other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Energy other, double tolerance, ComparisonType comparisonType) + public bool Equals(Energy other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1206,7 +1244,7 @@ public bool Equals(Energy other, double tolerance, ComparisonType comparisonType /// A hash code for the current Energy. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1217,17 +1255,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(EnergyUnit unit) + public QuantityValue As(EnergyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1242,12 +1279,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is EnergyUnit unitAsEnergyUnit)) + if (!(unit is EnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyUnit)} is supported.", nameof(unit)); - return As(unitAsEnergyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1279,7 +1316,7 @@ public Energy ToUnit(EnergyUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Energy)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(EnergyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1287,17 +1324,17 @@ public Energy ToUnit(EnergyUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is EnergyUnit unitAsEnergyUnit)) + if (!(unit is EnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1324,10 +1361,10 @@ public Energy ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(EnergyUnit unit) + private QuantityValue GetValueAs(EnergyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs index 5a3eed83c2..125d9bac9c 100644 --- a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Entropy is an important concept in the branch of science known as thermodynamics. The idea of "irreversibility" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units /// [DataContract] - public partial struct Entropy : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Entropy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -78,9 +78,9 @@ static Entropy() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Entropy(double value, EntropyUnit unit) + public Entropy(QuantityValue value, EntropyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -92,14 +92,14 @@ public Entropy(double value, EntropyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Entropy(double value, UnitSystem unitSystem) + public Entropy(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -140,7 +140,10 @@ public Entropy(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -163,39 +166,39 @@ public Entropy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); + public QuantityValue CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); + public QuantityValue JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); + public QuantityValue JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); + public QuantityValue KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); + public QuantityValue KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); + public QuantityValue KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); + public QuantityValue MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); #endregion @@ -269,7 +272,7 @@ public static string GetAbbreviation(EntropyUnit unit, IFormatProvider? provider /// If value is NaN or Infinity. public static Entropy FromCaloriesPerKelvin(QuantityValue caloriesperkelvin) { - double value = (double) caloriesperkelvin; + QuantityValue value = (QuantityValue) caloriesperkelvin; return new Entropy(value, EntropyUnit.CaloriePerKelvin); } @@ -279,7 +282,7 @@ public static Entropy FromCaloriesPerKelvin(QuantityValue caloriesperkelvin) /// If value is NaN or Infinity. public static Entropy FromJoulesPerDegreeCelsius(QuantityValue joulesperdegreecelsius) { - double value = (double) joulesperdegreecelsius; + QuantityValue value = (QuantityValue) joulesperdegreecelsius; return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); } @@ -289,7 +292,7 @@ public static Entropy FromJoulesPerDegreeCelsius(QuantityValue joulesperdegreece /// If value is NaN or Infinity. public static Entropy FromJoulesPerKelvin(QuantityValue joulesperkelvin) { - double value = (double) joulesperkelvin; + QuantityValue value = (QuantityValue) joulesperkelvin; return new Entropy(value, EntropyUnit.JoulePerKelvin); } @@ -299,7 +302,7 @@ public static Entropy FromJoulesPerKelvin(QuantityValue joulesperkelvin) /// If value is NaN or Infinity. public static Entropy FromKilocaloriesPerKelvin(QuantityValue kilocaloriesperkelvin) { - double value = (double) kilocaloriesperkelvin; + QuantityValue value = (QuantityValue) kilocaloriesperkelvin; return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); } @@ -309,7 +312,7 @@ public static Entropy FromKilocaloriesPerKelvin(QuantityValue kilocaloriesperkel /// If value is NaN or Infinity. public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue kilojoulesperdegreecelsius) { - double value = (double) kilojoulesperdegreecelsius; + QuantityValue value = (QuantityValue) kilojoulesperdegreecelsius; return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); } @@ -319,7 +322,7 @@ public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue kilojoulesper /// If value is NaN or Infinity. public static Entropy FromKilojoulesPerKelvin(QuantityValue kilojoulesperkelvin) { - double value = (double) kilojoulesperkelvin; + QuantityValue value = (QuantityValue) kilojoulesperkelvin; return new Entropy(value, EntropyUnit.KilojoulePerKelvin); } @@ -329,7 +332,7 @@ public static Entropy FromKilojoulesPerKelvin(QuantityValue kilojoulesperkelvin) /// If value is NaN or Infinity. public static Entropy FromMegajoulesPerKelvin(QuantityValue megajoulesperkelvin) { - double value = (double) megajoulesperkelvin; + QuantityValue value = (QuantityValue) megajoulesperkelvin; return new Entropy(value, EntropyUnit.MegajoulePerKelvin); } @@ -341,7 +344,7 @@ public static Entropy FromMegajoulesPerKelvin(QuantityValue megajoulesperkelvin) /// Entropy unit value. public static Entropy From(QuantityValue value, EntropyUnit fromUnit) { - return new Entropy((double)value, fromUnit); + return new Entropy((QuantityValue)value, fromUnit); } #endregion @@ -511,25 +514,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Entro } /// Get from multiplying value and . - public static Entropy operator *(double left, Entropy right) + public static Entropy operator *(QuantityValue left, Entropy right) { return new Entropy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Entropy operator *(Entropy left, double right) + public static Entropy operator *(Entropy left, QuantityValue right) { return new Entropy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Entropy operator /(Entropy left, double right) + public static Entropy operator /(Entropy left, QuantityValue right) { return new Entropy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Entropy left, Entropy right) + public static QuantityValue operator /(Entropy left, Entropy right) { return left.JoulesPerKelvin / right.JoulesPerKelvin; } @@ -562,6 +565,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Entro return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Entropy left, Entropy right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Entropy left, Entropy right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -574,7 +590,29 @@ public int CompareTo(object obj) /// public int CompareTo(Entropy other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Entropy objEntropy)) + return false; + return Equals(objEntropy); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Entropy other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -617,13 +655,13 @@ public int CompareTo(Entropy other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Entropy other, double tolerance, ComparisonType comparisonType) + public bool Equals(Entropy other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -634,7 +672,7 @@ public bool Equals(Entropy other, double tolerance, ComparisonType comparisonTyp /// A hash code for the current Entropy. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -645,17 +683,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(EntropyUnit unit) + public QuantityValue As(EntropyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -670,12 +707,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is EntropyUnit unitAsEntropyUnit)) + if (!(unit is EntropyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EntropyUnit)} is supported.", nameof(unit)); - return As(unitAsEntropyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -707,7 +744,7 @@ public Entropy ToUnit(EntropyUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Entropy)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(EntropyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -715,17 +752,17 @@ public Entropy ToUnit(EntropyUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is EntropyUnit unitAsEntropyUnit)) + if (!(unit is EntropyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EntropyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsEntropyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -752,10 +789,10 @@ public Entropy ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(EntropyUnit unit) + private QuantityValue GetValueAs(EntropyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Force.g.cs b/UnitsNet/GeneratedCode/Quantities/Force.g.cs index 67478a3e16..08781f06c6 100644 --- a/UnitsNet/GeneratedCode/Quantities/Force.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Force.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F. /// [DataContract] - public partial struct Force : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Force : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -86,9 +86,9 @@ static Force() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Force(double value, ForceUnit unit) + public Force(QuantityValue value, ForceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -100,14 +100,14 @@ public Force(double value, ForceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Force(double value, UnitSystem unitSystem) + public Force(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -148,7 +148,10 @@ public Force(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -171,79 +174,79 @@ public Force(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decanewtons => As(ForceUnit.Decanewton); + public QuantityValue Decanewtons => As(ForceUnit.Decanewton); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Dyne => As(ForceUnit.Dyn); + public QuantityValue Dyne => As(ForceUnit.Dyn); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForce => As(ForceUnit.KilogramForce); + public QuantityValue KilogramsForce => As(ForceUnit.KilogramForce); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilonewtons => As(ForceUnit.Kilonewton); + public QuantityValue Kilonewtons => As(ForceUnit.Kilonewton); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KiloPonds => As(ForceUnit.KiloPond); + public QuantityValue KiloPonds => As(ForceUnit.KiloPond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForce => As(ForceUnit.KilopoundForce); + public QuantityValue KilopoundsForce => As(ForceUnit.KilopoundForce); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Meganewtons => As(ForceUnit.Meganewton); + public QuantityValue Meganewtons => As(ForceUnit.Meganewton); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Micronewtons => As(ForceUnit.Micronewton); + public QuantityValue Micronewtons => As(ForceUnit.Micronewton); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millinewtons => As(ForceUnit.Millinewton); + public QuantityValue Millinewtons => As(ForceUnit.Millinewton); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Newtons => As(ForceUnit.Newton); + public QuantityValue Newtons => As(ForceUnit.Newton); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OunceForce => As(ForceUnit.OunceForce); + public QuantityValue OunceForce => As(ForceUnit.OunceForce); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Poundals => As(ForceUnit.Poundal); + public QuantityValue Poundals => As(ForceUnit.Poundal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForce => As(ForceUnit.PoundForce); + public QuantityValue PoundsForce => As(ForceUnit.PoundForce); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ShortTonsForce => As(ForceUnit.ShortTonForce); + public QuantityValue ShortTonsForce => As(ForceUnit.ShortTonForce); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForce => As(ForceUnit.TonneForce); + public QuantityValue TonnesForce => As(ForceUnit.TonneForce); #endregion @@ -354,7 +357,7 @@ public static string GetAbbreviation(ForceUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Force FromDecanewtons(QuantityValue decanewtons) { - double value = (double) decanewtons; + QuantityValue value = (QuantityValue) decanewtons; return new Force(value, ForceUnit.Decanewton); } @@ -364,7 +367,7 @@ public static Force FromDecanewtons(QuantityValue decanewtons) /// If value is NaN or Infinity. public static Force FromDyne(QuantityValue dyne) { - double value = (double) dyne; + QuantityValue value = (QuantityValue) dyne; return new Force(value, ForceUnit.Dyn); } @@ -374,7 +377,7 @@ public static Force FromDyne(QuantityValue dyne) /// If value is NaN or Infinity. public static Force FromKilogramsForce(QuantityValue kilogramsforce) { - double value = (double) kilogramsforce; + QuantityValue value = (QuantityValue) kilogramsforce; return new Force(value, ForceUnit.KilogramForce); } @@ -384,7 +387,7 @@ public static Force FromKilogramsForce(QuantityValue kilogramsforce) /// If value is NaN or Infinity. public static Force FromKilonewtons(QuantityValue kilonewtons) { - double value = (double) kilonewtons; + QuantityValue value = (QuantityValue) kilonewtons; return new Force(value, ForceUnit.Kilonewton); } @@ -394,7 +397,7 @@ public static Force FromKilonewtons(QuantityValue kilonewtons) /// If value is NaN or Infinity. public static Force FromKiloPonds(QuantityValue kiloponds) { - double value = (double) kiloponds; + QuantityValue value = (QuantityValue) kiloponds; return new Force(value, ForceUnit.KiloPond); } @@ -404,7 +407,7 @@ public static Force FromKiloPonds(QuantityValue kiloponds) /// If value is NaN or Infinity. public static Force FromKilopoundsForce(QuantityValue kilopoundsforce) { - double value = (double) kilopoundsforce; + QuantityValue value = (QuantityValue) kilopoundsforce; return new Force(value, ForceUnit.KilopoundForce); } @@ -414,7 +417,7 @@ public static Force FromKilopoundsForce(QuantityValue kilopoundsforce) /// If value is NaN or Infinity. public static Force FromMeganewtons(QuantityValue meganewtons) { - double value = (double) meganewtons; + QuantityValue value = (QuantityValue) meganewtons; return new Force(value, ForceUnit.Meganewton); } @@ -424,7 +427,7 @@ public static Force FromMeganewtons(QuantityValue meganewtons) /// If value is NaN or Infinity. public static Force FromMicronewtons(QuantityValue micronewtons) { - double value = (double) micronewtons; + QuantityValue value = (QuantityValue) micronewtons; return new Force(value, ForceUnit.Micronewton); } @@ -434,7 +437,7 @@ public static Force FromMicronewtons(QuantityValue micronewtons) /// If value is NaN or Infinity. public static Force FromMillinewtons(QuantityValue millinewtons) { - double value = (double) millinewtons; + QuantityValue value = (QuantityValue) millinewtons; return new Force(value, ForceUnit.Millinewton); } @@ -444,7 +447,7 @@ public static Force FromMillinewtons(QuantityValue millinewtons) /// If value is NaN or Infinity. public static Force FromNewtons(QuantityValue newtons) { - double value = (double) newtons; + QuantityValue value = (QuantityValue) newtons; return new Force(value, ForceUnit.Newton); } @@ -454,7 +457,7 @@ public static Force FromNewtons(QuantityValue newtons) /// If value is NaN or Infinity. public static Force FromOunceForce(QuantityValue ounceforce) { - double value = (double) ounceforce; + QuantityValue value = (QuantityValue) ounceforce; return new Force(value, ForceUnit.OunceForce); } @@ -464,7 +467,7 @@ public static Force FromOunceForce(QuantityValue ounceforce) /// If value is NaN or Infinity. public static Force FromPoundals(QuantityValue poundals) { - double value = (double) poundals; + QuantityValue value = (QuantityValue) poundals; return new Force(value, ForceUnit.Poundal); } @@ -474,7 +477,7 @@ public static Force FromPoundals(QuantityValue poundals) /// If value is NaN or Infinity. public static Force FromPoundsForce(QuantityValue poundsforce) { - double value = (double) poundsforce; + QuantityValue value = (QuantityValue) poundsforce; return new Force(value, ForceUnit.PoundForce); } @@ -484,7 +487,7 @@ public static Force FromPoundsForce(QuantityValue poundsforce) /// If value is NaN or Infinity. public static Force FromShortTonsForce(QuantityValue shorttonsforce) { - double value = (double) shorttonsforce; + QuantityValue value = (QuantityValue) shorttonsforce; return new Force(value, ForceUnit.ShortTonForce); } @@ -494,7 +497,7 @@ public static Force FromShortTonsForce(QuantityValue shorttonsforce) /// If value is NaN or Infinity. public static Force FromTonnesForce(QuantityValue tonnesforce) { - double value = (double) tonnesforce; + QuantityValue value = (QuantityValue) tonnesforce; return new Force(value, ForceUnit.TonneForce); } @@ -506,7 +509,7 @@ public static Force FromTonnesForce(QuantityValue tonnesforce) /// Force unit value. public static Force From(QuantityValue value, ForceUnit fromUnit) { - return new Force((double)value, fromUnit); + return new Force((QuantityValue)value, fromUnit); } #endregion @@ -676,25 +679,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Force } /// Get from multiplying value and . - public static Force operator *(double left, Force right) + public static Force operator *(QuantityValue left, Force right) { return new Force(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Force operator *(Force left, double right) + public static Force operator *(Force left, QuantityValue right) { return new Force(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Force operator /(Force left, double right) + public static Force operator /(Force left, QuantityValue right) { return new Force(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Force left, Force right) + public static QuantityValue operator /(Force left, Force right) { return left.Newtons / right.Newtons; } @@ -727,6 +730,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Force return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Force left, Force right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Force left, Force right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -739,7 +755,29 @@ public int CompareTo(object obj) /// public int CompareTo(Force other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Force objForce)) + return false; + return Equals(objForce); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Force other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -782,13 +820,13 @@ public int CompareTo(Force other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Force other, double tolerance, ComparisonType comparisonType) + public bool Equals(Force other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -799,7 +837,7 @@ public bool Equals(Force other, double tolerance, ComparisonType comparisonType) /// A hash code for the current Force. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -810,17 +848,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ForceUnit unit) + public QuantityValue As(ForceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -835,12 +872,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ForceUnit unitAsForceUnit)) + if (!(unit is ForceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceUnit)} is supported.", nameof(unit)); - return As(unitAsForceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -872,7 +909,7 @@ public Force ToUnit(ForceUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Force)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ForceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -880,17 +917,17 @@ public Force ToUnit(ForceUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ForceUnit unitAsForceUnit)) + if (!(unit is ForceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsForceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -917,10 +954,10 @@ public Force ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ForceUnit unit) + private QuantityValue GetValueAs(ForceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs index 247b741b2a..8b897ef600 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time). /// [DataContract] - public partial struct ForceChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ForceChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -86,9 +86,9 @@ static ForceChangeRate() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ForceChangeRate(double value, ForceChangeRateUnit unit) + public ForceChangeRate(QuantityValue value, ForceChangeRateUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -100,14 +100,14 @@ public ForceChangeRate(double value, ForceChangeRateUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ForceChangeRate(double value, UnitSystem unitSystem) + public ForceChangeRate(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -148,7 +148,10 @@ public ForceChangeRate(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -171,79 +174,79 @@ public ForceChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); + public QuantityValue CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); + public QuantityValue DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); + public QuantityValue DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); + public QuantityValue DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); + public QuantityValue KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); + public QuantityValue KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerMinute => As(ForceChangeRateUnit.KilopoundForcePerMinute); + public QuantityValue KilopoundsForcePerMinute => As(ForceChangeRateUnit.KilopoundForcePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerSecond => As(ForceChangeRateUnit.KilopoundForcePerSecond); + public QuantityValue KilopoundsForcePerSecond => As(ForceChangeRateUnit.KilopoundForcePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); + public QuantityValue MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); + public QuantityValue MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); + public QuantityValue NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); + public QuantityValue NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); + public QuantityValue NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerMinute => As(ForceChangeRateUnit.PoundForcePerMinute); + public QuantityValue PoundsForcePerMinute => As(ForceChangeRateUnit.PoundForcePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerSecond => As(ForceChangeRateUnit.PoundForcePerSecond); + public QuantityValue PoundsForcePerSecond => As(ForceChangeRateUnit.PoundForcePerSecond); #endregion @@ -341,7 +344,7 @@ public static string GetAbbreviation(ForceChangeRateUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue centinewtonspersecond) { - double value = (double) centinewtonspersecond; + QuantityValue value = (QuantityValue) centinewtonspersecond; return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); } @@ -351,7 +354,7 @@ public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue centinewto /// If value is NaN or Infinity. public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue decanewtonsperminute) { - double value = (double) decanewtonsperminute; + QuantityValue value = (QuantityValue) decanewtonsperminute; return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); } @@ -361,7 +364,7 @@ public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue decanewtons /// If value is NaN or Infinity. public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue decanewtonspersecond) { - double value = (double) decanewtonspersecond; + QuantityValue value = (QuantityValue) decanewtonspersecond; return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); } @@ -371,7 +374,7 @@ public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue decanewtons /// If value is NaN or Infinity. public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue decinewtonspersecond) { - double value = (double) decinewtonspersecond; + QuantityValue value = (QuantityValue) decinewtonspersecond; return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); } @@ -381,7 +384,7 @@ public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue decinewtons /// If value is NaN or Infinity. public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue kilonewtonsperminute) { - double value = (double) kilonewtonsperminute; + QuantityValue value = (QuantityValue) kilonewtonsperminute; return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); } @@ -391,7 +394,7 @@ public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue kilonewtons /// If value is NaN or Infinity. public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue kilonewtonspersecond) { - double value = (double) kilonewtonspersecond; + QuantityValue value = (QuantityValue) kilonewtonspersecond; return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); } @@ -401,7 +404,7 @@ public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue kilonewtons /// If value is NaN or Infinity. public static ForceChangeRate FromKilopoundsForcePerMinute(QuantityValue kilopoundsforceperminute) { - double value = (double) kilopoundsforceperminute; + QuantityValue value = (QuantityValue) kilopoundsforceperminute; return new ForceChangeRate(value, ForceChangeRateUnit.KilopoundForcePerMinute); } @@ -411,7 +414,7 @@ public static ForceChangeRate FromKilopoundsForcePerMinute(QuantityValue kilopou /// If value is NaN or Infinity. public static ForceChangeRate FromKilopoundsForcePerSecond(QuantityValue kilopoundsforcepersecond) { - double value = (double) kilopoundsforcepersecond; + QuantityValue value = (QuantityValue) kilopoundsforcepersecond; return new ForceChangeRate(value, ForceChangeRateUnit.KilopoundForcePerSecond); } @@ -421,7 +424,7 @@ public static ForceChangeRate FromKilopoundsForcePerSecond(QuantityValue kilopou /// If value is NaN or Infinity. public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue micronewtonspersecond) { - double value = (double) micronewtonspersecond; + QuantityValue value = (QuantityValue) micronewtonspersecond; return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); } @@ -431,7 +434,7 @@ public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue micronewto /// If value is NaN or Infinity. public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue millinewtonspersecond) { - double value = (double) millinewtonspersecond; + QuantityValue value = (QuantityValue) millinewtonspersecond; return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); } @@ -441,7 +444,7 @@ public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue millinewto /// If value is NaN or Infinity. public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue nanonewtonspersecond) { - double value = (double) nanonewtonspersecond; + QuantityValue value = (QuantityValue) nanonewtonspersecond; return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); } @@ -451,7 +454,7 @@ public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue nanonewtons /// If value is NaN or Infinity. public static ForceChangeRate FromNewtonsPerMinute(QuantityValue newtonsperminute) { - double value = (double) newtonsperminute; + QuantityValue value = (QuantityValue) newtonsperminute; return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); } @@ -461,7 +464,7 @@ public static ForceChangeRate FromNewtonsPerMinute(QuantityValue newtonsperminut /// If value is NaN or Infinity. public static ForceChangeRate FromNewtonsPerSecond(QuantityValue newtonspersecond) { - double value = (double) newtonspersecond; + QuantityValue value = (QuantityValue) newtonspersecond; return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerSecond); } @@ -471,7 +474,7 @@ public static ForceChangeRate FromNewtonsPerSecond(QuantityValue newtonspersecon /// If value is NaN or Infinity. public static ForceChangeRate FromPoundsForcePerMinute(QuantityValue poundsforceperminute) { - double value = (double) poundsforceperminute; + QuantityValue value = (QuantityValue) poundsforceperminute; return new ForceChangeRate(value, ForceChangeRateUnit.PoundForcePerMinute); } @@ -481,7 +484,7 @@ public static ForceChangeRate FromPoundsForcePerMinute(QuantityValue poundsforce /// If value is NaN or Infinity. public static ForceChangeRate FromPoundsForcePerSecond(QuantityValue poundsforcepersecond) { - double value = (double) poundsforcepersecond; + QuantityValue value = (QuantityValue) poundsforcepersecond; return new ForceChangeRate(value, ForceChangeRateUnit.PoundForcePerSecond); } @@ -493,7 +496,7 @@ public static ForceChangeRate FromPoundsForcePerSecond(QuantityValue poundsforce /// ForceChangeRate unit value. public static ForceChangeRate From(QuantityValue value, ForceChangeRateUnit fromUnit) { - return new ForceChangeRate((double)value, fromUnit); + return new ForceChangeRate((QuantityValue)value, fromUnit); } #endregion @@ -663,25 +666,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Force } /// Get from multiplying value and . - public static ForceChangeRate operator *(double left, ForceChangeRate right) + public static ForceChangeRate operator *(QuantityValue left, ForceChangeRate right) { return new ForceChangeRate(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ForceChangeRate operator *(ForceChangeRate left, double right) + public static ForceChangeRate operator *(ForceChangeRate left, QuantityValue right) { return new ForceChangeRate(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ForceChangeRate operator /(ForceChangeRate left, double right) + public static ForceChangeRate operator /(ForceChangeRate left, QuantityValue right) { return new ForceChangeRate(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ForceChangeRate left, ForceChangeRate right) + public static QuantityValue operator /(ForceChangeRate left, ForceChangeRate right) { return left.NewtonsPerSecond / right.NewtonsPerSecond; } @@ -714,6 +717,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Force return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ForceChangeRate left, ForceChangeRate right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ForceChangeRate left, ForceChangeRate right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -726,7 +742,29 @@ public int CompareTo(object obj) /// public int CompareTo(ForceChangeRate other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ForceChangeRate objForceChangeRate)) + return false; + return Equals(objForceChangeRate); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ForceChangeRate other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -769,13 +807,13 @@ public int CompareTo(ForceChangeRate other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ForceChangeRate other, double tolerance, ComparisonType comparisonType) + public bool Equals(ForceChangeRate other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -786,7 +824,7 @@ public bool Equals(ForceChangeRate other, double tolerance, ComparisonType compa /// A hash code for the current ForceChangeRate. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -797,17 +835,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ForceChangeRateUnit unit) + public QuantityValue As(ForceChangeRateUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -822,12 +859,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ForceChangeRateUnit unitAsForceChangeRateUnit)) + if (!(unit is ForceChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsForceChangeRateUnit); + return (QuantityValue)As(typedUnit); } /// @@ -859,7 +896,7 @@ public ForceChangeRate ToUnit(ForceChangeRateUnit unit, UnitConverter unitConver var converted = conversionFunction(this); return (ForceChangeRate)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ForceChangeRateUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -867,17 +904,17 @@ public ForceChangeRate ToUnit(ForceChangeRateUnit unit, UnitConverter unitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ForceChangeRateUnit unitAsForceChangeRateUnit)) + if (!(unit is ForceChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsForceChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -904,10 +941,10 @@ public ForceChangeRate ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ForceChangeRateUnit unit) + private QuantityValue GetValueAs(ForceChangeRateUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs index 820ff9473d..f937a368cf 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The magnitude of force per unit length. /// [DataContract] - public partial struct ForcePerLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ForcePerLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -109,9 +109,9 @@ static ForcePerLength() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ForcePerLength(double value, ForcePerLengthUnit unit) + public ForcePerLength(QuantityValue value, ForcePerLengthUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -123,14 +123,14 @@ public ForcePerLength(double value, ForcePerLengthUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ForcePerLength(double value, UnitSystem unitSystem) + public ForcePerLength(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -171,7 +171,10 @@ public ForcePerLength(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -194,194 +197,194 @@ public ForcePerLength(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentinewtonsPerCentimeter => As(ForcePerLengthUnit.CentinewtonPerCentimeter); + public QuantityValue CentinewtonsPerCentimeter => As(ForcePerLengthUnit.CentinewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); + public QuantityValue CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentinewtonsPerMillimeter => As(ForcePerLengthUnit.CentinewtonPerMillimeter); + public QuantityValue CentinewtonsPerMillimeter => As(ForcePerLengthUnit.CentinewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecanewtonsPerCentimeter => As(ForcePerLengthUnit.DecanewtonPerCentimeter); + public QuantityValue DecanewtonsPerCentimeter => As(ForcePerLengthUnit.DecanewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecanewtonsPerMeter => As(ForcePerLengthUnit.DecanewtonPerMeter); + public QuantityValue DecanewtonsPerMeter => As(ForcePerLengthUnit.DecanewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecanewtonsPerMillimeter => As(ForcePerLengthUnit.DecanewtonPerMillimeter); + public QuantityValue DecanewtonsPerMillimeter => As(ForcePerLengthUnit.DecanewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecinewtonsPerCentimeter => As(ForcePerLengthUnit.DecinewtonPerCentimeter); + public QuantityValue DecinewtonsPerCentimeter => As(ForcePerLengthUnit.DecinewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); + public QuantityValue DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecinewtonsPerMillimeter => As(ForcePerLengthUnit.DecinewtonPerMillimeter); + public QuantityValue DecinewtonsPerMillimeter => As(ForcePerLengthUnit.DecinewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForcePerCentimeter => As(ForcePerLengthUnit.KilogramForcePerCentimeter); + public QuantityValue KilogramsForcePerCentimeter => As(ForcePerLengthUnit.KilogramForcePerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); + public QuantityValue KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForcePerMillimeter => As(ForcePerLengthUnit.KilogramForcePerMillimeter); + public QuantityValue KilogramsForcePerMillimeter => As(ForcePerLengthUnit.KilogramForcePerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerCentimeter => As(ForcePerLengthUnit.KilonewtonPerCentimeter); + public QuantityValue KilonewtonsPerCentimeter => As(ForcePerLengthUnit.KilonewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); + public QuantityValue KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerMillimeter => As(ForcePerLengthUnit.KilonewtonPerMillimeter); + public QuantityValue KilonewtonsPerMillimeter => As(ForcePerLengthUnit.KilonewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerFoot => As(ForcePerLengthUnit.KilopoundForcePerFoot); + public QuantityValue KilopoundsForcePerFoot => As(ForcePerLengthUnit.KilopoundForcePerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerInch => As(ForcePerLengthUnit.KilopoundForcePerInch); + public QuantityValue KilopoundsForcePerInch => As(ForcePerLengthUnit.KilopoundForcePerInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonsPerCentimeter => As(ForcePerLengthUnit.MeganewtonPerCentimeter); + public QuantityValue MeganewtonsPerCentimeter => As(ForcePerLengthUnit.MeganewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); + public QuantityValue MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonsPerMillimeter => As(ForcePerLengthUnit.MeganewtonPerMillimeter); + public QuantityValue MeganewtonsPerMillimeter => As(ForcePerLengthUnit.MeganewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicronewtonsPerCentimeter => As(ForcePerLengthUnit.MicronewtonPerCentimeter); + public QuantityValue MicronewtonsPerCentimeter => As(ForcePerLengthUnit.MicronewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); + public QuantityValue MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicronewtonsPerMillimeter => As(ForcePerLengthUnit.MicronewtonPerMillimeter); + public QuantityValue MicronewtonsPerMillimeter => As(ForcePerLengthUnit.MicronewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillinewtonsPerCentimeter => As(ForcePerLengthUnit.MillinewtonPerCentimeter); + public QuantityValue MillinewtonsPerCentimeter => As(ForcePerLengthUnit.MillinewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); + public QuantityValue MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillinewtonsPerMillimeter => As(ForcePerLengthUnit.MillinewtonPerMillimeter); + public QuantityValue MillinewtonsPerMillimeter => As(ForcePerLengthUnit.MillinewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanonewtonsPerCentimeter => As(ForcePerLengthUnit.NanonewtonPerCentimeter); + public QuantityValue NanonewtonsPerCentimeter => As(ForcePerLengthUnit.NanonewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); + public QuantityValue NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanonewtonsPerMillimeter => As(ForcePerLengthUnit.NanonewtonPerMillimeter); + public QuantityValue NanonewtonsPerMillimeter => As(ForcePerLengthUnit.NanonewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerCentimeter => As(ForcePerLengthUnit.NewtonPerCentimeter); + public QuantityValue NewtonsPerCentimeter => As(ForcePerLengthUnit.NewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); + public QuantityValue NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerMillimeter => As(ForcePerLengthUnit.NewtonPerMillimeter); + public QuantityValue NewtonsPerMillimeter => As(ForcePerLengthUnit.NewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerFoot => As(ForcePerLengthUnit.PoundForcePerFoot); + public QuantityValue PoundsForcePerFoot => As(ForcePerLengthUnit.PoundForcePerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerInch => As(ForcePerLengthUnit.PoundForcePerInch); + public QuantityValue PoundsForcePerInch => As(ForcePerLengthUnit.PoundForcePerInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerYard => As(ForcePerLengthUnit.PoundForcePerYard); + public QuantityValue PoundsForcePerYard => As(ForcePerLengthUnit.PoundForcePerYard); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForcePerCentimeter => As(ForcePerLengthUnit.TonneForcePerCentimeter); + public QuantityValue TonnesForcePerCentimeter => As(ForcePerLengthUnit.TonneForcePerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForcePerMeter => As(ForcePerLengthUnit.TonneForcePerMeter); + public QuantityValue TonnesForcePerMeter => As(ForcePerLengthUnit.TonneForcePerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForcePerMillimeter => As(ForcePerLengthUnit.TonneForcePerMillimeter); + public QuantityValue TonnesForcePerMillimeter => As(ForcePerLengthUnit.TonneForcePerMillimeter); #endregion @@ -554,7 +557,7 @@ public static string GetAbbreviation(ForcePerLengthUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static ForcePerLength FromCentinewtonsPerCentimeter(QuantityValue centinewtonspercentimeter) { - double value = (double) centinewtonspercentimeter; + QuantityValue value = (QuantityValue) centinewtonspercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerCentimeter); } @@ -564,7 +567,7 @@ public static ForcePerLength FromCentinewtonsPerCentimeter(QuantityValue centine /// If value is NaN or Infinity. public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue centinewtonspermeter) { - double value = (double) centinewtonspermeter; + QuantityValue value = (QuantityValue) centinewtonspermeter; return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); } @@ -574,7 +577,7 @@ public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue centinewtons /// If value is NaN or Infinity. public static ForcePerLength FromCentinewtonsPerMillimeter(QuantityValue centinewtonspermillimeter) { - double value = (double) centinewtonspermillimeter; + QuantityValue value = (QuantityValue) centinewtonspermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMillimeter); } @@ -584,7 +587,7 @@ public static ForcePerLength FromCentinewtonsPerMillimeter(QuantityValue centine /// If value is NaN or Infinity. public static ForcePerLength FromDecanewtonsPerCentimeter(QuantityValue decanewtonspercentimeter) { - double value = (double) decanewtonspercentimeter; + QuantityValue value = (QuantityValue) decanewtonspercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerCentimeter); } @@ -594,7 +597,7 @@ public static ForcePerLength FromDecanewtonsPerCentimeter(QuantityValue decanewt /// If value is NaN or Infinity. public static ForcePerLength FromDecanewtonsPerMeter(QuantityValue decanewtonspermeter) { - double value = (double) decanewtonspermeter; + QuantityValue value = (QuantityValue) decanewtonspermeter; return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerMeter); } @@ -604,7 +607,7 @@ public static ForcePerLength FromDecanewtonsPerMeter(QuantityValue decanewtonspe /// If value is NaN or Infinity. public static ForcePerLength FromDecanewtonsPerMillimeter(QuantityValue decanewtonspermillimeter) { - double value = (double) decanewtonspermillimeter; + QuantityValue value = (QuantityValue) decanewtonspermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerMillimeter); } @@ -614,7 +617,7 @@ public static ForcePerLength FromDecanewtonsPerMillimeter(QuantityValue decanewt /// If value is NaN or Infinity. public static ForcePerLength FromDecinewtonsPerCentimeter(QuantityValue decinewtonspercentimeter) { - double value = (double) decinewtonspercentimeter; + QuantityValue value = (QuantityValue) decinewtonspercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerCentimeter); } @@ -624,7 +627,7 @@ public static ForcePerLength FromDecinewtonsPerCentimeter(QuantityValue decinewt /// If value is NaN or Infinity. public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue decinewtonspermeter) { - double value = (double) decinewtonspermeter; + QuantityValue value = (QuantityValue) decinewtonspermeter; return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); } @@ -634,7 +637,7 @@ public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue decinewtonspe /// If value is NaN or Infinity. public static ForcePerLength FromDecinewtonsPerMillimeter(QuantityValue decinewtonspermillimeter) { - double value = (double) decinewtonspermillimeter; + QuantityValue value = (QuantityValue) decinewtonspermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMillimeter); } @@ -644,7 +647,7 @@ public static ForcePerLength FromDecinewtonsPerMillimeter(QuantityValue decinewt /// If value is NaN or Infinity. public static ForcePerLength FromKilogramsForcePerCentimeter(QuantityValue kilogramsforcepercentimeter) { - double value = (double) kilogramsforcepercentimeter; + QuantityValue value = (QuantityValue) kilogramsforcepercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerCentimeter); } @@ -654,7 +657,7 @@ public static ForcePerLength FromKilogramsForcePerCentimeter(QuantityValue kilog /// If value is NaN or Infinity. public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue kilogramsforcepermeter) { - double value = (double) kilogramsforcepermeter; + QuantityValue value = (QuantityValue) kilogramsforcepermeter; return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); } @@ -664,7 +667,7 @@ public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue kilogramsf /// If value is NaN or Infinity. public static ForcePerLength FromKilogramsForcePerMillimeter(QuantityValue kilogramsforcepermillimeter) { - double value = (double) kilogramsforcepermillimeter; + QuantityValue value = (QuantityValue) kilogramsforcepermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMillimeter); } @@ -674,7 +677,7 @@ public static ForcePerLength FromKilogramsForcePerMillimeter(QuantityValue kilog /// If value is NaN or Infinity. public static ForcePerLength FromKilonewtonsPerCentimeter(QuantityValue kilonewtonspercentimeter) { - double value = (double) kilonewtonspercentimeter; + QuantityValue value = (QuantityValue) kilonewtonspercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerCentimeter); } @@ -684,7 +687,7 @@ public static ForcePerLength FromKilonewtonsPerCentimeter(QuantityValue kilonewt /// If value is NaN or Infinity. public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue kilonewtonspermeter) { - double value = (double) kilonewtonspermeter; + QuantityValue value = (QuantityValue) kilonewtonspermeter; return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); } @@ -694,7 +697,7 @@ public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue kilonewtonspe /// If value is NaN or Infinity. public static ForcePerLength FromKilonewtonsPerMillimeter(QuantityValue kilonewtonspermillimeter) { - double value = (double) kilonewtonspermillimeter; + QuantityValue value = (QuantityValue) kilonewtonspermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMillimeter); } @@ -704,7 +707,7 @@ public static ForcePerLength FromKilonewtonsPerMillimeter(QuantityValue kilonewt /// If value is NaN or Infinity. public static ForcePerLength FromKilopoundsForcePerFoot(QuantityValue kilopoundsforceperfoot) { - double value = (double) kilopoundsforceperfoot; + QuantityValue value = (QuantityValue) kilopoundsforceperfoot; return new ForcePerLength(value, ForcePerLengthUnit.KilopoundForcePerFoot); } @@ -714,7 +717,7 @@ public static ForcePerLength FromKilopoundsForcePerFoot(QuantityValue kilopounds /// If value is NaN or Infinity. public static ForcePerLength FromKilopoundsForcePerInch(QuantityValue kilopoundsforceperinch) { - double value = (double) kilopoundsforceperinch; + QuantityValue value = (QuantityValue) kilopoundsforceperinch; return new ForcePerLength(value, ForcePerLengthUnit.KilopoundForcePerInch); } @@ -724,7 +727,7 @@ public static ForcePerLength FromKilopoundsForcePerInch(QuantityValue kilopounds /// If value is NaN or Infinity. public static ForcePerLength FromMeganewtonsPerCentimeter(QuantityValue meganewtonspercentimeter) { - double value = (double) meganewtonspercentimeter; + QuantityValue value = (QuantityValue) meganewtonspercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerCentimeter); } @@ -734,7 +737,7 @@ public static ForcePerLength FromMeganewtonsPerCentimeter(QuantityValue meganewt /// If value is NaN or Infinity. public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue meganewtonspermeter) { - double value = (double) meganewtonspermeter; + QuantityValue value = (QuantityValue) meganewtonspermeter; return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); } @@ -744,7 +747,7 @@ public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue meganewtonspe /// If value is NaN or Infinity. public static ForcePerLength FromMeganewtonsPerMillimeter(QuantityValue meganewtonspermillimeter) { - double value = (double) meganewtonspermillimeter; + QuantityValue value = (QuantityValue) meganewtonspermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMillimeter); } @@ -754,7 +757,7 @@ public static ForcePerLength FromMeganewtonsPerMillimeter(QuantityValue meganewt /// If value is NaN or Infinity. public static ForcePerLength FromMicronewtonsPerCentimeter(QuantityValue micronewtonspercentimeter) { - double value = (double) micronewtonspercentimeter; + QuantityValue value = (QuantityValue) micronewtonspercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerCentimeter); } @@ -764,7 +767,7 @@ public static ForcePerLength FromMicronewtonsPerCentimeter(QuantityValue microne /// If value is NaN or Infinity. public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue micronewtonspermeter) { - double value = (double) micronewtonspermeter; + QuantityValue value = (QuantityValue) micronewtonspermeter; return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); } @@ -774,7 +777,7 @@ public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue micronewtons /// If value is NaN or Infinity. public static ForcePerLength FromMicronewtonsPerMillimeter(QuantityValue micronewtonspermillimeter) { - double value = (double) micronewtonspermillimeter; + QuantityValue value = (QuantityValue) micronewtonspermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMillimeter); } @@ -784,7 +787,7 @@ public static ForcePerLength FromMicronewtonsPerMillimeter(QuantityValue microne /// If value is NaN or Infinity. public static ForcePerLength FromMillinewtonsPerCentimeter(QuantityValue millinewtonspercentimeter) { - double value = (double) millinewtonspercentimeter; + QuantityValue value = (QuantityValue) millinewtonspercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerCentimeter); } @@ -794,7 +797,7 @@ public static ForcePerLength FromMillinewtonsPerCentimeter(QuantityValue milline /// If value is NaN or Infinity. public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue millinewtonspermeter) { - double value = (double) millinewtonspermeter; + QuantityValue value = (QuantityValue) millinewtonspermeter; return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); } @@ -804,7 +807,7 @@ public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue millinewtons /// If value is NaN or Infinity. public static ForcePerLength FromMillinewtonsPerMillimeter(QuantityValue millinewtonspermillimeter) { - double value = (double) millinewtonspermillimeter; + QuantityValue value = (QuantityValue) millinewtonspermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMillimeter); } @@ -814,7 +817,7 @@ public static ForcePerLength FromMillinewtonsPerMillimeter(QuantityValue milline /// If value is NaN or Infinity. public static ForcePerLength FromNanonewtonsPerCentimeter(QuantityValue nanonewtonspercentimeter) { - double value = (double) nanonewtonspercentimeter; + QuantityValue value = (QuantityValue) nanonewtonspercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerCentimeter); } @@ -824,7 +827,7 @@ public static ForcePerLength FromNanonewtonsPerCentimeter(QuantityValue nanonewt /// If value is NaN or Infinity. public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue nanonewtonspermeter) { - double value = (double) nanonewtonspermeter; + QuantityValue value = (QuantityValue) nanonewtonspermeter; return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); } @@ -834,7 +837,7 @@ public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue nanonewtonspe /// If value is NaN or Infinity. public static ForcePerLength FromNanonewtonsPerMillimeter(QuantityValue nanonewtonspermillimeter) { - double value = (double) nanonewtonspermillimeter; + QuantityValue value = (QuantityValue) nanonewtonspermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMillimeter); } @@ -844,7 +847,7 @@ public static ForcePerLength FromNanonewtonsPerMillimeter(QuantityValue nanonewt /// If value is NaN or Infinity. public static ForcePerLength FromNewtonsPerCentimeter(QuantityValue newtonspercentimeter) { - double value = (double) newtonspercentimeter; + QuantityValue value = (QuantityValue) newtonspercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerCentimeter); } @@ -854,7 +857,7 @@ public static ForcePerLength FromNewtonsPerCentimeter(QuantityValue newtonsperce /// If value is NaN or Infinity. public static ForcePerLength FromNewtonsPerMeter(QuantityValue newtonspermeter) { - double value = (double) newtonspermeter; + QuantityValue value = (QuantityValue) newtonspermeter; return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMeter); } @@ -864,7 +867,7 @@ public static ForcePerLength FromNewtonsPerMeter(QuantityValue newtonspermeter) /// If value is NaN or Infinity. public static ForcePerLength FromNewtonsPerMillimeter(QuantityValue newtonspermillimeter) { - double value = (double) newtonspermillimeter; + QuantityValue value = (QuantityValue) newtonspermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMillimeter); } @@ -874,7 +877,7 @@ public static ForcePerLength FromNewtonsPerMillimeter(QuantityValue newtonspermi /// If value is NaN or Infinity. public static ForcePerLength FromPoundsForcePerFoot(QuantityValue poundsforceperfoot) { - double value = (double) poundsforceperfoot; + QuantityValue value = (QuantityValue) poundsforceperfoot; return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerFoot); } @@ -884,7 +887,7 @@ public static ForcePerLength FromPoundsForcePerFoot(QuantityValue poundsforceper /// If value is NaN or Infinity. public static ForcePerLength FromPoundsForcePerInch(QuantityValue poundsforceperinch) { - double value = (double) poundsforceperinch; + QuantityValue value = (QuantityValue) poundsforceperinch; return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerInch); } @@ -894,7 +897,7 @@ public static ForcePerLength FromPoundsForcePerInch(QuantityValue poundsforceper /// If value is NaN or Infinity. public static ForcePerLength FromPoundsForcePerYard(QuantityValue poundsforceperyard) { - double value = (double) poundsforceperyard; + QuantityValue value = (QuantityValue) poundsforceperyard; return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerYard); } @@ -904,7 +907,7 @@ public static ForcePerLength FromPoundsForcePerYard(QuantityValue poundsforceper /// If value is NaN or Infinity. public static ForcePerLength FromTonnesForcePerCentimeter(QuantityValue tonnesforcepercentimeter) { - double value = (double) tonnesforcepercentimeter; + QuantityValue value = (QuantityValue) tonnesforcepercentimeter; return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerCentimeter); } @@ -914,7 +917,7 @@ public static ForcePerLength FromTonnesForcePerCentimeter(QuantityValue tonnesfo /// If value is NaN or Infinity. public static ForcePerLength FromTonnesForcePerMeter(QuantityValue tonnesforcepermeter) { - double value = (double) tonnesforcepermeter; + QuantityValue value = (QuantityValue) tonnesforcepermeter; return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerMeter); } @@ -924,7 +927,7 @@ public static ForcePerLength FromTonnesForcePerMeter(QuantityValue tonnesforcepe /// If value is NaN or Infinity. public static ForcePerLength FromTonnesForcePerMillimeter(QuantityValue tonnesforcepermillimeter) { - double value = (double) tonnesforcepermillimeter; + QuantityValue value = (QuantityValue) tonnesforcepermillimeter; return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerMillimeter); } @@ -936,7 +939,7 @@ public static ForcePerLength FromTonnesForcePerMillimeter(QuantityValue tonnesfo /// ForcePerLength unit value. public static ForcePerLength From(QuantityValue value, ForcePerLengthUnit fromUnit) { - return new ForcePerLength((double)value, fromUnit); + return new ForcePerLength((QuantityValue)value, fromUnit); } #endregion @@ -1106,25 +1109,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Force } /// Get from multiplying value and . - public static ForcePerLength operator *(double left, ForcePerLength right) + public static ForcePerLength operator *(QuantityValue left, ForcePerLength right) { return new ForcePerLength(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ForcePerLength operator *(ForcePerLength left, double right) + public static ForcePerLength operator *(ForcePerLength left, QuantityValue right) { return new ForcePerLength(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ForcePerLength operator /(ForcePerLength left, double right) + public static ForcePerLength operator /(ForcePerLength left, QuantityValue right) { return new ForcePerLength(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ForcePerLength left, ForcePerLength right) + public static QuantityValue operator /(ForcePerLength left, ForcePerLength right) { return left.NewtonsPerMeter / right.NewtonsPerMeter; } @@ -1157,6 +1160,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Force return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ForcePerLength left, ForcePerLength right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ForcePerLength left, ForcePerLength right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1169,7 +1185,29 @@ public int CompareTo(object obj) /// public int CompareTo(ForcePerLength other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ForcePerLength objForcePerLength)) + return false; + return Equals(objForcePerLength); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ForcePerLength other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1212,13 +1250,13 @@ public int CompareTo(ForcePerLength other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ForcePerLength other, double tolerance, ComparisonType comparisonType) + public bool Equals(ForcePerLength other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1229,7 +1267,7 @@ public bool Equals(ForcePerLength other, double tolerance, ComparisonType compar /// A hash code for the current ForcePerLength. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1240,17 +1278,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ForcePerLengthUnit unit) + public QuantityValue As(ForcePerLengthUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1265,12 +1302,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ForcePerLengthUnit unitAsForcePerLengthUnit)) + if (!(unit is ForcePerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForcePerLengthUnit)} is supported.", nameof(unit)); - return As(unitAsForcePerLengthUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1302,7 +1339,7 @@ public ForcePerLength ToUnit(ForcePerLengthUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (ForcePerLength)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ForcePerLengthUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1310,17 +1347,17 @@ public ForcePerLength ToUnit(ForcePerLengthUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ForcePerLengthUnit unitAsForcePerLengthUnit)) + if (!(unit is ForcePerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForcePerLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsForcePerLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1347,10 +1384,10 @@ public ForcePerLength ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ForcePerLengthUnit unit) + private QuantityValue GetValueAs(ForcePerLengthUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs index 695d03630d..190de13050 100644 --- a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The number of occurrences of a repeating event per unit time. /// [DataContract] - public partial struct Frequency : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Frequency : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -82,9 +82,9 @@ static Frequency() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Frequency(double value, FrequencyUnit unit) + public Frequency(QuantityValue value, FrequencyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -96,14 +96,14 @@ public Frequency(double value, FrequencyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Frequency(double value, UnitSystem unitSystem) + public Frequency(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -144,7 +144,10 @@ public Frequency(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -167,59 +170,59 @@ public Frequency(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BeatsPerMinute => As(FrequencyUnit.BeatPerMinute); + public QuantityValue BeatsPerMinute => As(FrequencyUnit.BeatPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BUnits => As(FrequencyUnit.BUnit); + public QuantityValue BUnits => As(FrequencyUnit.BUnit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CyclesPerHour => As(FrequencyUnit.CyclePerHour); + public QuantityValue CyclesPerHour => As(FrequencyUnit.CyclePerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); + public QuantityValue CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gigahertz => As(FrequencyUnit.Gigahertz); + public QuantityValue Gigahertz => As(FrequencyUnit.Gigahertz); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Hertz => As(FrequencyUnit.Hertz); + public QuantityValue Hertz => As(FrequencyUnit.Hertz); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilohertz => As(FrequencyUnit.Kilohertz); + public QuantityValue Kilohertz => As(FrequencyUnit.Kilohertz); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megahertz => As(FrequencyUnit.Megahertz); + public QuantityValue Megahertz => As(FrequencyUnit.Megahertz); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PerSecond => As(FrequencyUnit.PerSecond); + public QuantityValue PerSecond => As(FrequencyUnit.PerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); + public QuantityValue RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Terahertz => As(FrequencyUnit.Terahertz); + public QuantityValue Terahertz => As(FrequencyUnit.Terahertz); #endregion @@ -248,7 +251,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) // Register in unit converter: FrequencyUnit -> BaseUnit 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.BUnit, FrequencyUnit.Hertz, quantity => new Frequency(Math.Sqrt((double)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)); @@ -312,7 +315,7 @@ public static string GetAbbreviation(FrequencyUnit unit, IFormatProvider? provid /// If value is NaN or Infinity. public static Frequency FromBeatsPerMinute(QuantityValue beatsperminute) { - double value = (double) beatsperminute; + QuantityValue value = (QuantityValue) beatsperminute; return new Frequency(value, FrequencyUnit.BeatPerMinute); } @@ -322,7 +325,7 @@ public static Frequency FromBeatsPerMinute(QuantityValue beatsperminute) /// If value is NaN or Infinity. public static Frequency FromBUnits(QuantityValue bunits) { - double value = (double) bunits; + QuantityValue value = (QuantityValue) bunits; return new Frequency(value, FrequencyUnit.BUnit); } @@ -332,7 +335,7 @@ public static Frequency FromBUnits(QuantityValue bunits) /// If value is NaN or Infinity. public static Frequency FromCyclesPerHour(QuantityValue cyclesperhour) { - double value = (double) cyclesperhour; + QuantityValue value = (QuantityValue) cyclesperhour; return new Frequency(value, FrequencyUnit.CyclePerHour); } @@ -342,7 +345,7 @@ public static Frequency FromCyclesPerHour(QuantityValue cyclesperhour) /// If value is NaN or Infinity. public static Frequency FromCyclesPerMinute(QuantityValue cyclesperminute) { - double value = (double) cyclesperminute; + QuantityValue value = (QuantityValue) cyclesperminute; return new Frequency(value, FrequencyUnit.CyclePerMinute); } @@ -352,7 +355,7 @@ public static Frequency FromCyclesPerMinute(QuantityValue cyclesperminute) /// If value is NaN or Infinity. public static Frequency FromGigahertz(QuantityValue gigahertz) { - double value = (double) gigahertz; + QuantityValue value = (QuantityValue) gigahertz; return new Frequency(value, FrequencyUnit.Gigahertz); } @@ -362,7 +365,7 @@ public static Frequency FromGigahertz(QuantityValue gigahertz) /// If value is NaN or Infinity. public static Frequency FromHertz(QuantityValue hertz) { - double value = (double) hertz; + QuantityValue value = (QuantityValue) hertz; return new Frequency(value, FrequencyUnit.Hertz); } @@ -372,7 +375,7 @@ public static Frequency FromHertz(QuantityValue hertz) /// If value is NaN or Infinity. public static Frequency FromKilohertz(QuantityValue kilohertz) { - double value = (double) kilohertz; + QuantityValue value = (QuantityValue) kilohertz; return new Frequency(value, FrequencyUnit.Kilohertz); } @@ -382,7 +385,7 @@ public static Frequency FromKilohertz(QuantityValue kilohertz) /// If value is NaN or Infinity. public static Frequency FromMegahertz(QuantityValue megahertz) { - double value = (double) megahertz; + QuantityValue value = (QuantityValue) megahertz; return new Frequency(value, FrequencyUnit.Megahertz); } @@ -392,7 +395,7 @@ public static Frequency FromMegahertz(QuantityValue megahertz) /// If value is NaN or Infinity. public static Frequency FromPerSecond(QuantityValue persecond) { - double value = (double) persecond; + QuantityValue value = (QuantityValue) persecond; return new Frequency(value, FrequencyUnit.PerSecond); } @@ -402,7 +405,7 @@ public static Frequency FromPerSecond(QuantityValue persecond) /// If value is NaN or Infinity. public static Frequency FromRadiansPerSecond(QuantityValue radianspersecond) { - double value = (double) radianspersecond; + QuantityValue value = (QuantityValue) radianspersecond; return new Frequency(value, FrequencyUnit.RadianPerSecond); } @@ -412,7 +415,7 @@ public static Frequency FromRadiansPerSecond(QuantityValue radianspersecond) /// If value is NaN or Infinity. public static Frequency FromTerahertz(QuantityValue terahertz) { - double value = (double) terahertz; + QuantityValue value = (QuantityValue) terahertz; return new Frequency(value, FrequencyUnit.Terahertz); } @@ -424,7 +427,7 @@ public static Frequency FromTerahertz(QuantityValue terahertz) /// Frequency unit value. public static Frequency From(QuantityValue value, FrequencyUnit fromUnit) { - return new Frequency((double)value, fromUnit); + return new Frequency((QuantityValue)value, fromUnit); } #endregion @@ -594,25 +597,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Frequ } /// Get from multiplying value and . - public static Frequency operator *(double left, Frequency right) + public static Frequency operator *(QuantityValue left, Frequency right) { return new Frequency(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Frequency operator *(Frequency left, double right) + public static Frequency operator *(Frequency left, QuantityValue right) { return new Frequency(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Frequency operator /(Frequency left, double right) + public static Frequency operator /(Frequency left, QuantityValue right) { return new Frequency(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Frequency left, Frequency right) + public static QuantityValue operator /(Frequency left, Frequency right) { return left.Hertz / right.Hertz; } @@ -645,6 +648,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Frequ return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Frequency left, Frequency right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Frequency left, Frequency right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -657,7 +673,29 @@ public int CompareTo(object obj) /// public int CompareTo(Frequency other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Frequency objFrequency)) + return false; + return Equals(objFrequency); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Frequency other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -700,13 +738,13 @@ public int CompareTo(Frequency other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Frequency other, double tolerance, ComparisonType comparisonType) + public bool Equals(Frequency other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -717,7 +755,7 @@ public bool Equals(Frequency other, double tolerance, ComparisonType comparisonT /// A hash code for the current Frequency. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -728,17 +766,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(FrequencyUnit unit) + public QuantityValue As(FrequencyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -753,12 +790,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is FrequencyUnit unitAsFrequencyUnit)) + if (!(unit is FrequencyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FrequencyUnit)} is supported.", nameof(unit)); - return As(unitAsFrequencyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -790,7 +827,7 @@ public Frequency ToUnit(FrequencyUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Frequency)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(FrequencyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -798,17 +835,17 @@ public Frequency ToUnit(FrequencyUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is FrequencyUnit unitAsFrequencyUnit)) + if (!(unit is FrequencyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FrequencyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsFrequencyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -835,10 +872,10 @@ public Frequency ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(FrequencyUnit unit) + private QuantityValue GetValueAs(FrequencyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs index c2a2cfcf02..279770ce94 100644 --- a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Fuel_efficiency /// [DataContract] - public partial struct FuelEfficiency : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct FuelEfficiency : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -78,9 +78,9 @@ static FuelEfficiency() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public FuelEfficiency(double value, FuelEfficiencyUnit unit) + public FuelEfficiency(QuantityValue value, FuelEfficiencyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -92,14 +92,14 @@ public FuelEfficiency(double value, FuelEfficiencyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public FuelEfficiency(double value, UnitSystem unitSystem) + public FuelEfficiency(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -140,7 +140,10 @@ public FuelEfficiency(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -163,24 +166,24 @@ public FuelEfficiency(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilometersPerLiters => As(FuelEfficiencyUnit.KilometerPerLiter); + public QuantityValue KilometersPerLiters => As(FuelEfficiencyUnit.KilometerPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPer100Kilometers => As(FuelEfficiencyUnit.LiterPer100Kilometers); + public QuantityValue LitersPer100Kilometers => As(FuelEfficiencyUnit.LiterPer100Kilometers); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilesPerUkGallon => As(FuelEfficiencyUnit.MilePerUkGallon); + public QuantityValue MilesPerUkGallon => As(FuelEfficiencyUnit.MilePerUkGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilesPerUsGallon => As(FuelEfficiencyUnit.MilePerUsGallon); + public QuantityValue MilesPerUsGallon => As(FuelEfficiencyUnit.MilePerUsGallon); #endregion @@ -245,7 +248,7 @@ public static string GetAbbreviation(FuelEfficiencyUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static FuelEfficiency FromKilometersPerLiters(QuantityValue kilometersperliters) { - double value = (double) kilometersperliters; + QuantityValue value = (QuantityValue) kilometersperliters; return new FuelEfficiency(value, FuelEfficiencyUnit.KilometerPerLiter); } @@ -255,7 +258,7 @@ public static FuelEfficiency FromKilometersPerLiters(QuantityValue kilometersper /// If value is NaN or Infinity. public static FuelEfficiency FromLitersPer100Kilometers(QuantityValue litersper100kilometers) { - double value = (double) litersper100kilometers; + QuantityValue value = (QuantityValue) litersper100kilometers; return new FuelEfficiency(value, FuelEfficiencyUnit.LiterPer100Kilometers); } @@ -265,7 +268,7 @@ public static FuelEfficiency FromLitersPer100Kilometers(QuantityValue litersper1 /// If value is NaN or Infinity. public static FuelEfficiency FromMilesPerUkGallon(QuantityValue milesperukgallon) { - double value = (double) milesperukgallon; + QuantityValue value = (QuantityValue) milesperukgallon; return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUkGallon); } @@ -275,7 +278,7 @@ public static FuelEfficiency FromMilesPerUkGallon(QuantityValue milesperukgallon /// If value is NaN or Infinity. public static FuelEfficiency FromMilesPerUsGallon(QuantityValue milesperusgallon) { - double value = (double) milesperusgallon; + QuantityValue value = (QuantityValue) milesperusgallon; return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUsGallon); } @@ -287,7 +290,7 @@ public static FuelEfficiency FromMilesPerUsGallon(QuantityValue milesperusgallon /// FuelEfficiency unit value. public static FuelEfficiency From(QuantityValue value, FuelEfficiencyUnit fromUnit) { - return new FuelEfficiency((double)value, fromUnit); + return new FuelEfficiency((QuantityValue)value, fromUnit); } #endregion @@ -457,25 +460,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out FuelE } /// Get from multiplying value and . - public static FuelEfficiency operator *(double left, FuelEfficiency right) + public static FuelEfficiency operator *(QuantityValue left, FuelEfficiency right) { return new FuelEfficiency(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static FuelEfficiency operator *(FuelEfficiency left, double right) + public static FuelEfficiency operator *(FuelEfficiency left, QuantityValue right) { return new FuelEfficiency(left.Value * right, left.Unit); } /// Get from dividing by value. - public static FuelEfficiency operator /(FuelEfficiency left, double right) + public static FuelEfficiency operator /(FuelEfficiency left, QuantityValue right) { return new FuelEfficiency(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(FuelEfficiency left, FuelEfficiency right) + public static QuantityValue operator /(FuelEfficiency left, FuelEfficiency right) { return left.LitersPer100Kilometers / right.LitersPer100Kilometers; } @@ -508,6 +511,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out FuelE return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(FuelEfficiency left, FuelEfficiency right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(FuelEfficiency left, FuelEfficiency right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -520,7 +536,29 @@ public int CompareTo(object obj) /// public int CompareTo(FuelEfficiency other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is FuelEfficiency objFuelEfficiency)) + return false; + return Equals(objFuelEfficiency); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(FuelEfficiency other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -563,13 +601,13 @@ public int CompareTo(FuelEfficiency other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(FuelEfficiency other, double tolerance, ComparisonType comparisonType) + public bool Equals(FuelEfficiency other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -580,7 +618,7 @@ public bool Equals(FuelEfficiency other, double tolerance, ComparisonType compar /// A hash code for the current FuelEfficiency. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -591,17 +629,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(FuelEfficiencyUnit unit) + public QuantityValue As(FuelEfficiencyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -616,12 +653,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is FuelEfficiencyUnit unitAsFuelEfficiencyUnit)) + if (!(unit is FuelEfficiencyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); - return As(unitAsFuelEfficiencyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -653,7 +690,7 @@ public FuelEfficiency ToUnit(FuelEfficiencyUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (FuelEfficiency)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(FuelEfficiencyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -661,17 +698,17 @@ public FuelEfficiency ToUnit(FuelEfficiencyUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is FuelEfficiencyUnit unitAsFuelEfficiencyUnit)) + if (!(unit is FuelEfficiencyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsFuelEfficiencyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -698,10 +735,10 @@ public FuelEfficiency ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(FuelEfficiencyUnit unit) + private QuantityValue GetValueAs(FuelEfficiencyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs index 2b0f9a5278..be4d11404e 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Heat flux is the flow of energy per unit of area per unit of time /// [DataContract] - public partial struct HeatFlux : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct HeatFlux : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -89,9 +89,9 @@ static HeatFlux() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public HeatFlux(double value, HeatFluxUnit unit) + public HeatFlux(QuantityValue value, HeatFluxUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -103,14 +103,14 @@ public HeatFlux(double value, HeatFluxUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public HeatFlux(double value, UnitSystem unitSystem) + public HeatFlux(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -151,7 +151,10 @@ public HeatFlux(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -174,94 +177,94 @@ public HeatFlux(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BtusPerHourSquareFoot => As(HeatFluxUnit.BtuPerHourSquareFoot); + public QuantityValue BtusPerHourSquareFoot => As(HeatFluxUnit.BtuPerHourSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BtusPerMinuteSquareFoot => As(HeatFluxUnit.BtuPerMinuteSquareFoot); + public QuantityValue BtusPerMinuteSquareFoot => As(HeatFluxUnit.BtuPerMinuteSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BtusPerSecondSquareFoot => As(HeatFluxUnit.BtuPerSecondSquareFoot); + public QuantityValue BtusPerSecondSquareFoot => As(HeatFluxUnit.BtuPerSecondSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BtusPerSecondSquareInch => As(HeatFluxUnit.BtuPerSecondSquareInch); + public QuantityValue BtusPerSecondSquareInch => As(HeatFluxUnit.BtuPerSecondSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); + public QuantityValue CaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentiwattsPerSquareMeter => As(HeatFluxUnit.CentiwattPerSquareMeter); + public QuantityValue CentiwattsPerSquareMeter => As(HeatFluxUnit.CentiwattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DeciwattsPerSquareMeter => As(HeatFluxUnit.DeciwattPerSquareMeter); + public QuantityValue DeciwattsPerSquareMeter => As(HeatFluxUnit.DeciwattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilocaloriesPerHourSquareMeter => As(HeatFluxUnit.KilocaloriePerHourSquareMeter); + public QuantityValue KilocaloriesPerHourSquareMeter => As(HeatFluxUnit.KilocaloriePerHourSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilocaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); + public QuantityValue KilocaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerSquareMeter => As(HeatFluxUnit.KilowattPerSquareMeter); + public QuantityValue KilowattsPerSquareMeter => As(HeatFluxUnit.KilowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrowattsPerSquareMeter => As(HeatFluxUnit.MicrowattPerSquareMeter); + public QuantityValue MicrowattsPerSquareMeter => As(HeatFluxUnit.MicrowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerSquareMeter => As(HeatFluxUnit.MilliwattPerSquareMeter); + public QuantityValue MilliwattsPerSquareMeter => As(HeatFluxUnit.MilliwattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanowattsPerSquareMeter => As(HeatFluxUnit.NanowattPerSquareMeter); + public QuantityValue NanowattsPerSquareMeter => As(HeatFluxUnit.NanowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerFootSecond => As(HeatFluxUnit.PoundForcePerFootSecond); + public QuantityValue PoundsForcePerFootSecond => As(HeatFluxUnit.PoundForcePerFootSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerSecondCubed => As(HeatFluxUnit.PoundPerSecondCubed); + public QuantityValue PoundsPerSecondCubed => As(HeatFluxUnit.PoundPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerSquareFoot => As(HeatFluxUnit.WattPerSquareFoot); + public QuantityValue WattsPerSquareFoot => As(HeatFluxUnit.WattPerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerSquareInch => As(HeatFluxUnit.WattPerSquareInch); + public QuantityValue WattsPerSquareInch => As(HeatFluxUnit.WattPerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerSquareMeter => As(HeatFluxUnit.WattPerSquareMeter); + public QuantityValue WattsPerSquareMeter => As(HeatFluxUnit.WattPerSquareMeter); #endregion @@ -368,7 +371,7 @@ public static string GetAbbreviation(HeatFluxUnit unit, IFormatProvider? provide /// If value is NaN or Infinity. public static HeatFlux FromBtusPerHourSquareFoot(QuantityValue btusperhoursquarefoot) { - double value = (double) btusperhoursquarefoot; + QuantityValue value = (QuantityValue) btusperhoursquarefoot; return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); } @@ -378,7 +381,7 @@ public static HeatFlux FromBtusPerHourSquareFoot(QuantityValue btusperhoursquare /// If value is NaN or Infinity. public static HeatFlux FromBtusPerMinuteSquareFoot(QuantityValue btusperminutesquarefoot) { - double value = (double) btusperminutesquarefoot; + QuantityValue value = (QuantityValue) btusperminutesquarefoot; return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); } @@ -388,7 +391,7 @@ public static HeatFlux FromBtusPerMinuteSquareFoot(QuantityValue btusperminutesq /// If value is NaN or Infinity. public static HeatFlux FromBtusPerSecondSquareFoot(QuantityValue btuspersecondsquarefoot) { - double value = (double) btuspersecondsquarefoot; + QuantityValue value = (QuantityValue) btuspersecondsquarefoot; return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); } @@ -398,7 +401,7 @@ public static HeatFlux FromBtusPerSecondSquareFoot(QuantityValue btuspersecondsq /// If value is NaN or Infinity. public static HeatFlux FromBtusPerSecondSquareInch(QuantityValue btuspersecondsquareinch) { - double value = (double) btuspersecondsquareinch; + QuantityValue value = (QuantityValue) btuspersecondsquareinch; return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); } @@ -408,7 +411,7 @@ public static HeatFlux FromBtusPerSecondSquareInch(QuantityValue btuspersecondsq /// If value is NaN or Infinity. public static HeatFlux FromCaloriesPerSecondSquareCentimeter(QuantityValue caloriespersecondsquarecentimeter) { - double value = (double) caloriespersecondsquarecentimeter; + QuantityValue value = (QuantityValue) caloriespersecondsquarecentimeter; return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); } @@ -418,7 +421,7 @@ public static HeatFlux FromCaloriesPerSecondSquareCentimeter(QuantityValue calor /// If value is NaN or Infinity. public static HeatFlux FromCentiwattsPerSquareMeter(QuantityValue centiwattspersquaremeter) { - double value = (double) centiwattspersquaremeter; + QuantityValue value = (QuantityValue) centiwattspersquaremeter; return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); } @@ -428,7 +431,7 @@ public static HeatFlux FromCentiwattsPerSquareMeter(QuantityValue centiwattspers /// If value is NaN or Infinity. public static HeatFlux FromDeciwattsPerSquareMeter(QuantityValue deciwattspersquaremeter) { - double value = (double) deciwattspersquaremeter; + QuantityValue value = (QuantityValue) deciwattspersquaremeter; return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); } @@ -438,7 +441,7 @@ public static HeatFlux FromDeciwattsPerSquareMeter(QuantityValue deciwattspersqu /// If value is NaN or Infinity. public static HeatFlux FromKilocaloriesPerHourSquareMeter(QuantityValue kilocaloriesperhoursquaremeter) { - double value = (double) kilocaloriesperhoursquaremeter; + QuantityValue value = (QuantityValue) kilocaloriesperhoursquaremeter; return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); } @@ -448,7 +451,7 @@ public static HeatFlux FromKilocaloriesPerHourSquareMeter(QuantityValue kilocalo /// If value is NaN or Infinity. public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(QuantityValue kilocaloriespersecondsquarecentimeter) { - double value = (double) kilocaloriespersecondsquarecentimeter; + QuantityValue value = (QuantityValue) kilocaloriespersecondsquarecentimeter; return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); } @@ -458,7 +461,7 @@ public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(QuantityValue k /// If value is NaN or Infinity. public static HeatFlux FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) { - double value = (double) kilowattspersquaremeter; + QuantityValue value = (QuantityValue) kilowattspersquaremeter; return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); } @@ -468,7 +471,7 @@ public static HeatFlux FromKilowattsPerSquareMeter(QuantityValue kilowattspersqu /// If value is NaN or Infinity. public static HeatFlux FromMicrowattsPerSquareMeter(QuantityValue microwattspersquaremeter) { - double value = (double) microwattspersquaremeter; + QuantityValue value = (QuantityValue) microwattspersquaremeter; return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); } @@ -478,7 +481,7 @@ public static HeatFlux FromMicrowattsPerSquareMeter(QuantityValue microwattspers /// If value is NaN or Infinity. public static HeatFlux FromMilliwattsPerSquareMeter(QuantityValue milliwattspersquaremeter) { - double value = (double) milliwattspersquaremeter; + QuantityValue value = (QuantityValue) milliwattspersquaremeter; return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); } @@ -488,7 +491,7 @@ public static HeatFlux FromMilliwattsPerSquareMeter(QuantityValue milliwattspers /// If value is NaN or Infinity. public static HeatFlux FromNanowattsPerSquareMeter(QuantityValue nanowattspersquaremeter) { - double value = (double) nanowattspersquaremeter; + QuantityValue value = (QuantityValue) nanowattspersquaremeter; return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); } @@ -498,7 +501,7 @@ public static HeatFlux FromNanowattsPerSquareMeter(QuantityValue nanowattspersqu /// If value is NaN or Infinity. public static HeatFlux FromPoundsForcePerFootSecond(QuantityValue poundsforceperfootsecond) { - double value = (double) poundsforceperfootsecond; + QuantityValue value = (QuantityValue) poundsforceperfootsecond; return new HeatFlux(value, HeatFluxUnit.PoundForcePerFootSecond); } @@ -508,7 +511,7 @@ public static HeatFlux FromPoundsForcePerFootSecond(QuantityValue poundsforceper /// If value is NaN or Infinity. public static HeatFlux FromPoundsPerSecondCubed(QuantityValue poundspersecondcubed) { - double value = (double) poundspersecondcubed; + QuantityValue value = (QuantityValue) poundspersecondcubed; return new HeatFlux(value, HeatFluxUnit.PoundPerSecondCubed); } @@ -518,7 +521,7 @@ public static HeatFlux FromPoundsPerSecondCubed(QuantityValue poundspersecondcub /// If value is NaN or Infinity. public static HeatFlux FromWattsPerSquareFoot(QuantityValue wattspersquarefoot) { - double value = (double) wattspersquarefoot; + QuantityValue value = (QuantityValue) wattspersquarefoot; return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); } @@ -528,7 +531,7 @@ public static HeatFlux FromWattsPerSquareFoot(QuantityValue wattspersquarefoot) /// If value is NaN or Infinity. public static HeatFlux FromWattsPerSquareInch(QuantityValue wattspersquareinch) { - double value = (double) wattspersquareinch; + QuantityValue value = (QuantityValue) wattspersquareinch; return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); } @@ -538,7 +541,7 @@ public static HeatFlux FromWattsPerSquareInch(QuantityValue wattspersquareinch) /// If value is NaN or Infinity. public static HeatFlux FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) { - double value = (double) wattspersquaremeter; + QuantityValue value = (QuantityValue) wattspersquaremeter; return new HeatFlux(value, HeatFluxUnit.WattPerSquareMeter); } @@ -550,7 +553,7 @@ public static HeatFlux FromWattsPerSquareMeter(QuantityValue wattspersquaremeter /// HeatFlux unit value. public static HeatFlux From(QuantityValue value, HeatFluxUnit fromUnit) { - return new HeatFlux((double)value, fromUnit); + return new HeatFlux((QuantityValue)value, fromUnit); } #endregion @@ -720,25 +723,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatF } /// Get from multiplying value and . - public static HeatFlux operator *(double left, HeatFlux right) + public static HeatFlux operator *(QuantityValue left, HeatFlux right) { return new HeatFlux(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static HeatFlux operator *(HeatFlux left, double right) + public static HeatFlux operator *(HeatFlux left, QuantityValue right) { return new HeatFlux(left.Value * right, left.Unit); } /// Get from dividing by value. - public static HeatFlux operator /(HeatFlux left, double right) + public static HeatFlux operator /(HeatFlux left, QuantityValue right) { return new HeatFlux(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(HeatFlux left, HeatFlux right) + public static QuantityValue operator /(HeatFlux left, HeatFlux right) { return left.WattsPerSquareMeter / right.WattsPerSquareMeter; } @@ -771,6 +774,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatF return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(HeatFlux left, HeatFlux right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(HeatFlux left, HeatFlux right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -783,7 +799,29 @@ public int CompareTo(object obj) /// public int CompareTo(HeatFlux other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is HeatFlux objHeatFlux)) + return false; + return Equals(objHeatFlux); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(HeatFlux other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -826,13 +864,13 @@ public int CompareTo(HeatFlux other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(HeatFlux other, double tolerance, ComparisonType comparisonType) + public bool Equals(HeatFlux other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -843,7 +881,7 @@ public bool Equals(HeatFlux other, double tolerance, ComparisonType comparisonTy /// A hash code for the current HeatFlux. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -854,17 +892,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(HeatFluxUnit unit) + public QuantityValue As(HeatFluxUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -879,12 +916,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is HeatFluxUnit unitAsHeatFluxUnit)) + if (!(unit is HeatFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatFluxUnit)} is supported.", nameof(unit)); - return As(unitAsHeatFluxUnit); + return (QuantityValue)As(typedUnit); } /// @@ -916,7 +953,7 @@ public HeatFlux ToUnit(HeatFluxUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (HeatFlux)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(HeatFluxUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -924,17 +961,17 @@ public HeatFlux ToUnit(HeatFluxUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is HeatFluxUnit unitAsHeatFluxUnit)) + if (!(unit is HeatFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatFluxUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsHeatFluxUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -961,10 +998,10 @@ public HeatFlux ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(HeatFluxUnit unit) + private QuantityValue GetValueAs(HeatFluxUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs index 2e7f448c7b..39919d552c 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT) /// [DataContract] - public partial struct HeatTransferCoefficient : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct HeatTransferCoefficient : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -74,9 +74,9 @@ static HeatTransferCoefficient() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public HeatTransferCoefficient(double value, HeatTransferCoefficientUnit unit) + public HeatTransferCoefficient(QuantityValue value, HeatTransferCoefficientUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -88,14 +88,14 @@ public HeatTransferCoefficient(double value, HeatTransferCoefficientUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public HeatTransferCoefficient(double value, UnitSystem unitSystem) + public HeatTransferCoefficient(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -136,7 +136,10 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -159,19 +162,19 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BtusPerSquareFootDegreeFahrenheit => As(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit); + public QuantityValue BtusPerSquareFootDegreeFahrenheit => As(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + public QuantityValue WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); + public QuantityValue WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); #endregion @@ -233,7 +236,7 @@ public static string GetAbbreviation(HeatTransferCoefficientUnit unit, IFormatPr /// If value is NaN or Infinity. public static HeatTransferCoefficient FromBtusPerSquareFootDegreeFahrenheit(QuantityValue btuspersquarefootdegreefahrenheit) { - double value = (double) btuspersquarefootdegreefahrenheit; + QuantityValue value = (QuantityValue) btuspersquarefootdegreefahrenheit; return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit); } @@ -243,7 +246,7 @@ public static HeatTransferCoefficient FromBtusPerSquareFootDegreeFahrenheit(Quan /// If value is NaN or Infinity. public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(QuantityValue wattspersquaremetercelsius) { - double value = (double) wattspersquaremetercelsius; + QuantityValue value = (QuantityValue) wattspersquaremetercelsius; return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); } @@ -253,7 +256,7 @@ public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(QuantityVal /// If value is NaN or Infinity. public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(QuantityValue wattspersquaremeterkelvin) { - double value = (double) wattspersquaremeterkelvin; + QuantityValue value = (QuantityValue) wattspersquaremeterkelvin; return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); } @@ -265,7 +268,7 @@ public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(QuantityValu /// HeatTransferCoefficient unit value. public static HeatTransferCoefficient From(QuantityValue value, HeatTransferCoefficientUnit fromUnit) { - return new HeatTransferCoefficient((double)value, fromUnit); + return new HeatTransferCoefficient((QuantityValue)value, fromUnit); } #endregion @@ -435,25 +438,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatT } /// Get from multiplying value and . - public static HeatTransferCoefficient operator *(double left, HeatTransferCoefficient right) + public static HeatTransferCoefficient operator *(QuantityValue left, HeatTransferCoefficient right) { return new HeatTransferCoefficient(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static HeatTransferCoefficient operator *(HeatTransferCoefficient left, double right) + public static HeatTransferCoefficient operator *(HeatTransferCoefficient left, QuantityValue right) { return new HeatTransferCoefficient(left.Value * right, left.Unit); } /// Get from dividing by value. - public static HeatTransferCoefficient operator /(HeatTransferCoefficient left, double right) + public static HeatTransferCoefficient operator /(HeatTransferCoefficient left, QuantityValue right) { return new HeatTransferCoefficient(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(HeatTransferCoefficient left, HeatTransferCoefficient right) + public static QuantityValue operator /(HeatTransferCoefficient left, HeatTransferCoefficient right) { return left.WattsPerSquareMeterKelvin / right.WattsPerSquareMeterKelvin; } @@ -486,6 +489,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatT return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -498,7 +514,29 @@ public int CompareTo(object obj) /// public int CompareTo(HeatTransferCoefficient other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is HeatTransferCoefficient objHeatTransferCoefficient)) + return false; + return Equals(objHeatTransferCoefficient); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(HeatTransferCoefficient other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -541,13 +579,13 @@ public int CompareTo(HeatTransferCoefficient other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(HeatTransferCoefficient other, double tolerance, ComparisonType comparisonType) + public bool Equals(HeatTransferCoefficient other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -558,7 +596,7 @@ public bool Equals(HeatTransferCoefficient other, double tolerance, ComparisonTy /// A hash code for the current HeatTransferCoefficient. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -569,17 +607,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(HeatTransferCoefficientUnit unit) + public QuantityValue As(HeatTransferCoefficientUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -594,12 +631,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is HeatTransferCoefficientUnit unitAsHeatTransferCoefficientUnit)) + if (!(unit is HeatTransferCoefficientUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatTransferCoefficientUnit)} is supported.", nameof(unit)); - return As(unitAsHeatTransferCoefficientUnit); + return (QuantityValue)As(typedUnit); } /// @@ -631,7 +668,7 @@ public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit, UnitConv var converted = conversionFunction(this); return (HeatTransferCoefficient)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(HeatTransferCoefficientUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -639,17 +676,17 @@ public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit, UnitConv } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is HeatTransferCoefficientUnit unitAsHeatTransferCoefficientUnit)) + if (!(unit is HeatTransferCoefficientUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatTransferCoefficientUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsHeatTransferCoefficientUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -676,10 +713,10 @@ public HeatTransferCoefficient ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(HeatTransferCoefficientUnit unit) + private QuantityValue GetValueAs(HeatTransferCoefficientUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs index 304d11ab4d..66cc8c75f6 100644 --- a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Illuminance /// [DataContract] - public partial struct Illuminance : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Illuminance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -78,9 +78,9 @@ static Illuminance() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Illuminance(double value, IlluminanceUnit unit) + public Illuminance(QuantityValue value, IlluminanceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -92,14 +92,14 @@ public Illuminance(double value, IlluminanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Illuminance(double value, UnitSystem unitSystem) + public Illuminance(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -140,7 +140,10 @@ public Illuminance(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -163,24 +166,24 @@ public Illuminance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilolux => As(IlluminanceUnit.Kilolux); + public QuantityValue Kilolux => As(IlluminanceUnit.Kilolux); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Lux => As(IlluminanceUnit.Lux); + public QuantityValue Lux => As(IlluminanceUnit.Lux); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megalux => As(IlluminanceUnit.Megalux); + public QuantityValue Megalux => As(IlluminanceUnit.Megalux); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millilux => As(IlluminanceUnit.Millilux); + public QuantityValue Millilux => As(IlluminanceUnit.Millilux); #endregion @@ -245,7 +248,7 @@ public static string GetAbbreviation(IlluminanceUnit unit, IFormatProvider? prov /// If value is NaN or Infinity. public static Illuminance FromKilolux(QuantityValue kilolux) { - double value = (double) kilolux; + QuantityValue value = (QuantityValue) kilolux; return new Illuminance(value, IlluminanceUnit.Kilolux); } @@ -255,7 +258,7 @@ public static Illuminance FromKilolux(QuantityValue kilolux) /// If value is NaN or Infinity. public static Illuminance FromLux(QuantityValue lux) { - double value = (double) lux; + QuantityValue value = (QuantityValue) lux; return new Illuminance(value, IlluminanceUnit.Lux); } @@ -265,7 +268,7 @@ public static Illuminance FromLux(QuantityValue lux) /// If value is NaN or Infinity. public static Illuminance FromMegalux(QuantityValue megalux) { - double value = (double) megalux; + QuantityValue value = (QuantityValue) megalux; return new Illuminance(value, IlluminanceUnit.Megalux); } @@ -275,7 +278,7 @@ public static Illuminance FromMegalux(QuantityValue megalux) /// If value is NaN or Infinity. public static Illuminance FromMillilux(QuantityValue millilux) { - double value = (double) millilux; + QuantityValue value = (QuantityValue) millilux; return new Illuminance(value, IlluminanceUnit.Millilux); } @@ -287,7 +290,7 @@ public static Illuminance FromMillilux(QuantityValue millilux) /// Illuminance unit value. public static Illuminance From(QuantityValue value, IlluminanceUnit fromUnit) { - return new Illuminance((double)value, fromUnit); + return new Illuminance((QuantityValue)value, fromUnit); } #endregion @@ -457,25 +460,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Illum } /// Get from multiplying value and . - public static Illuminance operator *(double left, Illuminance right) + public static Illuminance operator *(QuantityValue left, Illuminance right) { return new Illuminance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Illuminance operator *(Illuminance left, double right) + public static Illuminance operator *(Illuminance left, QuantityValue right) { return new Illuminance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Illuminance operator /(Illuminance left, double right) + public static Illuminance operator /(Illuminance left, QuantityValue right) { return new Illuminance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Illuminance left, Illuminance right) + public static QuantityValue operator /(Illuminance left, Illuminance right) { return left.Lux / right.Lux; } @@ -508,6 +511,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Illum return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Illuminance left, Illuminance right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Illuminance left, Illuminance right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -520,7 +536,29 @@ public int CompareTo(object obj) /// public int CompareTo(Illuminance other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Illuminance objIlluminance)) + return false; + return Equals(objIlluminance); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Illuminance other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -563,13 +601,13 @@ public int CompareTo(Illuminance other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Illuminance other, double tolerance, ComparisonType comparisonType) + public bool Equals(Illuminance other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -580,7 +618,7 @@ public bool Equals(Illuminance other, double tolerance, ComparisonType compariso /// A hash code for the current Illuminance. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -591,17 +629,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(IlluminanceUnit unit) + public QuantityValue As(IlluminanceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -616,12 +653,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is IlluminanceUnit unitAsIlluminanceUnit)) + if (!(unit is IlluminanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IlluminanceUnit)} is supported.", nameof(unit)); - return As(unitAsIlluminanceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -653,7 +690,7 @@ public Illuminance ToUnit(IlluminanceUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Illuminance)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(IlluminanceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -661,17 +698,17 @@ public Illuminance ToUnit(IlluminanceUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is IlluminanceUnit unitAsIlluminanceUnit)) + if (!(unit is IlluminanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IlluminanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsIlluminanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -698,10 +735,10 @@ public Illuminance ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(IlluminanceUnit unit) + private QuantityValue GetValueAs(IlluminanceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Information.g.cs b/UnitsNet/GeneratedCode/Quantities/Information.g.cs index 880f4a52fb..1c0f90b38f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Information.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Information.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. /// [DataContract] - public partial struct Information : IQuantity, IDecimalQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Information : IQuantity, IDecimalQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly decimal _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -97,7 +97,7 @@ static Information() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Information(decimal value, InformationUnit unit) + public Information(QuantityValue value, InformationUnit unit) { _value = value; _unit = unit; @@ -111,7 +111,7 @@ public Information(decimal value, InformationUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Information(decimal value, UnitSystem unitSystem) + public Information(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -159,12 +159,13 @@ public Information(decimal value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public decimal Value => _value; + public QuantityValue Value => _value; - double IQuantity.Value => (double) _value; + /// + QuantityValue IQuantity.Value => _value; /// - decimal IDecimalQuantity.Value => _value; + decimal IDecimalQuantity.Value => (decimal)_value; Enum IQuantity.Unit => Unit; @@ -187,134 +188,134 @@ public Information(decimal value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Bits => As(InformationUnit.Bit); + public QuantityValue Bits => As(InformationUnit.Bit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Bytes => As(InformationUnit.Byte); + public QuantityValue Bytes => As(InformationUnit.Byte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Exabits => As(InformationUnit.Exabit); + public QuantityValue Exabits => As(InformationUnit.Exabit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Exabytes => As(InformationUnit.Exabyte); + public QuantityValue Exabytes => As(InformationUnit.Exabyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Exbibits => As(InformationUnit.Exbibit); + public QuantityValue Exbibits => As(InformationUnit.Exbibit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Exbibytes => As(InformationUnit.Exbibyte); + public QuantityValue Exbibytes => As(InformationUnit.Exbibyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gibibits => As(InformationUnit.Gibibit); + public QuantityValue Gibibits => As(InformationUnit.Gibibit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gibibytes => As(InformationUnit.Gibibyte); + public QuantityValue Gibibytes => As(InformationUnit.Gibibyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gigabits => As(InformationUnit.Gigabit); + public QuantityValue Gigabits => As(InformationUnit.Gigabit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gigabytes => As(InformationUnit.Gigabyte); + public QuantityValue Gigabytes => As(InformationUnit.Gigabyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kibibits => As(InformationUnit.Kibibit); + public QuantityValue Kibibits => As(InformationUnit.Kibibit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kibibytes => As(InformationUnit.Kibibyte); + public QuantityValue Kibibytes => As(InformationUnit.Kibibyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilobits => As(InformationUnit.Kilobit); + public QuantityValue Kilobits => As(InformationUnit.Kilobit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilobytes => As(InformationUnit.Kilobyte); + public QuantityValue Kilobytes => As(InformationUnit.Kilobyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Mebibits => As(InformationUnit.Mebibit); + public QuantityValue Mebibits => As(InformationUnit.Mebibit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Mebibytes => As(InformationUnit.Mebibyte); + public QuantityValue Mebibytes => As(InformationUnit.Mebibyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megabits => As(InformationUnit.Megabit); + public QuantityValue Megabits => As(InformationUnit.Megabit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megabytes => As(InformationUnit.Megabyte); + public QuantityValue Megabytes => As(InformationUnit.Megabyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Pebibits => As(InformationUnit.Pebibit); + public QuantityValue Pebibits => As(InformationUnit.Pebibit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Pebibytes => As(InformationUnit.Pebibyte); + public QuantityValue Pebibytes => As(InformationUnit.Pebibyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Petabits => As(InformationUnit.Petabit); + public QuantityValue Petabits => As(InformationUnit.Petabit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Petabytes => As(InformationUnit.Petabyte); + public QuantityValue Petabytes => As(InformationUnit.Petabyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Tebibits => As(InformationUnit.Tebibit); + public QuantityValue Tebibits => As(InformationUnit.Tebibit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Tebibytes => As(InformationUnit.Tebibyte); + public QuantityValue Tebibytes => As(InformationUnit.Tebibyte); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Terabits => As(InformationUnit.Terabit); + public QuantityValue Terabits => As(InformationUnit.Terabit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Terabytes => As(InformationUnit.Terabyte); + public QuantityValue Terabytes => As(InformationUnit.Terabyte); #endregion @@ -445,7 +446,7 @@ public static string GetAbbreviation(InformationUnit unit, IFormatProvider? prov /// If value is NaN or Infinity. public static Information FromBits(QuantityValue bits) { - decimal value = (decimal) bits; + QuantityValue value = (QuantityValue) bits; return new Information(value, InformationUnit.Bit); } @@ -455,7 +456,7 @@ public static Information FromBits(QuantityValue bits) /// If value is NaN or Infinity. public static Information FromBytes(QuantityValue bytes) { - decimal value = (decimal) bytes; + QuantityValue value = (QuantityValue) bytes; return new Information(value, InformationUnit.Byte); } @@ -465,7 +466,7 @@ public static Information FromBytes(QuantityValue bytes) /// If value is NaN or Infinity. public static Information FromExabits(QuantityValue exabits) { - decimal value = (decimal) exabits; + QuantityValue value = (QuantityValue) exabits; return new Information(value, InformationUnit.Exabit); } @@ -475,7 +476,7 @@ public static Information FromExabits(QuantityValue exabits) /// If value is NaN or Infinity. public static Information FromExabytes(QuantityValue exabytes) { - decimal value = (decimal) exabytes; + QuantityValue value = (QuantityValue) exabytes; return new Information(value, InformationUnit.Exabyte); } @@ -485,7 +486,7 @@ public static Information FromExabytes(QuantityValue exabytes) /// If value is NaN or Infinity. public static Information FromExbibits(QuantityValue exbibits) { - decimal value = (decimal) exbibits; + QuantityValue value = (QuantityValue) exbibits; return new Information(value, InformationUnit.Exbibit); } @@ -495,7 +496,7 @@ public static Information FromExbibits(QuantityValue exbibits) /// If value is NaN or Infinity. public static Information FromExbibytes(QuantityValue exbibytes) { - decimal value = (decimal) exbibytes; + QuantityValue value = (QuantityValue) exbibytes; return new Information(value, InformationUnit.Exbibyte); } @@ -505,7 +506,7 @@ public static Information FromExbibytes(QuantityValue exbibytes) /// If value is NaN or Infinity. public static Information FromGibibits(QuantityValue gibibits) { - decimal value = (decimal) gibibits; + QuantityValue value = (QuantityValue) gibibits; return new Information(value, InformationUnit.Gibibit); } @@ -515,7 +516,7 @@ public static Information FromGibibits(QuantityValue gibibits) /// If value is NaN or Infinity. public static Information FromGibibytes(QuantityValue gibibytes) { - decimal value = (decimal) gibibytes; + QuantityValue value = (QuantityValue) gibibytes; return new Information(value, InformationUnit.Gibibyte); } @@ -525,7 +526,7 @@ public static Information FromGibibytes(QuantityValue gibibytes) /// If value is NaN or Infinity. public static Information FromGigabits(QuantityValue gigabits) { - decimal value = (decimal) gigabits; + QuantityValue value = (QuantityValue) gigabits; return new Information(value, InformationUnit.Gigabit); } @@ -535,7 +536,7 @@ public static Information FromGigabits(QuantityValue gigabits) /// If value is NaN or Infinity. public static Information FromGigabytes(QuantityValue gigabytes) { - decimal value = (decimal) gigabytes; + QuantityValue value = (QuantityValue) gigabytes; return new Information(value, InformationUnit.Gigabyte); } @@ -545,7 +546,7 @@ public static Information FromGigabytes(QuantityValue gigabytes) /// If value is NaN or Infinity. public static Information FromKibibits(QuantityValue kibibits) { - decimal value = (decimal) kibibits; + QuantityValue value = (QuantityValue) kibibits; return new Information(value, InformationUnit.Kibibit); } @@ -555,7 +556,7 @@ public static Information FromKibibits(QuantityValue kibibits) /// If value is NaN or Infinity. public static Information FromKibibytes(QuantityValue kibibytes) { - decimal value = (decimal) kibibytes; + QuantityValue value = (QuantityValue) kibibytes; return new Information(value, InformationUnit.Kibibyte); } @@ -565,7 +566,7 @@ public static Information FromKibibytes(QuantityValue kibibytes) /// If value is NaN or Infinity. public static Information FromKilobits(QuantityValue kilobits) { - decimal value = (decimal) kilobits; + QuantityValue value = (QuantityValue) kilobits; return new Information(value, InformationUnit.Kilobit); } @@ -575,7 +576,7 @@ public static Information FromKilobits(QuantityValue kilobits) /// If value is NaN or Infinity. public static Information FromKilobytes(QuantityValue kilobytes) { - decimal value = (decimal) kilobytes; + QuantityValue value = (QuantityValue) kilobytes; return new Information(value, InformationUnit.Kilobyte); } @@ -585,7 +586,7 @@ public static Information FromKilobytes(QuantityValue kilobytes) /// If value is NaN or Infinity. public static Information FromMebibits(QuantityValue mebibits) { - decimal value = (decimal) mebibits; + QuantityValue value = (QuantityValue) mebibits; return new Information(value, InformationUnit.Mebibit); } @@ -595,7 +596,7 @@ public static Information FromMebibits(QuantityValue mebibits) /// If value is NaN or Infinity. public static Information FromMebibytes(QuantityValue mebibytes) { - decimal value = (decimal) mebibytes; + QuantityValue value = (QuantityValue) mebibytes; return new Information(value, InformationUnit.Mebibyte); } @@ -605,7 +606,7 @@ public static Information FromMebibytes(QuantityValue mebibytes) /// If value is NaN or Infinity. public static Information FromMegabits(QuantityValue megabits) { - decimal value = (decimal) megabits; + QuantityValue value = (QuantityValue) megabits; return new Information(value, InformationUnit.Megabit); } @@ -615,7 +616,7 @@ public static Information FromMegabits(QuantityValue megabits) /// If value is NaN or Infinity. public static Information FromMegabytes(QuantityValue megabytes) { - decimal value = (decimal) megabytes; + QuantityValue value = (QuantityValue) megabytes; return new Information(value, InformationUnit.Megabyte); } @@ -625,7 +626,7 @@ public static Information FromMegabytes(QuantityValue megabytes) /// If value is NaN or Infinity. public static Information FromPebibits(QuantityValue pebibits) { - decimal value = (decimal) pebibits; + QuantityValue value = (QuantityValue) pebibits; return new Information(value, InformationUnit.Pebibit); } @@ -635,7 +636,7 @@ public static Information FromPebibits(QuantityValue pebibits) /// If value is NaN or Infinity. public static Information FromPebibytes(QuantityValue pebibytes) { - decimal value = (decimal) pebibytes; + QuantityValue value = (QuantityValue) pebibytes; return new Information(value, InformationUnit.Pebibyte); } @@ -645,7 +646,7 @@ public static Information FromPebibytes(QuantityValue pebibytes) /// If value is NaN or Infinity. public static Information FromPetabits(QuantityValue petabits) { - decimal value = (decimal) petabits; + QuantityValue value = (QuantityValue) petabits; return new Information(value, InformationUnit.Petabit); } @@ -655,7 +656,7 @@ public static Information FromPetabits(QuantityValue petabits) /// If value is NaN or Infinity. public static Information FromPetabytes(QuantityValue petabytes) { - decimal value = (decimal) petabytes; + QuantityValue value = (QuantityValue) petabytes; return new Information(value, InformationUnit.Petabyte); } @@ -665,7 +666,7 @@ public static Information FromPetabytes(QuantityValue petabytes) /// If value is NaN or Infinity. public static Information FromTebibits(QuantityValue tebibits) { - decimal value = (decimal) tebibits; + QuantityValue value = (QuantityValue) tebibits; return new Information(value, InformationUnit.Tebibit); } @@ -675,7 +676,7 @@ public static Information FromTebibits(QuantityValue tebibits) /// If value is NaN or Infinity. public static Information FromTebibytes(QuantityValue tebibytes) { - decimal value = (decimal) tebibytes; + QuantityValue value = (QuantityValue) tebibytes; return new Information(value, InformationUnit.Tebibyte); } @@ -685,7 +686,7 @@ public static Information FromTebibytes(QuantityValue tebibytes) /// If value is NaN or Infinity. public static Information FromTerabits(QuantityValue terabits) { - decimal value = (decimal) terabits; + QuantityValue value = (QuantityValue) terabits; return new Information(value, InformationUnit.Terabit); } @@ -695,7 +696,7 @@ public static Information FromTerabits(QuantityValue terabits) /// If value is NaN or Infinity. public static Information FromTerabytes(QuantityValue terabytes) { - decimal value = (decimal) terabytes; + QuantityValue value = (QuantityValue) terabytes; return new Information(value, InformationUnit.Terabyte); } @@ -707,7 +708,7 @@ public static Information FromTerabytes(QuantityValue terabytes) /// Information unit value. public static Information From(QuantityValue value, InformationUnit fromUnit) { - return new Information((decimal)value, fromUnit); + return new Information((QuantityValue)value, fromUnit); } #endregion @@ -877,25 +878,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Infor } /// Get from multiplying value and . - public static Information operator *(decimal left, Information right) + public static Information operator *(QuantityValue left, Information right) { return new Information(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Information operator *(Information left, decimal right) + public static Information operator *(Information left, QuantityValue right) { return new Information(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Information operator /(Information left, decimal right) + public static Information operator /(Information left, QuantityValue right) { return new Information(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Information left, Information right) + public static QuantityValue operator /(Information left, Information right) { return left.Bits / right.Bits; } @@ -928,6 +929,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Infor return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Information left, Information right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Information left, Information right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -940,7 +954,29 @@ public int CompareTo(object obj) /// public int CompareTo(Information other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Information objInformation)) + return false; + return Equals(objInformation); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Information other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -983,13 +1019,13 @@ public int CompareTo(Information other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Information other, double tolerance, ComparisonType comparisonType) + public bool Equals(Information other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1000,7 +1036,7 @@ public bool Equals(Information other, double tolerance, ComparisonType compariso /// A hash code for the current Information. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1011,17 +1047,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(InformationUnit unit) + public QuantityValue As(InformationUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1036,12 +1071,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is InformationUnit unitAsInformationUnit)) + if (!(unit is InformationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(InformationUnit)} is supported.", nameof(unit)); - return As(unitAsInformationUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1073,7 +1108,7 @@ public Information ToUnit(InformationUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Information)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(InformationUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1081,17 +1116,17 @@ public Information ToUnit(InformationUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is InformationUnit unitAsInformationUnit)) + if (!(unit is InformationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(InformationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsInformationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1118,10 +1153,10 @@ public Information ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private decimal GetValueAs(InformationUnit unit) + private QuantityValue GetValueAs(InformationUnit unit) { var converted = ToUnit(unit); - return (decimal)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs index f395d39318..155555ecc5 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. /// [DataContract] - public partial struct Irradiance : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Irradiance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -85,9 +85,9 @@ static Irradiance() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Irradiance(double value, IrradianceUnit unit) + public Irradiance(QuantityValue value, IrradianceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -99,14 +99,14 @@ public Irradiance(double value, IrradianceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Irradiance(double value, UnitSystem unitSystem) + public Irradiance(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -147,7 +147,10 @@ public Irradiance(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -170,74 +173,74 @@ public Irradiance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerSquareCentimeter => As(IrradianceUnit.KilowattPerSquareCentimeter); + public QuantityValue KilowattsPerSquareCentimeter => As(IrradianceUnit.KilowattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); + public QuantityValue KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerSquareCentimeter => As(IrradianceUnit.MegawattPerSquareCentimeter); + public QuantityValue MegawattsPerSquareCentimeter => As(IrradianceUnit.MegawattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerSquareMeter => As(IrradianceUnit.MegawattPerSquareMeter); + public QuantityValue MegawattsPerSquareMeter => As(IrradianceUnit.MegawattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrowattsPerSquareCentimeter => As(IrradianceUnit.MicrowattPerSquareCentimeter); + public QuantityValue MicrowattsPerSquareCentimeter => As(IrradianceUnit.MicrowattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrowattsPerSquareMeter => As(IrradianceUnit.MicrowattPerSquareMeter); + public QuantityValue MicrowattsPerSquareMeter => As(IrradianceUnit.MicrowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerSquareCentimeter => As(IrradianceUnit.MilliwattPerSquareCentimeter); + public QuantityValue MilliwattsPerSquareCentimeter => As(IrradianceUnit.MilliwattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerSquareMeter => As(IrradianceUnit.MilliwattPerSquareMeter); + public QuantityValue MilliwattsPerSquareMeter => As(IrradianceUnit.MilliwattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanowattsPerSquareCentimeter => As(IrradianceUnit.NanowattPerSquareCentimeter); + public QuantityValue NanowattsPerSquareCentimeter => As(IrradianceUnit.NanowattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanowattsPerSquareMeter => As(IrradianceUnit.NanowattPerSquareMeter); + public QuantityValue NanowattsPerSquareMeter => As(IrradianceUnit.NanowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicowattsPerSquareCentimeter => As(IrradianceUnit.PicowattPerSquareCentimeter); + public QuantityValue PicowattsPerSquareCentimeter => As(IrradianceUnit.PicowattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicowattsPerSquareMeter => As(IrradianceUnit.PicowattPerSquareMeter); + public QuantityValue PicowattsPerSquareMeter => As(IrradianceUnit.PicowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerSquareCentimeter => As(IrradianceUnit.WattPerSquareCentimeter); + public QuantityValue WattsPerSquareCentimeter => As(IrradianceUnit.WattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); + public QuantityValue WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); #endregion @@ -332,7 +335,7 @@ public static string GetAbbreviation(IrradianceUnit unit, IFormatProvider? provi /// If value is NaN or Infinity. public static Irradiance FromKilowattsPerSquareCentimeter(QuantityValue kilowattspersquarecentimeter) { - double value = (double) kilowattspersquarecentimeter; + QuantityValue value = (QuantityValue) kilowattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.KilowattPerSquareCentimeter); } @@ -342,7 +345,7 @@ public static Irradiance FromKilowattsPerSquareCentimeter(QuantityValue kilowatt /// If value is NaN or Infinity. public static Irradiance FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) { - double value = (double) kilowattspersquaremeter; + QuantityValue value = (QuantityValue) kilowattspersquaremeter; return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); } @@ -352,7 +355,7 @@ public static Irradiance FromKilowattsPerSquareMeter(QuantityValue kilowattspers /// If value is NaN or Infinity. public static Irradiance FromMegawattsPerSquareCentimeter(QuantityValue megawattspersquarecentimeter) { - double value = (double) megawattspersquarecentimeter; + QuantityValue value = (QuantityValue) megawattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.MegawattPerSquareCentimeter); } @@ -362,7 +365,7 @@ public static Irradiance FromMegawattsPerSquareCentimeter(QuantityValue megawatt /// If value is NaN or Infinity. public static Irradiance FromMegawattsPerSquareMeter(QuantityValue megawattspersquaremeter) { - double value = (double) megawattspersquaremeter; + QuantityValue value = (QuantityValue) megawattspersquaremeter; return new Irradiance(value, IrradianceUnit.MegawattPerSquareMeter); } @@ -372,7 +375,7 @@ public static Irradiance FromMegawattsPerSquareMeter(QuantityValue megawattspers /// If value is NaN or Infinity. public static Irradiance FromMicrowattsPerSquareCentimeter(QuantityValue microwattspersquarecentimeter) { - double value = (double) microwattspersquarecentimeter; + QuantityValue value = (QuantityValue) microwattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.MicrowattPerSquareCentimeter); } @@ -382,7 +385,7 @@ public static Irradiance FromMicrowattsPerSquareCentimeter(QuantityValue microwa /// If value is NaN or Infinity. public static Irradiance FromMicrowattsPerSquareMeter(QuantityValue microwattspersquaremeter) { - double value = (double) microwattspersquaremeter; + QuantityValue value = (QuantityValue) microwattspersquaremeter; return new Irradiance(value, IrradianceUnit.MicrowattPerSquareMeter); } @@ -392,7 +395,7 @@ public static Irradiance FromMicrowattsPerSquareMeter(QuantityValue microwattspe /// If value is NaN or Infinity. public static Irradiance FromMilliwattsPerSquareCentimeter(QuantityValue milliwattspersquarecentimeter) { - double value = (double) milliwattspersquarecentimeter; + QuantityValue value = (QuantityValue) milliwattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.MilliwattPerSquareCentimeter); } @@ -402,7 +405,7 @@ public static Irradiance FromMilliwattsPerSquareCentimeter(QuantityValue milliwa /// If value is NaN or Infinity. public static Irradiance FromMilliwattsPerSquareMeter(QuantityValue milliwattspersquaremeter) { - double value = (double) milliwattspersquaremeter; + QuantityValue value = (QuantityValue) milliwattspersquaremeter; return new Irradiance(value, IrradianceUnit.MilliwattPerSquareMeter); } @@ -412,7 +415,7 @@ public static Irradiance FromMilliwattsPerSquareMeter(QuantityValue milliwattspe /// If value is NaN or Infinity. public static Irradiance FromNanowattsPerSquareCentimeter(QuantityValue nanowattspersquarecentimeter) { - double value = (double) nanowattspersquarecentimeter; + QuantityValue value = (QuantityValue) nanowattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.NanowattPerSquareCentimeter); } @@ -422,7 +425,7 @@ public static Irradiance FromNanowattsPerSquareCentimeter(QuantityValue nanowatt /// If value is NaN or Infinity. public static Irradiance FromNanowattsPerSquareMeter(QuantityValue nanowattspersquaremeter) { - double value = (double) nanowattspersquaremeter; + QuantityValue value = (QuantityValue) nanowattspersquaremeter; return new Irradiance(value, IrradianceUnit.NanowattPerSquareMeter); } @@ -432,7 +435,7 @@ public static Irradiance FromNanowattsPerSquareMeter(QuantityValue nanowattspers /// If value is NaN or Infinity. public static Irradiance FromPicowattsPerSquareCentimeter(QuantityValue picowattspersquarecentimeter) { - double value = (double) picowattspersquarecentimeter; + QuantityValue value = (QuantityValue) picowattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.PicowattPerSquareCentimeter); } @@ -442,7 +445,7 @@ public static Irradiance FromPicowattsPerSquareCentimeter(QuantityValue picowatt /// If value is NaN or Infinity. public static Irradiance FromPicowattsPerSquareMeter(QuantityValue picowattspersquaremeter) { - double value = (double) picowattspersquaremeter; + QuantityValue value = (QuantityValue) picowattspersquaremeter; return new Irradiance(value, IrradianceUnit.PicowattPerSquareMeter); } @@ -452,7 +455,7 @@ public static Irradiance FromPicowattsPerSquareMeter(QuantityValue picowattspers /// If value is NaN or Infinity. public static Irradiance FromWattsPerSquareCentimeter(QuantityValue wattspersquarecentimeter) { - double value = (double) wattspersquarecentimeter; + QuantityValue value = (QuantityValue) wattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.WattPerSquareCentimeter); } @@ -462,7 +465,7 @@ public static Irradiance FromWattsPerSquareCentimeter(QuantityValue wattspersqua /// If value is NaN or Infinity. public static Irradiance FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) { - double value = (double) wattspersquaremeter; + QuantityValue value = (QuantityValue) wattspersquaremeter; return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); } @@ -474,7 +477,7 @@ public static Irradiance FromWattsPerSquareMeter(QuantityValue wattspersquaremet /// Irradiance unit value. public static Irradiance From(QuantityValue value, IrradianceUnit fromUnit) { - return new Irradiance((double)value, fromUnit); + return new Irradiance((QuantityValue)value, fromUnit); } #endregion @@ -644,25 +647,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Irrad } /// Get from multiplying value and . - public static Irradiance operator *(double left, Irradiance right) + public static Irradiance operator *(QuantityValue left, Irradiance right) { return new Irradiance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Irradiance operator *(Irradiance left, double right) + public static Irradiance operator *(Irradiance left, QuantityValue right) { return new Irradiance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Irradiance operator /(Irradiance left, double right) + public static Irradiance operator /(Irradiance left, QuantityValue right) { return new Irradiance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Irradiance left, Irradiance right) + public static QuantityValue operator /(Irradiance left, Irradiance right) { return left.WattsPerSquareMeter / right.WattsPerSquareMeter; } @@ -695,6 +698,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Irrad return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Irradiance left, Irradiance right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Irradiance left, Irradiance right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -707,7 +723,29 @@ public int CompareTo(object obj) /// public int CompareTo(Irradiance other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Irradiance objIrradiance)) + return false; + return Equals(objIrradiance); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Irradiance other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -750,13 +788,13 @@ public int CompareTo(Irradiance other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Irradiance other, double tolerance, ComparisonType comparisonType) + public bool Equals(Irradiance other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -767,7 +805,7 @@ public bool Equals(Irradiance other, double tolerance, ComparisonType comparison /// A hash code for the current Irradiance. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -778,17 +816,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(IrradianceUnit unit) + public QuantityValue As(IrradianceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -803,12 +840,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is IrradianceUnit unitAsIrradianceUnit)) + if (!(unit is IrradianceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradianceUnit)} is supported.", nameof(unit)); - return As(unitAsIrradianceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -840,7 +877,7 @@ public Irradiance ToUnit(IrradianceUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Irradiance)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(IrradianceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -848,17 +885,17 @@ public Irradiance ToUnit(IrradianceUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is IrradianceUnit unitAsIrradianceUnit)) + if (!(unit is IrradianceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradianceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsIrradianceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -885,10 +922,10 @@ public Irradiance ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(IrradianceUnit unit) + private QuantityValue GetValueAs(IrradianceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs index 9ddd5731b6..943088a2af 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Irradiation /// [DataContract] - public partial struct Irradiation : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Irradiation : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -81,9 +81,9 @@ static Irradiation() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Irradiation(double value, IrradiationUnit unit) + public Irradiation(QuantityValue value, IrradiationUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -95,14 +95,14 @@ public Irradiation(double value, IrradiationUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Irradiation(double value, UnitSystem unitSystem) + public Irradiation(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -143,7 +143,10 @@ public Irradiation(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -166,39 +169,39 @@ public Irradiation(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerSquareCentimeter => As(IrradiationUnit.JoulePerSquareCentimeter); + public QuantityValue JoulesPerSquareCentimeter => As(IrradiationUnit.JoulePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); + public QuantityValue JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerSquareMillimeter => As(IrradiationUnit.JoulePerSquareMillimeter); + public QuantityValue JoulesPerSquareMillimeter => As(IrradiationUnit.JoulePerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerSquareMeter => As(IrradiationUnit.KilojoulePerSquareMeter); + public QuantityValue KilojoulesPerSquareMeter => As(IrradiationUnit.KilojoulePerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); + public QuantityValue KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillijoulesPerSquareCentimeter => As(IrradiationUnit.MillijoulePerSquareCentimeter); + public QuantityValue MillijoulesPerSquareCentimeter => As(IrradiationUnit.MillijoulePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); + public QuantityValue WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); #endregion @@ -272,7 +275,7 @@ public static string GetAbbreviation(IrradiationUnit unit, IFormatProvider? prov /// If value is NaN or Infinity. public static Irradiation FromJoulesPerSquareCentimeter(QuantityValue joulespersquarecentimeter) { - double value = (double) joulespersquarecentimeter; + QuantityValue value = (QuantityValue) joulespersquarecentimeter; return new Irradiation(value, IrradiationUnit.JoulePerSquareCentimeter); } @@ -282,7 +285,7 @@ public static Irradiation FromJoulesPerSquareCentimeter(QuantityValue joulespers /// If value is NaN or Infinity. public static Irradiation FromJoulesPerSquareMeter(QuantityValue joulespersquaremeter) { - double value = (double) joulespersquaremeter; + QuantityValue value = (QuantityValue) joulespersquaremeter; return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); } @@ -292,7 +295,7 @@ public static Irradiation FromJoulesPerSquareMeter(QuantityValue joulespersquare /// If value is NaN or Infinity. public static Irradiation FromJoulesPerSquareMillimeter(QuantityValue joulespersquaremillimeter) { - double value = (double) joulespersquaremillimeter; + QuantityValue value = (QuantityValue) joulespersquaremillimeter; return new Irradiation(value, IrradiationUnit.JoulePerSquareMillimeter); } @@ -302,7 +305,7 @@ public static Irradiation FromJoulesPerSquareMillimeter(QuantityValue joulespers /// If value is NaN or Infinity. public static Irradiation FromKilojoulesPerSquareMeter(QuantityValue kilojoulespersquaremeter) { - double value = (double) kilojoulespersquaremeter; + QuantityValue value = (QuantityValue) kilojoulespersquaremeter; return new Irradiation(value, IrradiationUnit.KilojoulePerSquareMeter); } @@ -312,7 +315,7 @@ public static Irradiation FromKilojoulesPerSquareMeter(QuantityValue kilojoulesp /// If value is NaN or Infinity. public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue kilowatthourspersquaremeter) { - double value = (double) kilowatthourspersquaremeter; + QuantityValue value = (QuantityValue) kilowatthourspersquaremeter; return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); } @@ -322,7 +325,7 @@ public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue kilowatt /// If value is NaN or Infinity. public static Irradiation FromMillijoulesPerSquareCentimeter(QuantityValue millijoulespersquarecentimeter) { - double value = (double) millijoulespersquarecentimeter; + QuantityValue value = (QuantityValue) millijoulespersquarecentimeter; return new Irradiation(value, IrradiationUnit.MillijoulePerSquareCentimeter); } @@ -332,7 +335,7 @@ public static Irradiation FromMillijoulesPerSquareCentimeter(QuantityValue milli /// If value is NaN or Infinity. public static Irradiation FromWattHoursPerSquareMeter(QuantityValue watthourspersquaremeter) { - double value = (double) watthourspersquaremeter; + QuantityValue value = (QuantityValue) watthourspersquaremeter; return new Irradiation(value, IrradiationUnit.WattHourPerSquareMeter); } @@ -344,7 +347,7 @@ public static Irradiation FromWattHoursPerSquareMeter(QuantityValue watthoursper /// Irradiation unit value. public static Irradiation From(QuantityValue value, IrradiationUnit fromUnit) { - return new Irradiation((double)value, fromUnit); + return new Irradiation((QuantityValue)value, fromUnit); } #endregion @@ -514,25 +517,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Irrad } /// Get from multiplying value and . - public static Irradiation operator *(double left, Irradiation right) + public static Irradiation operator *(QuantityValue left, Irradiation right) { return new Irradiation(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Irradiation operator *(Irradiation left, double right) + public static Irradiation operator *(Irradiation left, QuantityValue right) { return new Irradiation(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Irradiation operator /(Irradiation left, double right) + public static Irradiation operator /(Irradiation left, QuantityValue right) { return new Irradiation(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Irradiation left, Irradiation right) + public static QuantityValue operator /(Irradiation left, Irradiation right) { return left.JoulesPerSquareMeter / right.JoulesPerSquareMeter; } @@ -565,6 +568,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Irrad return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Irradiation left, Irradiation right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Irradiation left, Irradiation right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -577,7 +593,29 @@ public int CompareTo(object obj) /// public int CompareTo(Irradiation other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Irradiation objIrradiation)) + return false; + return Equals(objIrradiation); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Irradiation other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -620,13 +658,13 @@ public int CompareTo(Irradiation other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Irradiation other, double tolerance, ComparisonType comparisonType) + public bool Equals(Irradiation other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -637,7 +675,7 @@ public bool Equals(Irradiation other, double tolerance, ComparisonType compariso /// A hash code for the current Irradiation. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -648,17 +686,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(IrradiationUnit unit) + public QuantityValue As(IrradiationUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -673,12 +710,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is IrradiationUnit unitAsIrradiationUnit)) + if (!(unit is IrradiationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradiationUnit)} is supported.", nameof(unit)); - return As(unitAsIrradiationUnit); + return (QuantityValue)As(typedUnit); } /// @@ -710,7 +747,7 @@ public Irradiation ToUnit(IrradiationUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Irradiation)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(IrradiationUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -718,17 +755,17 @@ public Irradiation ToUnit(IrradiationUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is IrradiationUnit unitAsIrradiationUnit)) + if (!(unit is IrradiationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradiationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsIrradiationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -755,10 +792,10 @@ public Irradiation ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(IrradiationUnit unit) + private QuantityValue GetValueAs(IrradiationUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs index 7c5b0cee06..d590a3b824 100644 --- a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// /// [DataContract] - public partial struct Jerk : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Jerk : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -82,9 +82,9 @@ static Jerk() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Jerk(double value, JerkUnit unit) + public Jerk(QuantityValue value, JerkUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -96,14 +96,14 @@ public Jerk(double value, JerkUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Jerk(double value, UnitSystem unitSystem) + public Jerk(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -144,7 +144,10 @@ public Jerk(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -167,59 +170,59 @@ public Jerk(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentimetersPerSecondCubed => As(JerkUnit.CentimeterPerSecondCubed); + public QuantityValue CentimetersPerSecondCubed => As(JerkUnit.CentimeterPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimetersPerSecondCubed => As(JerkUnit.DecimeterPerSecondCubed); + public QuantityValue DecimetersPerSecondCubed => As(JerkUnit.DecimeterPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FeetPerSecondCubed => As(JerkUnit.FootPerSecondCubed); + public QuantityValue FeetPerSecondCubed => As(JerkUnit.FootPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InchesPerSecondCubed => As(JerkUnit.InchPerSecondCubed); + public QuantityValue InchesPerSecondCubed => As(JerkUnit.InchPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilometersPerSecondCubed => As(JerkUnit.KilometerPerSecondCubed); + public QuantityValue KilometersPerSecondCubed => As(JerkUnit.KilometerPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetersPerSecondCubed => As(JerkUnit.MeterPerSecondCubed); + public QuantityValue MetersPerSecondCubed => As(JerkUnit.MeterPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrometersPerSecondCubed => As(JerkUnit.MicrometerPerSecondCubed); + public QuantityValue MicrometersPerSecondCubed => As(JerkUnit.MicrometerPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimetersPerSecondCubed => As(JerkUnit.MillimeterPerSecondCubed); + public QuantityValue MillimetersPerSecondCubed => As(JerkUnit.MillimeterPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillistandardGravitiesPerSecond => As(JerkUnit.MillistandardGravitiesPerSecond); + public QuantityValue MillistandardGravitiesPerSecond => As(JerkUnit.MillistandardGravitiesPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanometersPerSecondCubed => As(JerkUnit.NanometerPerSecondCubed); + public QuantityValue NanometersPerSecondCubed => As(JerkUnit.NanometerPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardGravitiesPerSecond => As(JerkUnit.StandardGravitiesPerSecond); + public QuantityValue StandardGravitiesPerSecond => As(JerkUnit.StandardGravitiesPerSecond); #endregion @@ -316,7 +319,7 @@ public static string GetAbbreviation(JerkUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Jerk FromCentimetersPerSecondCubed(QuantityValue centimeterspersecondcubed) { - double value = (double) centimeterspersecondcubed; + QuantityValue value = (QuantityValue) centimeterspersecondcubed; return new Jerk(value, JerkUnit.CentimeterPerSecondCubed); } @@ -326,7 +329,7 @@ public static Jerk FromCentimetersPerSecondCubed(QuantityValue centimeterspersec /// If value is NaN or Infinity. public static Jerk FromDecimetersPerSecondCubed(QuantityValue decimeterspersecondcubed) { - double value = (double) decimeterspersecondcubed; + QuantityValue value = (QuantityValue) decimeterspersecondcubed; return new Jerk(value, JerkUnit.DecimeterPerSecondCubed); } @@ -336,7 +339,7 @@ public static Jerk FromDecimetersPerSecondCubed(QuantityValue decimeterspersecon /// If value is NaN or Infinity. public static Jerk FromFeetPerSecondCubed(QuantityValue feetpersecondcubed) { - double value = (double) feetpersecondcubed; + QuantityValue value = (QuantityValue) feetpersecondcubed; return new Jerk(value, JerkUnit.FootPerSecondCubed); } @@ -346,7 +349,7 @@ public static Jerk FromFeetPerSecondCubed(QuantityValue feetpersecondcubed) /// If value is NaN or Infinity. public static Jerk FromInchesPerSecondCubed(QuantityValue inchespersecondcubed) { - double value = (double) inchespersecondcubed; + QuantityValue value = (QuantityValue) inchespersecondcubed; return new Jerk(value, JerkUnit.InchPerSecondCubed); } @@ -356,7 +359,7 @@ public static Jerk FromInchesPerSecondCubed(QuantityValue inchespersecondcubed) /// If value is NaN or Infinity. public static Jerk FromKilometersPerSecondCubed(QuantityValue kilometerspersecondcubed) { - double value = (double) kilometerspersecondcubed; + QuantityValue value = (QuantityValue) kilometerspersecondcubed; return new Jerk(value, JerkUnit.KilometerPerSecondCubed); } @@ -366,7 +369,7 @@ public static Jerk FromKilometersPerSecondCubed(QuantityValue kilometerspersecon /// If value is NaN or Infinity. public static Jerk FromMetersPerSecondCubed(QuantityValue meterspersecondcubed) { - double value = (double) meterspersecondcubed; + QuantityValue value = (QuantityValue) meterspersecondcubed; return new Jerk(value, JerkUnit.MeterPerSecondCubed); } @@ -376,7 +379,7 @@ public static Jerk FromMetersPerSecondCubed(QuantityValue meterspersecondcubed) /// If value is NaN or Infinity. public static Jerk FromMicrometersPerSecondCubed(QuantityValue micrometerspersecondcubed) { - double value = (double) micrometerspersecondcubed; + QuantityValue value = (QuantityValue) micrometerspersecondcubed; return new Jerk(value, JerkUnit.MicrometerPerSecondCubed); } @@ -386,7 +389,7 @@ public static Jerk FromMicrometersPerSecondCubed(QuantityValue micrometerspersec /// If value is NaN or Infinity. public static Jerk FromMillimetersPerSecondCubed(QuantityValue millimeterspersecondcubed) { - double value = (double) millimeterspersecondcubed; + QuantityValue value = (QuantityValue) millimeterspersecondcubed; return new Jerk(value, JerkUnit.MillimeterPerSecondCubed); } @@ -396,7 +399,7 @@ public static Jerk FromMillimetersPerSecondCubed(QuantityValue millimeterspersec /// If value is NaN or Infinity. public static Jerk FromMillistandardGravitiesPerSecond(QuantityValue millistandardgravitiespersecond) { - double value = (double) millistandardgravitiespersecond; + QuantityValue value = (QuantityValue) millistandardgravitiespersecond; return new Jerk(value, JerkUnit.MillistandardGravitiesPerSecond); } @@ -406,7 +409,7 @@ public static Jerk FromMillistandardGravitiesPerSecond(QuantityValue millistanda /// If value is NaN or Infinity. public static Jerk FromNanometersPerSecondCubed(QuantityValue nanometerspersecondcubed) { - double value = (double) nanometerspersecondcubed; + QuantityValue value = (QuantityValue) nanometerspersecondcubed; return new Jerk(value, JerkUnit.NanometerPerSecondCubed); } @@ -416,7 +419,7 @@ public static Jerk FromNanometersPerSecondCubed(QuantityValue nanometerspersecon /// If value is NaN or Infinity. public static Jerk FromStandardGravitiesPerSecond(QuantityValue standardgravitiespersecond) { - double value = (double) standardgravitiespersecond; + QuantityValue value = (QuantityValue) standardgravitiespersecond; return new Jerk(value, JerkUnit.StandardGravitiesPerSecond); } @@ -428,7 +431,7 @@ public static Jerk FromStandardGravitiesPerSecond(QuantityValue standardgravitie /// Jerk unit value. public static Jerk From(QuantityValue value, JerkUnit fromUnit) { - return new Jerk((double)value, fromUnit); + return new Jerk((QuantityValue)value, fromUnit); } #endregion @@ -598,25 +601,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out JerkU } /// Get from multiplying value and . - public static Jerk operator *(double left, Jerk right) + public static Jerk operator *(QuantityValue left, Jerk right) { return new Jerk(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Jerk operator *(Jerk left, double right) + public static Jerk operator *(Jerk left, QuantityValue right) { return new Jerk(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Jerk operator /(Jerk left, double right) + public static Jerk operator /(Jerk left, QuantityValue right) { return new Jerk(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Jerk left, Jerk right) + public static QuantityValue operator /(Jerk left, Jerk right) { return left.MetersPerSecondCubed / right.MetersPerSecondCubed; } @@ -649,6 +652,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out JerkU return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Jerk left, Jerk right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Jerk left, Jerk right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -661,7 +677,29 @@ public int CompareTo(object obj) /// public int CompareTo(Jerk other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Jerk objJerk)) + return false; + return Equals(objJerk); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Jerk other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -704,13 +742,13 @@ public int CompareTo(Jerk other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Jerk other, double tolerance, ComparisonType comparisonType) + public bool Equals(Jerk other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -721,7 +759,7 @@ public bool Equals(Jerk other, double tolerance, ComparisonType comparisonType) /// A hash code for the current Jerk. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -732,17 +770,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(JerkUnit unit) + public QuantityValue As(JerkUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -757,12 +794,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is JerkUnit unitAsJerkUnit)) + if (!(unit is JerkUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(JerkUnit)} is supported.", nameof(unit)); - return As(unitAsJerkUnit); + return (QuantityValue)As(typedUnit); } /// @@ -794,7 +831,7 @@ public Jerk ToUnit(JerkUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Jerk)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(JerkUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -802,17 +839,17 @@ public Jerk ToUnit(JerkUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is JerkUnit unitAsJerkUnit)) + if (!(unit is JerkUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(JerkUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsJerkUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -839,10 +876,10 @@ public Jerk ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(JerkUnit unit) + private QuantityValue GetValueAs(JerkUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs index 35282f2c29..bb3d26a618 100644 --- a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Viscosity /// [DataContract] - public partial struct KinematicViscosity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct KinematicViscosity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -83,9 +83,9 @@ static KinematicViscosity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public KinematicViscosity(double value, KinematicViscosityUnit unit) + public KinematicViscosity(QuantityValue value, KinematicViscosityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -97,14 +97,14 @@ public KinematicViscosity(double value, KinematicViscosityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public KinematicViscosity(double value, UnitSystem unitSystem) + public KinematicViscosity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -145,7 +145,10 @@ public KinematicViscosity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -168,49 +171,49 @@ public KinematicViscosity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Centistokes => As(KinematicViscosityUnit.Centistokes); + public QuantityValue Centistokes => As(KinematicViscosityUnit.Centistokes); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decistokes => As(KinematicViscosityUnit.Decistokes); + public QuantityValue Decistokes => As(KinematicViscosityUnit.Decistokes); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilostokes => As(KinematicViscosityUnit.Kilostokes); + public QuantityValue Kilostokes => As(KinematicViscosityUnit.Kilostokes); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microstokes => As(KinematicViscosityUnit.Microstokes); + public QuantityValue Microstokes => As(KinematicViscosityUnit.Microstokes); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millistokes => As(KinematicViscosityUnit.Millistokes); + public QuantityValue Millistokes => As(KinematicViscosityUnit.Millistokes); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanostokes => As(KinematicViscosityUnit.Nanostokes); + public QuantityValue Nanostokes => As(KinematicViscosityUnit.Nanostokes); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareFeetPerSecond => As(KinematicViscosityUnit.SquareFootPerSecond); + public QuantityValue SquareFeetPerSecond => As(KinematicViscosityUnit.SquareFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); + public QuantityValue SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Stokes => As(KinematicViscosityUnit.Stokes); + public QuantityValue Stokes => As(KinematicViscosityUnit.Stokes); #endregion @@ -298,7 +301,7 @@ public static string GetAbbreviation(KinematicViscosityUnit unit, IFormatProvide /// If value is NaN or Infinity. public static KinematicViscosity FromCentistokes(QuantityValue centistokes) { - double value = (double) centistokes; + QuantityValue value = (QuantityValue) centistokes; return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); } @@ -308,7 +311,7 @@ public static KinematicViscosity FromCentistokes(QuantityValue centistokes) /// If value is NaN or Infinity. public static KinematicViscosity FromDecistokes(QuantityValue decistokes) { - double value = (double) decistokes; + QuantityValue value = (QuantityValue) decistokes; return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); } @@ -318,7 +321,7 @@ public static KinematicViscosity FromDecistokes(QuantityValue decistokes) /// If value is NaN or Infinity. public static KinematicViscosity FromKilostokes(QuantityValue kilostokes) { - double value = (double) kilostokes; + QuantityValue value = (QuantityValue) kilostokes; return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); } @@ -328,7 +331,7 @@ public static KinematicViscosity FromKilostokes(QuantityValue kilostokes) /// If value is NaN or Infinity. public static KinematicViscosity FromMicrostokes(QuantityValue microstokes) { - double value = (double) microstokes; + QuantityValue value = (QuantityValue) microstokes; return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); } @@ -338,7 +341,7 @@ public static KinematicViscosity FromMicrostokes(QuantityValue microstokes) /// If value is NaN or Infinity. public static KinematicViscosity FromMillistokes(QuantityValue millistokes) { - double value = (double) millistokes; + QuantityValue value = (QuantityValue) millistokes; return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); } @@ -348,7 +351,7 @@ public static KinematicViscosity FromMillistokes(QuantityValue millistokes) /// If value is NaN or Infinity. public static KinematicViscosity FromNanostokes(QuantityValue nanostokes) { - double value = (double) nanostokes; + QuantityValue value = (QuantityValue) nanostokes; return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); } @@ -358,7 +361,7 @@ public static KinematicViscosity FromNanostokes(QuantityValue nanostokes) /// If value is NaN or Infinity. public static KinematicViscosity FromSquareFeetPerSecond(QuantityValue squarefeetpersecond) { - double value = (double) squarefeetpersecond; + QuantityValue value = (QuantityValue) squarefeetpersecond; return new KinematicViscosity(value, KinematicViscosityUnit.SquareFootPerSecond); } @@ -368,7 +371,7 @@ public static KinematicViscosity FromSquareFeetPerSecond(QuantityValue squarefee /// If value is NaN or Infinity. public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue squaremeterspersecond) { - double value = (double) squaremeterspersecond; + QuantityValue value = (QuantityValue) squaremeterspersecond; return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); } @@ -378,7 +381,7 @@ public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue squarem /// If value is NaN or Infinity. public static KinematicViscosity FromStokes(QuantityValue stokes) { - double value = (double) stokes; + QuantityValue value = (QuantityValue) stokes; return new KinematicViscosity(value, KinematicViscosityUnit.Stokes); } @@ -390,7 +393,7 @@ public static KinematicViscosity FromStokes(QuantityValue stokes) /// KinematicViscosity unit value. public static KinematicViscosity From(QuantityValue value, KinematicViscosityUnit fromUnit) { - return new KinematicViscosity((double)value, fromUnit); + return new KinematicViscosity((QuantityValue)value, fromUnit); } #endregion @@ -560,25 +563,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Kinem } /// Get from multiplying value and . - public static KinematicViscosity operator *(double left, KinematicViscosity right) + public static KinematicViscosity operator *(QuantityValue left, KinematicViscosity right) { return new KinematicViscosity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static KinematicViscosity operator *(KinematicViscosity left, double right) + public static KinematicViscosity operator *(KinematicViscosity left, QuantityValue right) { return new KinematicViscosity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static KinematicViscosity operator /(KinematicViscosity left, double right) + public static KinematicViscosity operator /(KinematicViscosity left, QuantityValue right) { return new KinematicViscosity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(KinematicViscosity left, KinematicViscosity right) + public static QuantityValue operator /(KinematicViscosity left, KinematicViscosity right) { return left.SquareMetersPerSecond / right.SquareMetersPerSecond; } @@ -611,6 +614,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Kinem return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(KinematicViscosity left, KinematicViscosity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(KinematicViscosity left, KinematicViscosity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -623,7 +639,29 @@ public int CompareTo(object obj) /// public int CompareTo(KinematicViscosity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is KinematicViscosity objKinematicViscosity)) + return false; + return Equals(objKinematicViscosity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(KinematicViscosity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -666,13 +704,13 @@ public int CompareTo(KinematicViscosity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(KinematicViscosity other, double tolerance, ComparisonType comparisonType) + public bool Equals(KinematicViscosity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -683,7 +721,7 @@ public bool Equals(KinematicViscosity other, double tolerance, ComparisonType co /// A hash code for the current KinematicViscosity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -694,17 +732,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(KinematicViscosityUnit unit) + public QuantityValue As(KinematicViscosityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -719,12 +756,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is KinematicViscosityUnit unitAsKinematicViscosityUnit)) + if (!(unit is KinematicViscosityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(KinematicViscosityUnit)} is supported.", nameof(unit)); - return As(unitAsKinematicViscosityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -756,7 +793,7 @@ public KinematicViscosity ToUnit(KinematicViscosityUnit unit, UnitConverter unit var converted = conversionFunction(this); return (KinematicViscosity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(KinematicViscosityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -764,17 +801,17 @@ public KinematicViscosity ToUnit(KinematicViscosityUnit unit, UnitConverter unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is KinematicViscosityUnit unitAsKinematicViscosityUnit)) + if (!(unit is KinematicViscosityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(KinematicViscosityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsKinematicViscosityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -801,10 +838,10 @@ public KinematicViscosity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(KinematicViscosityUnit unit) + private QuantityValue GetValueAs(KinematicViscosityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs b/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs index fa9e8077ee..615c634f71 100644 --- a/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs @@ -36,13 +36,13 @@ namespace UnitsNet /// [Obsolete("Use TemperatureGradient instead.")] [DataContract] - public partial struct LapseRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct LapseRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -73,9 +73,9 @@ static LapseRate() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public LapseRate(double value, LapseRateUnit unit) + public LapseRate(QuantityValue value, LapseRateUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -87,14 +87,14 @@ public LapseRate(double value, LapseRateUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public LapseRate(double value, UnitSystem unitSystem) + public LapseRate(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -135,7 +135,10 @@ public LapseRate(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -158,9 +161,9 @@ public LapseRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); + public QuantityValue DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); #endregion @@ -216,7 +219,7 @@ public static string GetAbbreviation(LapseRateUnit unit, IFormatProvider? provid /// If value is NaN or Infinity. public static LapseRate FromDegreesCelciusPerKilometer(QuantityValue degreescelciusperkilometer) { - double value = (double) degreescelciusperkilometer; + QuantityValue value = (QuantityValue) degreescelciusperkilometer; return new LapseRate(value, LapseRateUnit.DegreeCelsiusPerKilometer); } @@ -228,7 +231,7 @@ public static LapseRate FromDegreesCelciusPerKilometer(QuantityValue degreescelc /// LapseRate unit value. public static LapseRate From(QuantityValue value, LapseRateUnit fromUnit) { - return new LapseRate((double)value, fromUnit); + return new LapseRate((QuantityValue)value, fromUnit); } #endregion @@ -398,25 +401,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lapse } /// Get from multiplying value and . - public static LapseRate operator *(double left, LapseRate right) + public static LapseRate operator *(QuantityValue left, LapseRate right) { return new LapseRate(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static LapseRate operator *(LapseRate left, double right) + public static LapseRate operator *(LapseRate left, QuantityValue right) { return new LapseRate(left.Value * right, left.Unit); } /// Get from dividing by value. - public static LapseRate operator /(LapseRate left, double right) + public static LapseRate operator /(LapseRate left, QuantityValue right) { return new LapseRate(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(LapseRate left, LapseRate right) + public static QuantityValue operator /(LapseRate left, LapseRate right) { return left.DegreesCelciusPerKilometer / right.DegreesCelciusPerKilometer; } @@ -449,6 +452,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lapse return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(LapseRate left, LapseRate right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(LapseRate left, LapseRate right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -461,7 +477,29 @@ public int CompareTo(object obj) /// public int CompareTo(LapseRate other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is LapseRate objLapseRate)) + return false; + return Equals(objLapseRate); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(LapseRate other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -504,13 +542,13 @@ public int CompareTo(LapseRate other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LapseRate other, double tolerance, ComparisonType comparisonType) + public bool Equals(LapseRate other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -521,7 +559,7 @@ public bool Equals(LapseRate other, double tolerance, ComparisonType comparisonT /// A hash code for the current LapseRate. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -532,17 +570,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(LapseRateUnit unit) + public QuantityValue As(LapseRateUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -557,12 +594,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is LapseRateUnit unitAsLapseRateUnit)) + if (!(unit is LapseRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LapseRateUnit)} is supported.", nameof(unit)); - return As(unitAsLapseRateUnit); + return (QuantityValue)As(typedUnit); } /// @@ -594,7 +631,7 @@ public LapseRate ToUnit(LapseRateUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (LapseRate)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(LapseRateUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -602,17 +639,17 @@ public LapseRate ToUnit(LapseRateUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LapseRateUnit unitAsLapseRateUnit)) + if (!(unit is LapseRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LapseRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLapseRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -639,10 +676,10 @@ public LapseRate ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(LapseRateUnit unit) + private QuantityValue GetValueAs(LapseRateUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Length.g.cs b/UnitsNet/GeneratedCode/Quantities/Length.g.cs index ab1960b463..2d564bacc4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Length.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Length.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. /// [DataContract] - public partial struct Length : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Length : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -107,9 +107,9 @@ static Length() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Length(double value, LengthUnit unit) + public Length(QuantityValue value, LengthUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -121,14 +121,14 @@ public Length(double value, LengthUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Length(double value, UnitSystem unitSystem) + public Length(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -169,7 +169,10 @@ public Length(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -192,184 +195,184 @@ public Length(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Angstroms => As(LengthUnit.Angstrom); + public QuantityValue Angstroms => As(LengthUnit.Angstrom); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AstronomicalUnits => As(LengthUnit.AstronomicalUnit); + public QuantityValue AstronomicalUnits => As(LengthUnit.AstronomicalUnit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Centimeters => As(LengthUnit.Centimeter); + public QuantityValue Centimeters => As(LengthUnit.Centimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Chains => As(LengthUnit.Chain); + public QuantityValue Chains => As(LengthUnit.Chain); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DataMiles => As(LengthUnit.DataMile); + public QuantityValue DataMiles => As(LengthUnit.DataMile); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decameters => As(LengthUnit.Decameter); + public QuantityValue Decameters => As(LengthUnit.Decameter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decimeters => As(LengthUnit.Decimeter); + public QuantityValue Decimeters => As(LengthUnit.Decimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DtpPicas => As(LengthUnit.DtpPica); + public QuantityValue DtpPicas => As(LengthUnit.DtpPica); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DtpPoints => As(LengthUnit.DtpPoint); + public QuantityValue DtpPoints => As(LengthUnit.DtpPoint); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Fathoms => As(LengthUnit.Fathom); + public QuantityValue Fathoms => As(LengthUnit.Fathom); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Feet => As(LengthUnit.Foot); + public QuantityValue Feet => As(LengthUnit.Foot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Hands => As(LengthUnit.Hand); + public QuantityValue Hands => As(LengthUnit.Hand); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Hectometers => As(LengthUnit.Hectometer); + public QuantityValue Hectometers => As(LengthUnit.Hectometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Inches => As(LengthUnit.Inch); + public QuantityValue Inches => As(LengthUnit.Inch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilolightYears => As(LengthUnit.KilolightYear); + public QuantityValue KilolightYears => As(LengthUnit.KilolightYear); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilometers => As(LengthUnit.Kilometer); + public QuantityValue Kilometers => As(LengthUnit.Kilometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kiloparsecs => As(LengthUnit.Kiloparsec); + public QuantityValue Kiloparsecs => As(LengthUnit.Kiloparsec); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LightYears => As(LengthUnit.LightYear); + public QuantityValue LightYears => As(LengthUnit.LightYear); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegalightYears => As(LengthUnit.MegalightYear); + public QuantityValue MegalightYears => As(LengthUnit.MegalightYear); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megaparsecs => As(LengthUnit.Megaparsec); + public QuantityValue Megaparsecs => As(LengthUnit.Megaparsec); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Meters => As(LengthUnit.Meter); + public QuantityValue Meters => As(LengthUnit.Meter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microinches => As(LengthUnit.Microinch); + public QuantityValue Microinches => As(LengthUnit.Microinch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Micrometers => As(LengthUnit.Micrometer); + public QuantityValue Micrometers => As(LengthUnit.Micrometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Mils => As(LengthUnit.Mil); + public QuantityValue Mils => As(LengthUnit.Mil); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Miles => As(LengthUnit.Mile); + public QuantityValue Miles => As(LengthUnit.Mile); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millimeters => As(LengthUnit.Millimeter); + public QuantityValue Millimeters => As(LengthUnit.Millimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanometers => As(LengthUnit.Nanometer); + public QuantityValue Nanometers => As(LengthUnit.Nanometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NauticalMiles => As(LengthUnit.NauticalMile); + public QuantityValue NauticalMiles => As(LengthUnit.NauticalMile); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Parsecs => As(LengthUnit.Parsec); + public QuantityValue Parsecs => As(LengthUnit.Parsec); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PrinterPicas => As(LengthUnit.PrinterPica); + public QuantityValue PrinterPicas => As(LengthUnit.PrinterPica); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PrinterPoints => As(LengthUnit.PrinterPoint); + public QuantityValue PrinterPoints => As(LengthUnit.PrinterPoint); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Shackles => As(LengthUnit.Shackle); + public QuantityValue Shackles => As(LengthUnit.Shackle); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SolarRadiuses => As(LengthUnit.SolarRadius); + public QuantityValue SolarRadiuses => As(LengthUnit.SolarRadius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Twips => As(LengthUnit.Twip); + public QuantityValue Twips => As(LengthUnit.Twip); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); + public QuantityValue UsSurveyFeet => As(LengthUnit.UsSurveyFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Yards => As(LengthUnit.Yard); + public QuantityValue Yards => As(LengthUnit.Yard); #endregion @@ -562,7 +565,7 @@ public static string GetAbbreviation(LengthUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Length FromAngstroms(QuantityValue angstroms) { - double value = (double) angstroms; + QuantityValue value = (QuantityValue) angstroms; return new Length(value, LengthUnit.Angstrom); } @@ -572,7 +575,7 @@ public static Length FromAngstroms(QuantityValue angstroms) /// If value is NaN or Infinity. public static Length FromAstronomicalUnits(QuantityValue astronomicalunits) { - double value = (double) astronomicalunits; + QuantityValue value = (QuantityValue) astronomicalunits; return new Length(value, LengthUnit.AstronomicalUnit); } @@ -582,7 +585,7 @@ public static Length FromAstronomicalUnits(QuantityValue astronomicalunits) /// If value is NaN or Infinity. public static Length FromCentimeters(QuantityValue centimeters) { - double value = (double) centimeters; + QuantityValue value = (QuantityValue) centimeters; return new Length(value, LengthUnit.Centimeter); } @@ -592,7 +595,7 @@ public static Length FromCentimeters(QuantityValue centimeters) /// If value is NaN or Infinity. public static Length FromChains(QuantityValue chains) { - double value = (double) chains; + QuantityValue value = (QuantityValue) chains; return new Length(value, LengthUnit.Chain); } @@ -602,7 +605,7 @@ public static Length FromChains(QuantityValue chains) /// If value is NaN or Infinity. public static Length FromDataMiles(QuantityValue datamiles) { - double value = (double) datamiles; + QuantityValue value = (QuantityValue) datamiles; return new Length(value, LengthUnit.DataMile); } @@ -612,7 +615,7 @@ public static Length FromDataMiles(QuantityValue datamiles) /// If value is NaN or Infinity. public static Length FromDecameters(QuantityValue decameters) { - double value = (double) decameters; + QuantityValue value = (QuantityValue) decameters; return new Length(value, LengthUnit.Decameter); } @@ -622,7 +625,7 @@ public static Length FromDecameters(QuantityValue decameters) /// If value is NaN or Infinity. public static Length FromDecimeters(QuantityValue decimeters) { - double value = (double) decimeters; + QuantityValue value = (QuantityValue) decimeters; return new Length(value, LengthUnit.Decimeter); } @@ -632,7 +635,7 @@ public static Length FromDecimeters(QuantityValue decimeters) /// If value is NaN or Infinity. public static Length FromDtpPicas(QuantityValue dtppicas) { - double value = (double) dtppicas; + QuantityValue value = (QuantityValue) dtppicas; return new Length(value, LengthUnit.DtpPica); } @@ -642,7 +645,7 @@ public static Length FromDtpPicas(QuantityValue dtppicas) /// If value is NaN or Infinity. public static Length FromDtpPoints(QuantityValue dtppoints) { - double value = (double) dtppoints; + QuantityValue value = (QuantityValue) dtppoints; return new Length(value, LengthUnit.DtpPoint); } @@ -652,7 +655,7 @@ public static Length FromDtpPoints(QuantityValue dtppoints) /// If value is NaN or Infinity. public static Length FromFathoms(QuantityValue fathoms) { - double value = (double) fathoms; + QuantityValue value = (QuantityValue) fathoms; return new Length(value, LengthUnit.Fathom); } @@ -662,7 +665,7 @@ public static Length FromFathoms(QuantityValue fathoms) /// If value is NaN or Infinity. public static Length FromFeet(QuantityValue feet) { - double value = (double) feet; + QuantityValue value = (QuantityValue) feet; return new Length(value, LengthUnit.Foot); } @@ -672,7 +675,7 @@ public static Length FromFeet(QuantityValue feet) /// If value is NaN or Infinity. public static Length FromHands(QuantityValue hands) { - double value = (double) hands; + QuantityValue value = (QuantityValue) hands; return new Length(value, LengthUnit.Hand); } @@ -682,7 +685,7 @@ public static Length FromHands(QuantityValue hands) /// If value is NaN or Infinity. public static Length FromHectometers(QuantityValue hectometers) { - double value = (double) hectometers; + QuantityValue value = (QuantityValue) hectometers; return new Length(value, LengthUnit.Hectometer); } @@ -692,7 +695,7 @@ public static Length FromHectometers(QuantityValue hectometers) /// If value is NaN or Infinity. public static Length FromInches(QuantityValue inches) { - double value = (double) inches; + QuantityValue value = (QuantityValue) inches; return new Length(value, LengthUnit.Inch); } @@ -702,7 +705,7 @@ public static Length FromInches(QuantityValue inches) /// If value is NaN or Infinity. public static Length FromKilolightYears(QuantityValue kilolightyears) { - double value = (double) kilolightyears; + QuantityValue value = (QuantityValue) kilolightyears; return new Length(value, LengthUnit.KilolightYear); } @@ -712,7 +715,7 @@ public static Length FromKilolightYears(QuantityValue kilolightyears) /// If value is NaN or Infinity. public static Length FromKilometers(QuantityValue kilometers) { - double value = (double) kilometers; + QuantityValue value = (QuantityValue) kilometers; return new Length(value, LengthUnit.Kilometer); } @@ -722,7 +725,7 @@ public static Length FromKilometers(QuantityValue kilometers) /// If value is NaN or Infinity. public static Length FromKiloparsecs(QuantityValue kiloparsecs) { - double value = (double) kiloparsecs; + QuantityValue value = (QuantityValue) kiloparsecs; return new Length(value, LengthUnit.Kiloparsec); } @@ -732,7 +735,7 @@ public static Length FromKiloparsecs(QuantityValue kiloparsecs) /// If value is NaN or Infinity. public static Length FromLightYears(QuantityValue lightyears) { - double value = (double) lightyears; + QuantityValue value = (QuantityValue) lightyears; return new Length(value, LengthUnit.LightYear); } @@ -742,7 +745,7 @@ public static Length FromLightYears(QuantityValue lightyears) /// If value is NaN or Infinity. public static Length FromMegalightYears(QuantityValue megalightyears) { - double value = (double) megalightyears; + QuantityValue value = (QuantityValue) megalightyears; return new Length(value, LengthUnit.MegalightYear); } @@ -752,7 +755,7 @@ public static Length FromMegalightYears(QuantityValue megalightyears) /// If value is NaN or Infinity. public static Length FromMegaparsecs(QuantityValue megaparsecs) { - double value = (double) megaparsecs; + QuantityValue value = (QuantityValue) megaparsecs; return new Length(value, LengthUnit.Megaparsec); } @@ -762,7 +765,7 @@ public static Length FromMegaparsecs(QuantityValue megaparsecs) /// If value is NaN or Infinity. public static Length FromMeters(QuantityValue meters) { - double value = (double) meters; + QuantityValue value = (QuantityValue) meters; return new Length(value, LengthUnit.Meter); } @@ -772,7 +775,7 @@ public static Length FromMeters(QuantityValue meters) /// If value is NaN or Infinity. public static Length FromMicroinches(QuantityValue microinches) { - double value = (double) microinches; + QuantityValue value = (QuantityValue) microinches; return new Length(value, LengthUnit.Microinch); } @@ -782,7 +785,7 @@ public static Length FromMicroinches(QuantityValue microinches) /// If value is NaN or Infinity. public static Length FromMicrometers(QuantityValue micrometers) { - double value = (double) micrometers; + QuantityValue value = (QuantityValue) micrometers; return new Length(value, LengthUnit.Micrometer); } @@ -792,7 +795,7 @@ public static Length FromMicrometers(QuantityValue micrometers) /// If value is NaN or Infinity. public static Length FromMils(QuantityValue mils) { - double value = (double) mils; + QuantityValue value = (QuantityValue) mils; return new Length(value, LengthUnit.Mil); } @@ -802,7 +805,7 @@ public static Length FromMils(QuantityValue mils) /// If value is NaN or Infinity. public static Length FromMiles(QuantityValue miles) { - double value = (double) miles; + QuantityValue value = (QuantityValue) miles; return new Length(value, LengthUnit.Mile); } @@ -812,7 +815,7 @@ public static Length FromMiles(QuantityValue miles) /// If value is NaN or Infinity. public static Length FromMillimeters(QuantityValue millimeters) { - double value = (double) millimeters; + QuantityValue value = (QuantityValue) millimeters; return new Length(value, LengthUnit.Millimeter); } @@ -822,7 +825,7 @@ public static Length FromMillimeters(QuantityValue millimeters) /// If value is NaN or Infinity. public static Length FromNanometers(QuantityValue nanometers) { - double value = (double) nanometers; + QuantityValue value = (QuantityValue) nanometers; return new Length(value, LengthUnit.Nanometer); } @@ -832,7 +835,7 @@ public static Length FromNanometers(QuantityValue nanometers) /// If value is NaN or Infinity. public static Length FromNauticalMiles(QuantityValue nauticalmiles) { - double value = (double) nauticalmiles; + QuantityValue value = (QuantityValue) nauticalmiles; return new Length(value, LengthUnit.NauticalMile); } @@ -842,7 +845,7 @@ public static Length FromNauticalMiles(QuantityValue nauticalmiles) /// If value is NaN or Infinity. public static Length FromParsecs(QuantityValue parsecs) { - double value = (double) parsecs; + QuantityValue value = (QuantityValue) parsecs; return new Length(value, LengthUnit.Parsec); } @@ -852,7 +855,7 @@ public static Length FromParsecs(QuantityValue parsecs) /// If value is NaN or Infinity. public static Length FromPrinterPicas(QuantityValue printerpicas) { - double value = (double) printerpicas; + QuantityValue value = (QuantityValue) printerpicas; return new Length(value, LengthUnit.PrinterPica); } @@ -862,7 +865,7 @@ public static Length FromPrinterPicas(QuantityValue printerpicas) /// If value is NaN or Infinity. public static Length FromPrinterPoints(QuantityValue printerpoints) { - double value = (double) printerpoints; + QuantityValue value = (QuantityValue) printerpoints; return new Length(value, LengthUnit.PrinterPoint); } @@ -872,7 +875,7 @@ public static Length FromPrinterPoints(QuantityValue printerpoints) /// If value is NaN or Infinity. public static Length FromShackles(QuantityValue shackles) { - double value = (double) shackles; + QuantityValue value = (QuantityValue) shackles; return new Length(value, LengthUnit.Shackle); } @@ -882,7 +885,7 @@ public static Length FromShackles(QuantityValue shackles) /// If value is NaN or Infinity. public static Length FromSolarRadiuses(QuantityValue solarradiuses) { - double value = (double) solarradiuses; + QuantityValue value = (QuantityValue) solarradiuses; return new Length(value, LengthUnit.SolarRadius); } @@ -892,7 +895,7 @@ public static Length FromSolarRadiuses(QuantityValue solarradiuses) /// If value is NaN or Infinity. public static Length FromTwips(QuantityValue twips) { - double value = (double) twips; + QuantityValue value = (QuantityValue) twips; return new Length(value, LengthUnit.Twip); } @@ -902,7 +905,7 @@ public static Length FromTwips(QuantityValue twips) /// If value is NaN or Infinity. public static Length FromUsSurveyFeet(QuantityValue ussurveyfeet) { - double value = (double) ussurveyfeet; + QuantityValue value = (QuantityValue) ussurveyfeet; return new Length(value, LengthUnit.UsSurveyFoot); } @@ -912,7 +915,7 @@ public static Length FromUsSurveyFeet(QuantityValue ussurveyfeet) /// If value is NaN or Infinity. public static Length FromYards(QuantityValue yards) { - double value = (double) yards; + QuantityValue value = (QuantityValue) yards; return new Length(value, LengthUnit.Yard); } @@ -924,7 +927,7 @@ public static Length FromYards(QuantityValue yards) /// Length unit value. public static Length From(QuantityValue value, LengthUnit fromUnit) { - return new Length((double)value, fromUnit); + return new Length((QuantityValue)value, fromUnit); } #endregion @@ -1094,25 +1097,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lengt } /// Get from multiplying value and . - public static Length operator *(double left, Length right) + public static Length operator *(QuantityValue left, Length right) { return new Length(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Length operator *(Length left, double right) + public static Length operator *(Length left, QuantityValue right) { return new Length(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Length operator /(Length left, double right) + public static Length operator /(Length left, QuantityValue right) { return new Length(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Length left, Length right) + public static QuantityValue operator /(Length left, Length right) { return left.Meters / right.Meters; } @@ -1145,6 +1148,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lengt return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Length left, Length right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Length left, Length right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1157,7 +1173,29 @@ public int CompareTo(object obj) /// public int CompareTo(Length other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Length objLength)) + return false; + return Equals(objLength); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Length other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1200,13 +1238,13 @@ public int CompareTo(Length other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Length other, double tolerance, ComparisonType comparisonType) + public bool Equals(Length other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1217,7 +1255,7 @@ public bool Equals(Length other, double tolerance, ComparisonType comparisonType /// A hash code for the current Length. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1228,17 +1266,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(LengthUnit unit) + public QuantityValue As(LengthUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1253,12 +1290,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is LengthUnit unitAsLengthUnit)) + if (!(unit is LengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LengthUnit)} is supported.", nameof(unit)); - return As(unitAsLengthUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1290,7 +1327,7 @@ public Length ToUnit(LengthUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Length)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(LengthUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1298,17 +1335,17 @@ public Length ToUnit(LengthUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LengthUnit unitAsLengthUnit)) + if (!(unit is LengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1335,10 +1372,10 @@ public Length ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(LengthUnit unit) + private QuantityValue GetValueAs(LengthUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Level.g.cs b/UnitsNet/GeneratedCode/Quantities/Level.g.cs index 16b78f3430..2610e6c6f9 100644 --- a/UnitsNet/GeneratedCode/Quantities/Level.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Level.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. /// [DataContract] - public partial struct Level : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Level : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -73,9 +73,9 @@ static Level() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Level(double value, LevelUnit unit) + public Level(QuantityValue value, LevelUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -87,14 +87,14 @@ public Level(double value, LevelUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Level(double value, UnitSystem unitSystem) + public Level(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -135,7 +135,10 @@ public Level(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -158,14 +161,14 @@ public Level(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decibels => As(LevelUnit.Decibel); + public QuantityValue Decibels => As(LevelUnit.Decibel); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nepers => As(LevelUnit.Neper); + public QuantityValue Nepers => As(LevelUnit.Neper); #endregion @@ -224,7 +227,7 @@ public static string GetAbbreviation(LevelUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Level FromDecibels(QuantityValue decibels) { - double value = (double) decibels; + QuantityValue value = (QuantityValue) decibels; return new Level(value, LevelUnit.Decibel); } @@ -234,7 +237,7 @@ public static Level FromDecibels(QuantityValue decibels) /// If value is NaN or Infinity. public static Level FromNepers(QuantityValue nepers) { - double value = (double) nepers; + QuantityValue value = (QuantityValue) nepers; return new Level(value, LevelUnit.Neper); } @@ -246,7 +249,7 @@ public static Level FromNepers(QuantityValue nepers) /// Level unit value. public static Level From(QuantityValue value, LevelUnit fromUnit) { - return new Level((double)value, fromUnit); + return new Level((QuantityValue)value, fromUnit); } #endregion @@ -408,7 +411,7 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Level { // Logarithmic addition // Formula: 10 * log10(10^(x/10) + 10^(y/10)) - return new Level(10 * Math.Log10(Math.Pow(10, left.Value/10) + Math.Pow(10, right.GetValueAs(left.Unit)/10)), left.Unit); + return new Level(10 * Math.Log10(Math.Pow(10, (double)left.Value/10) + Math.Pow(10, (double)right.GetValueAs(left.Unit)/10)), left.Unit); } /// Get from logarithmic subtraction of two . @@ -416,11 +419,11 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Level { // Logarithmic subtraction // Formula: 10 * log10(10^(x/10) - 10^(y/10)) - return new Level(10 * Math.Log10(Math.Pow(10, left.Value/10) - Math.Pow(10, right.GetValueAs(left.Unit)/10)), left.Unit); + return new Level(10 * Math.Log10(Math.Pow(10, (double)left.Value/10) - Math.Pow(10, (double)right.GetValueAs(left.Unit)/10)), left.Unit); } /// Get from logarithmic multiplication of value and . - public static Level operator *(double left, Level right) + public static Level operator *(QuantityValue left, Level right) { // Logarithmic multiplication = addition return new Level(left + right.Value, right.Unit); @@ -430,14 +433,14 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Level public static Level operator *(Level left, double right) { // Logarithmic multiplication = addition - return new Level(left.Value + (double)right, left.Unit); + return new Level(left.Value + (QuantityValue)right, left.Unit); } /// Get from logarithmic division of by value. public static Level operator /(Level left, double right) { // Logarithmic division = subtraction - return new Level(left.Value - (double)right, left.Unit); + return new Level(left.Value - (QuantityValue)right, left.Unit); } /// Get ratio value from logarithmic division of by . @@ -475,6 +478,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Level return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Level left, Level right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Level left, Level right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -487,7 +503,29 @@ public int CompareTo(object obj) /// public int CompareTo(Level other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Level objLevel)) + return false; + return Equals(objLevel); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Level other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -530,13 +568,13 @@ public int CompareTo(Level other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Level other, double tolerance, ComparisonType comparisonType) + public bool Equals(Level other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -547,7 +585,7 @@ public bool Equals(Level other, double tolerance, ComparisonType comparisonType) /// A hash code for the current Level. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -558,17 +596,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(LevelUnit unit) + public QuantityValue As(LevelUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -583,12 +620,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is LevelUnit unitAsLevelUnit)) + if (!(unit is LevelUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LevelUnit)} is supported.", nameof(unit)); - return As(unitAsLevelUnit); + return (QuantityValue)As(typedUnit); } /// @@ -620,7 +657,7 @@ public Level ToUnit(LevelUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Level)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(LevelUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -628,17 +665,17 @@ public Level ToUnit(LevelUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LevelUnit unitAsLevelUnit)) + if (!(unit is LevelUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LevelUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLevelUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -665,10 +702,10 @@ public Level ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(LevelUnit unit) + private QuantityValue GetValueAs(LevelUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs index 659ad66f37..ceec19fbc9 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Linear_density /// [DataContract] - public partial struct LinearDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct LinearDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -88,9 +88,9 @@ static LinearDensity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public LinearDensity(double value, LinearDensityUnit unit) + public LinearDensity(QuantityValue value, LinearDensityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -102,14 +102,14 @@ public LinearDensity(double value, LinearDensityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public LinearDensity(double value, UnitSystem unitSystem) + public LinearDensity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -150,7 +150,10 @@ public LinearDensity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -173,74 +176,74 @@ public LinearDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerCentimeter => As(LinearDensityUnit.GramPerCentimeter); + public QuantityValue GramsPerCentimeter => As(LinearDensityUnit.GramPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerMeter => As(LinearDensityUnit.GramPerMeter); + public QuantityValue GramsPerMeter => As(LinearDensityUnit.GramPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerMillimeter => As(LinearDensityUnit.GramPerMillimeter); + public QuantityValue GramsPerMillimeter => As(LinearDensityUnit.GramPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerCentimeter => As(LinearDensityUnit.KilogramPerCentimeter); + public QuantityValue KilogramsPerCentimeter => As(LinearDensityUnit.KilogramPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); + public QuantityValue KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerMillimeter => As(LinearDensityUnit.KilogramPerMillimeter); + public QuantityValue KilogramsPerMillimeter => As(LinearDensityUnit.KilogramPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerCentimeter => As(LinearDensityUnit.MicrogramPerCentimeter); + public QuantityValue MicrogramsPerCentimeter => As(LinearDensityUnit.MicrogramPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerMeter => As(LinearDensityUnit.MicrogramPerMeter); + public QuantityValue MicrogramsPerMeter => As(LinearDensityUnit.MicrogramPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerMillimeter => As(LinearDensityUnit.MicrogramPerMillimeter); + public QuantityValue MicrogramsPerMillimeter => As(LinearDensityUnit.MicrogramPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerCentimeter => As(LinearDensityUnit.MilligramPerCentimeter); + public QuantityValue MilligramsPerCentimeter => As(LinearDensityUnit.MilligramPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerMeter => As(LinearDensityUnit.MilligramPerMeter); + public QuantityValue MilligramsPerMeter => As(LinearDensityUnit.MilligramPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerMillimeter => As(LinearDensityUnit.MilligramPerMillimeter); + public QuantityValue MilligramsPerMillimeter => As(LinearDensityUnit.MilligramPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); + public QuantityValue PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerInch => As(LinearDensityUnit.PoundPerInch); + public QuantityValue PoundsPerInch => As(LinearDensityUnit.PoundPerInch); #endregion @@ -335,7 +338,7 @@ public static string GetAbbreviation(LinearDensityUnit unit, IFormatProvider? pr /// If value is NaN or Infinity. public static LinearDensity FromGramsPerCentimeter(QuantityValue gramspercentimeter) { - double value = (double) gramspercentimeter; + QuantityValue value = (QuantityValue) gramspercentimeter; return new LinearDensity(value, LinearDensityUnit.GramPerCentimeter); } @@ -345,7 +348,7 @@ public static LinearDensity FromGramsPerCentimeter(QuantityValue gramspercentime /// If value is NaN or Infinity. public static LinearDensity FromGramsPerMeter(QuantityValue gramspermeter) { - double value = (double) gramspermeter; + QuantityValue value = (QuantityValue) gramspermeter; return new LinearDensity(value, LinearDensityUnit.GramPerMeter); } @@ -355,7 +358,7 @@ public static LinearDensity FromGramsPerMeter(QuantityValue gramspermeter) /// If value is NaN or Infinity. public static LinearDensity FromGramsPerMillimeter(QuantityValue gramspermillimeter) { - double value = (double) gramspermillimeter; + QuantityValue value = (QuantityValue) gramspermillimeter; return new LinearDensity(value, LinearDensityUnit.GramPerMillimeter); } @@ -365,7 +368,7 @@ public static LinearDensity FromGramsPerMillimeter(QuantityValue gramspermillime /// If value is NaN or Infinity. public static LinearDensity FromKilogramsPerCentimeter(QuantityValue kilogramspercentimeter) { - double value = (double) kilogramspercentimeter; + QuantityValue value = (QuantityValue) kilogramspercentimeter; return new LinearDensity(value, LinearDensityUnit.KilogramPerCentimeter); } @@ -375,7 +378,7 @@ public static LinearDensity FromKilogramsPerCentimeter(QuantityValue kilogramspe /// If value is NaN or Infinity. public static LinearDensity FromKilogramsPerMeter(QuantityValue kilogramspermeter) { - double value = (double) kilogramspermeter; + QuantityValue value = (QuantityValue) kilogramspermeter; return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); } @@ -385,7 +388,7 @@ public static LinearDensity FromKilogramsPerMeter(QuantityValue kilogramspermete /// If value is NaN or Infinity. public static LinearDensity FromKilogramsPerMillimeter(QuantityValue kilogramspermillimeter) { - double value = (double) kilogramspermillimeter; + QuantityValue value = (QuantityValue) kilogramspermillimeter; return new LinearDensity(value, LinearDensityUnit.KilogramPerMillimeter); } @@ -395,7 +398,7 @@ public static LinearDensity FromKilogramsPerMillimeter(QuantityValue kilogramspe /// If value is NaN or Infinity. public static LinearDensity FromMicrogramsPerCentimeter(QuantityValue microgramspercentimeter) { - double value = (double) microgramspercentimeter; + QuantityValue value = (QuantityValue) microgramspercentimeter; return new LinearDensity(value, LinearDensityUnit.MicrogramPerCentimeter); } @@ -405,7 +408,7 @@ public static LinearDensity FromMicrogramsPerCentimeter(QuantityValue micrograms /// If value is NaN or Infinity. public static LinearDensity FromMicrogramsPerMeter(QuantityValue microgramspermeter) { - double value = (double) microgramspermeter; + QuantityValue value = (QuantityValue) microgramspermeter; return new LinearDensity(value, LinearDensityUnit.MicrogramPerMeter); } @@ -415,7 +418,7 @@ public static LinearDensity FromMicrogramsPerMeter(QuantityValue microgramsperme /// If value is NaN or Infinity. public static LinearDensity FromMicrogramsPerMillimeter(QuantityValue microgramspermillimeter) { - double value = (double) microgramspermillimeter; + QuantityValue value = (QuantityValue) microgramspermillimeter; return new LinearDensity(value, LinearDensityUnit.MicrogramPerMillimeter); } @@ -425,7 +428,7 @@ public static LinearDensity FromMicrogramsPerMillimeter(QuantityValue micrograms /// If value is NaN or Infinity. public static LinearDensity FromMilligramsPerCentimeter(QuantityValue milligramspercentimeter) { - double value = (double) milligramspercentimeter; + QuantityValue value = (QuantityValue) milligramspercentimeter; return new LinearDensity(value, LinearDensityUnit.MilligramPerCentimeter); } @@ -435,7 +438,7 @@ public static LinearDensity FromMilligramsPerCentimeter(QuantityValue milligrams /// If value is NaN or Infinity. public static LinearDensity FromMilligramsPerMeter(QuantityValue milligramspermeter) { - double value = (double) milligramspermeter; + QuantityValue value = (QuantityValue) milligramspermeter; return new LinearDensity(value, LinearDensityUnit.MilligramPerMeter); } @@ -445,7 +448,7 @@ public static LinearDensity FromMilligramsPerMeter(QuantityValue milligramsperme /// If value is NaN or Infinity. public static LinearDensity FromMilligramsPerMillimeter(QuantityValue milligramspermillimeter) { - double value = (double) milligramspermillimeter; + QuantityValue value = (QuantityValue) milligramspermillimeter; return new LinearDensity(value, LinearDensityUnit.MilligramPerMillimeter); } @@ -455,7 +458,7 @@ public static LinearDensity FromMilligramsPerMillimeter(QuantityValue milligrams /// If value is NaN or Infinity. public static LinearDensity FromPoundsPerFoot(QuantityValue poundsperfoot) { - double value = (double) poundsperfoot; + QuantityValue value = (QuantityValue) poundsperfoot; return new LinearDensity(value, LinearDensityUnit.PoundPerFoot); } @@ -465,7 +468,7 @@ public static LinearDensity FromPoundsPerFoot(QuantityValue poundsperfoot) /// If value is NaN or Infinity. public static LinearDensity FromPoundsPerInch(QuantityValue poundsperinch) { - double value = (double) poundsperinch; + QuantityValue value = (QuantityValue) poundsperinch; return new LinearDensity(value, LinearDensityUnit.PoundPerInch); } @@ -477,7 +480,7 @@ public static LinearDensity FromPoundsPerInch(QuantityValue poundsperinch) /// LinearDensity unit value. public static LinearDensity From(QuantityValue value, LinearDensityUnit fromUnit) { - return new LinearDensity((double)value, fromUnit); + return new LinearDensity((QuantityValue)value, fromUnit); } #endregion @@ -647,25 +650,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Linea } /// Get from multiplying value and . - public static LinearDensity operator *(double left, LinearDensity right) + public static LinearDensity operator *(QuantityValue left, LinearDensity right) { return new LinearDensity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static LinearDensity operator *(LinearDensity left, double right) + public static LinearDensity operator *(LinearDensity left, QuantityValue right) { return new LinearDensity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static LinearDensity operator /(LinearDensity left, double right) + public static LinearDensity operator /(LinearDensity left, QuantityValue right) { return new LinearDensity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(LinearDensity left, LinearDensity right) + public static QuantityValue operator /(LinearDensity left, LinearDensity right) { return left.KilogramsPerMeter / right.KilogramsPerMeter; } @@ -698,6 +701,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Linea return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(LinearDensity left, LinearDensity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(LinearDensity left, LinearDensity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -710,7 +726,29 @@ public int CompareTo(object obj) /// public int CompareTo(LinearDensity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is LinearDensity objLinearDensity)) + return false; + return Equals(objLinearDensity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(LinearDensity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -753,13 +791,13 @@ public int CompareTo(LinearDensity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LinearDensity other, double tolerance, ComparisonType comparisonType) + public bool Equals(LinearDensity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -770,7 +808,7 @@ public bool Equals(LinearDensity other, double tolerance, ComparisonType compari /// A hash code for the current LinearDensity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -781,17 +819,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(LinearDensityUnit unit) + public QuantityValue As(LinearDensityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -806,12 +843,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is LinearDensityUnit unitAsLinearDensityUnit)) + if (!(unit is LinearDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearDensityUnit)} is supported.", nameof(unit)); - return As(unitAsLinearDensityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -843,7 +880,7 @@ public LinearDensity ToUnit(LinearDensityUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (LinearDensity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(LinearDensityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -851,17 +888,17 @@ public LinearDensity ToUnit(LinearDensityUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LinearDensityUnit unitAsLinearDensityUnit)) + if (!(unit is LinearDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLinearDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -888,10 +925,10 @@ public LinearDensity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(LinearDensityUnit unit) + private QuantityValue GetValueAs(LinearDensityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs index 20a484724a..5500223a41 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Linear_density /// [DataContract] - public partial struct LinearPowerDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct LinearPowerDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -99,9 +99,9 @@ static LinearPowerDensity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public LinearPowerDensity(double value, LinearPowerDensityUnit unit) + public LinearPowerDensity(QuantityValue value, LinearPowerDensityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -113,14 +113,14 @@ public LinearPowerDensity(double value, LinearPowerDensityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public LinearPowerDensity(double value, UnitSystem unitSystem) + public LinearPowerDensity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -161,7 +161,10 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -184,129 +187,129 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattsPerCentimeter => As(LinearPowerDensityUnit.GigawattPerCentimeter); + public QuantityValue GigawattsPerCentimeter => As(LinearPowerDensityUnit.GigawattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattsPerFoot => As(LinearPowerDensityUnit.GigawattPerFoot); + public QuantityValue GigawattsPerFoot => As(LinearPowerDensityUnit.GigawattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattsPerInch => As(LinearPowerDensityUnit.GigawattPerInch); + public QuantityValue GigawattsPerInch => As(LinearPowerDensityUnit.GigawattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattsPerMeter => As(LinearPowerDensityUnit.GigawattPerMeter); + public QuantityValue GigawattsPerMeter => As(LinearPowerDensityUnit.GigawattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattsPerMillimeter => As(LinearPowerDensityUnit.GigawattPerMillimeter); + public QuantityValue GigawattsPerMillimeter => As(LinearPowerDensityUnit.GigawattPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerCentimeter => As(LinearPowerDensityUnit.KilowattPerCentimeter); + public QuantityValue KilowattsPerCentimeter => As(LinearPowerDensityUnit.KilowattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerFoot => As(LinearPowerDensityUnit.KilowattPerFoot); + public QuantityValue KilowattsPerFoot => As(LinearPowerDensityUnit.KilowattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerInch => As(LinearPowerDensityUnit.KilowattPerInch); + public QuantityValue KilowattsPerInch => As(LinearPowerDensityUnit.KilowattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerMeter => As(LinearPowerDensityUnit.KilowattPerMeter); + public QuantityValue KilowattsPerMeter => As(LinearPowerDensityUnit.KilowattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerMillimeter => As(LinearPowerDensityUnit.KilowattPerMillimeter); + public QuantityValue KilowattsPerMillimeter => As(LinearPowerDensityUnit.KilowattPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerCentimeter => As(LinearPowerDensityUnit.MegawattPerCentimeter); + public QuantityValue MegawattsPerCentimeter => As(LinearPowerDensityUnit.MegawattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerFoot => As(LinearPowerDensityUnit.MegawattPerFoot); + public QuantityValue MegawattsPerFoot => As(LinearPowerDensityUnit.MegawattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerInch => As(LinearPowerDensityUnit.MegawattPerInch); + public QuantityValue MegawattsPerInch => As(LinearPowerDensityUnit.MegawattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerMeter => As(LinearPowerDensityUnit.MegawattPerMeter); + public QuantityValue MegawattsPerMeter => As(LinearPowerDensityUnit.MegawattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerMillimeter => As(LinearPowerDensityUnit.MegawattPerMillimeter); + public QuantityValue MegawattsPerMillimeter => As(LinearPowerDensityUnit.MegawattPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerCentimeter => As(LinearPowerDensityUnit.MilliwattPerCentimeter); + public QuantityValue MilliwattsPerCentimeter => As(LinearPowerDensityUnit.MilliwattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerFoot => As(LinearPowerDensityUnit.MilliwattPerFoot); + public QuantityValue MilliwattsPerFoot => As(LinearPowerDensityUnit.MilliwattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerInch => As(LinearPowerDensityUnit.MilliwattPerInch); + public QuantityValue MilliwattsPerInch => As(LinearPowerDensityUnit.MilliwattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerMeter => As(LinearPowerDensityUnit.MilliwattPerMeter); + public QuantityValue MilliwattsPerMeter => As(LinearPowerDensityUnit.MilliwattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerMillimeter => As(LinearPowerDensityUnit.MilliwattPerMillimeter); + public QuantityValue MilliwattsPerMillimeter => As(LinearPowerDensityUnit.MilliwattPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerCentimeter => As(LinearPowerDensityUnit.WattPerCentimeter); + public QuantityValue WattsPerCentimeter => As(LinearPowerDensityUnit.WattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerFoot => As(LinearPowerDensityUnit.WattPerFoot); + public QuantityValue WattsPerFoot => As(LinearPowerDensityUnit.WattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerInch => As(LinearPowerDensityUnit.WattPerInch); + public QuantityValue WattsPerInch => As(LinearPowerDensityUnit.WattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerMeter => As(LinearPowerDensityUnit.WattPerMeter); + public QuantityValue WattsPerMeter => As(LinearPowerDensityUnit.WattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerMillimeter => As(LinearPowerDensityUnit.WattPerMillimeter); + public QuantityValue WattsPerMillimeter => As(LinearPowerDensityUnit.WattPerMillimeter); #endregion @@ -434,7 +437,7 @@ public static string GetAbbreviation(LinearPowerDensityUnit unit, IFormatProvide /// If value is NaN or Infinity. public static LinearPowerDensity FromGigawattsPerCentimeter(QuantityValue gigawattspercentimeter) { - double value = (double) gigawattspercentimeter; + QuantityValue value = (QuantityValue) gigawattspercentimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerCentimeter); } @@ -444,7 +447,7 @@ public static LinearPowerDensity FromGigawattsPerCentimeter(QuantityValue gigawa /// If value is NaN or Infinity. public static LinearPowerDensity FromGigawattsPerFoot(QuantityValue gigawattsperfoot) { - double value = (double) gigawattsperfoot; + QuantityValue value = (QuantityValue) gigawattsperfoot; return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerFoot); } @@ -454,7 +457,7 @@ public static LinearPowerDensity FromGigawattsPerFoot(QuantityValue gigawattsper /// If value is NaN or Infinity. public static LinearPowerDensity FromGigawattsPerInch(QuantityValue gigawattsperinch) { - double value = (double) gigawattsperinch; + QuantityValue value = (QuantityValue) gigawattsperinch; return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerInch); } @@ -464,7 +467,7 @@ public static LinearPowerDensity FromGigawattsPerInch(QuantityValue gigawattsper /// If value is NaN or Infinity. public static LinearPowerDensity FromGigawattsPerMeter(QuantityValue gigawattspermeter) { - double value = (double) gigawattspermeter; + QuantityValue value = (QuantityValue) gigawattspermeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerMeter); } @@ -474,7 +477,7 @@ public static LinearPowerDensity FromGigawattsPerMeter(QuantityValue gigawattspe /// If value is NaN or Infinity. public static LinearPowerDensity FromGigawattsPerMillimeter(QuantityValue gigawattspermillimeter) { - double value = (double) gigawattspermillimeter; + QuantityValue value = (QuantityValue) gigawattspermillimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerMillimeter); } @@ -484,7 +487,7 @@ public static LinearPowerDensity FromGigawattsPerMillimeter(QuantityValue gigawa /// If value is NaN or Infinity. public static LinearPowerDensity FromKilowattsPerCentimeter(QuantityValue kilowattspercentimeter) { - double value = (double) kilowattspercentimeter; + QuantityValue value = (QuantityValue) kilowattspercentimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerCentimeter); } @@ -494,7 +497,7 @@ public static LinearPowerDensity FromKilowattsPerCentimeter(QuantityValue kilowa /// If value is NaN or Infinity. public static LinearPowerDensity FromKilowattsPerFoot(QuantityValue kilowattsperfoot) { - double value = (double) kilowattsperfoot; + QuantityValue value = (QuantityValue) kilowattsperfoot; return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerFoot); } @@ -504,7 +507,7 @@ public static LinearPowerDensity FromKilowattsPerFoot(QuantityValue kilowattsper /// If value is NaN or Infinity. public static LinearPowerDensity FromKilowattsPerInch(QuantityValue kilowattsperinch) { - double value = (double) kilowattsperinch; + QuantityValue value = (QuantityValue) kilowattsperinch; return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerInch); } @@ -514,7 +517,7 @@ public static LinearPowerDensity FromKilowattsPerInch(QuantityValue kilowattsper /// If value is NaN or Infinity. public static LinearPowerDensity FromKilowattsPerMeter(QuantityValue kilowattspermeter) { - double value = (double) kilowattspermeter; + QuantityValue value = (QuantityValue) kilowattspermeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerMeter); } @@ -524,7 +527,7 @@ public static LinearPowerDensity FromKilowattsPerMeter(QuantityValue kilowattspe /// If value is NaN or Infinity. public static LinearPowerDensity FromKilowattsPerMillimeter(QuantityValue kilowattspermillimeter) { - double value = (double) kilowattspermillimeter; + QuantityValue value = (QuantityValue) kilowattspermillimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerMillimeter); } @@ -534,7 +537,7 @@ public static LinearPowerDensity FromKilowattsPerMillimeter(QuantityValue kilowa /// If value is NaN or Infinity. public static LinearPowerDensity FromMegawattsPerCentimeter(QuantityValue megawattspercentimeter) { - double value = (double) megawattspercentimeter; + QuantityValue value = (QuantityValue) megawattspercentimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerCentimeter); } @@ -544,7 +547,7 @@ public static LinearPowerDensity FromMegawattsPerCentimeter(QuantityValue megawa /// If value is NaN or Infinity. public static LinearPowerDensity FromMegawattsPerFoot(QuantityValue megawattsperfoot) { - double value = (double) megawattsperfoot; + QuantityValue value = (QuantityValue) megawattsperfoot; return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerFoot); } @@ -554,7 +557,7 @@ public static LinearPowerDensity FromMegawattsPerFoot(QuantityValue megawattsper /// If value is NaN or Infinity. public static LinearPowerDensity FromMegawattsPerInch(QuantityValue megawattsperinch) { - double value = (double) megawattsperinch; + QuantityValue value = (QuantityValue) megawattsperinch; return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerInch); } @@ -564,7 +567,7 @@ public static LinearPowerDensity FromMegawattsPerInch(QuantityValue megawattsper /// If value is NaN or Infinity. public static LinearPowerDensity FromMegawattsPerMeter(QuantityValue megawattspermeter) { - double value = (double) megawattspermeter; + QuantityValue value = (QuantityValue) megawattspermeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerMeter); } @@ -574,7 +577,7 @@ public static LinearPowerDensity FromMegawattsPerMeter(QuantityValue megawattspe /// If value is NaN or Infinity. public static LinearPowerDensity FromMegawattsPerMillimeter(QuantityValue megawattspermillimeter) { - double value = (double) megawattspermillimeter; + QuantityValue value = (QuantityValue) megawattspermillimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerMillimeter); } @@ -584,7 +587,7 @@ public static LinearPowerDensity FromMegawattsPerMillimeter(QuantityValue megawa /// If value is NaN or Infinity. public static LinearPowerDensity FromMilliwattsPerCentimeter(QuantityValue milliwattspercentimeter) { - double value = (double) milliwattspercentimeter; + QuantityValue value = (QuantityValue) milliwattspercentimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerCentimeter); } @@ -594,7 +597,7 @@ public static LinearPowerDensity FromMilliwattsPerCentimeter(QuantityValue milli /// If value is NaN or Infinity. public static LinearPowerDensity FromMilliwattsPerFoot(QuantityValue milliwattsperfoot) { - double value = (double) milliwattsperfoot; + QuantityValue value = (QuantityValue) milliwattsperfoot; return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerFoot); } @@ -604,7 +607,7 @@ public static LinearPowerDensity FromMilliwattsPerFoot(QuantityValue milliwattsp /// If value is NaN or Infinity. public static LinearPowerDensity FromMilliwattsPerInch(QuantityValue milliwattsperinch) { - double value = (double) milliwattsperinch; + QuantityValue value = (QuantityValue) milliwattsperinch; return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerInch); } @@ -614,7 +617,7 @@ public static LinearPowerDensity FromMilliwattsPerInch(QuantityValue milliwattsp /// If value is NaN or Infinity. public static LinearPowerDensity FromMilliwattsPerMeter(QuantityValue milliwattspermeter) { - double value = (double) milliwattspermeter; + QuantityValue value = (QuantityValue) milliwattspermeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerMeter); } @@ -624,7 +627,7 @@ public static LinearPowerDensity FromMilliwattsPerMeter(QuantityValue milliwatts /// If value is NaN or Infinity. public static LinearPowerDensity FromMilliwattsPerMillimeter(QuantityValue milliwattspermillimeter) { - double value = (double) milliwattspermillimeter; + QuantityValue value = (QuantityValue) milliwattspermillimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerMillimeter); } @@ -634,7 +637,7 @@ public static LinearPowerDensity FromMilliwattsPerMillimeter(QuantityValue milli /// If value is NaN or Infinity. public static LinearPowerDensity FromWattsPerCentimeter(QuantityValue wattspercentimeter) { - double value = (double) wattspercentimeter; + QuantityValue value = (QuantityValue) wattspercentimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerCentimeter); } @@ -644,7 +647,7 @@ public static LinearPowerDensity FromWattsPerCentimeter(QuantityValue wattsperce /// If value is NaN or Infinity. public static LinearPowerDensity FromWattsPerFoot(QuantityValue wattsperfoot) { - double value = (double) wattsperfoot; + QuantityValue value = (QuantityValue) wattsperfoot; return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerFoot); } @@ -654,7 +657,7 @@ public static LinearPowerDensity FromWattsPerFoot(QuantityValue wattsperfoot) /// If value is NaN or Infinity. public static LinearPowerDensity FromWattsPerInch(QuantityValue wattsperinch) { - double value = (double) wattsperinch; + QuantityValue value = (QuantityValue) wattsperinch; return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerInch); } @@ -664,7 +667,7 @@ public static LinearPowerDensity FromWattsPerInch(QuantityValue wattsperinch) /// If value is NaN or Infinity. public static LinearPowerDensity FromWattsPerMeter(QuantityValue wattspermeter) { - double value = (double) wattspermeter; + QuantityValue value = (QuantityValue) wattspermeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerMeter); } @@ -674,7 +677,7 @@ public static LinearPowerDensity FromWattsPerMeter(QuantityValue wattspermeter) /// If value is NaN or Infinity. public static LinearPowerDensity FromWattsPerMillimeter(QuantityValue wattspermillimeter) { - double value = (double) wattspermillimeter; + QuantityValue value = (QuantityValue) wattspermillimeter; return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerMillimeter); } @@ -686,7 +689,7 @@ public static LinearPowerDensity FromWattsPerMillimeter(QuantityValue wattspermi /// LinearPowerDensity unit value. public static LinearPowerDensity From(QuantityValue value, LinearPowerDensityUnit fromUnit) { - return new LinearPowerDensity((double)value, fromUnit); + return new LinearPowerDensity((QuantityValue)value, fromUnit); } #endregion @@ -856,25 +859,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Linea } /// Get from multiplying value and . - public static LinearPowerDensity operator *(double left, LinearPowerDensity right) + public static LinearPowerDensity operator *(QuantityValue left, LinearPowerDensity right) { return new LinearPowerDensity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static LinearPowerDensity operator *(LinearPowerDensity left, double right) + public static LinearPowerDensity operator *(LinearPowerDensity left, QuantityValue right) { return new LinearPowerDensity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static LinearPowerDensity operator /(LinearPowerDensity left, double right) + public static LinearPowerDensity operator /(LinearPowerDensity left, QuantityValue right) { return new LinearPowerDensity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(LinearPowerDensity left, LinearPowerDensity right) + public static QuantityValue operator /(LinearPowerDensity left, LinearPowerDensity right) { return left.WattsPerMeter / right.WattsPerMeter; } @@ -907,6 +910,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Linea return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(LinearPowerDensity left, LinearPowerDensity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(LinearPowerDensity left, LinearPowerDensity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -919,7 +935,29 @@ public int CompareTo(object obj) /// public int CompareTo(LinearPowerDensity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is LinearPowerDensity objLinearPowerDensity)) + return false; + return Equals(objLinearPowerDensity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(LinearPowerDensity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -962,13 +1000,13 @@ public int CompareTo(LinearPowerDensity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LinearPowerDensity other, double tolerance, ComparisonType comparisonType) + public bool Equals(LinearPowerDensity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -979,7 +1017,7 @@ public bool Equals(LinearPowerDensity other, double tolerance, ComparisonType co /// A hash code for the current LinearPowerDensity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -990,17 +1028,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(LinearPowerDensityUnit unit) + public QuantityValue As(LinearPowerDensityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1015,12 +1052,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is LinearPowerDensityUnit unitAsLinearPowerDensityUnit)) + if (!(unit is LinearPowerDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearPowerDensityUnit)} is supported.", nameof(unit)); - return As(unitAsLinearPowerDensityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1052,7 +1089,7 @@ public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit, UnitConverter unit var converted = conversionFunction(this); return (LinearPowerDensity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(LinearPowerDensityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1060,17 +1097,17 @@ public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit, UnitConverter unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LinearPowerDensityUnit unitAsLinearPowerDensityUnit)) + if (!(unit is LinearPowerDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearPowerDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLinearPowerDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1097,10 +1134,10 @@ public LinearPowerDensity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(LinearPowerDensityUnit unit) + private QuantityValue GetValueAs(LinearPowerDensityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs index d78acbfd8c..0f8d6b6604 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminosity /// [DataContract] - public partial struct Luminosity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Luminosity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -88,9 +88,9 @@ static Luminosity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Luminosity(double value, LuminosityUnit unit) + public Luminosity(QuantityValue value, LuminosityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -102,14 +102,14 @@ public Luminosity(double value, LuminosityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Luminosity(double value, UnitSystem unitSystem) + public Luminosity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -150,7 +150,10 @@ public Luminosity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -173,74 +176,74 @@ public Luminosity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decawatts => As(LuminosityUnit.Decawatt); + public QuantityValue Decawatts => As(LuminosityUnit.Decawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Deciwatts => As(LuminosityUnit.Deciwatt); + public QuantityValue Deciwatts => As(LuminosityUnit.Deciwatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Femtowatts => As(LuminosityUnit.Femtowatt); + public QuantityValue Femtowatts => As(LuminosityUnit.Femtowatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gigawatts => As(LuminosityUnit.Gigawatt); + public QuantityValue Gigawatts => As(LuminosityUnit.Gigawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilowatts => As(LuminosityUnit.Kilowatt); + public QuantityValue Kilowatts => As(LuminosityUnit.Kilowatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megawatts => As(LuminosityUnit.Megawatt); + public QuantityValue Megawatts => As(LuminosityUnit.Megawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microwatts => As(LuminosityUnit.Microwatt); + public QuantityValue Microwatts => As(LuminosityUnit.Microwatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milliwatts => As(LuminosityUnit.Milliwatt); + public QuantityValue Milliwatts => As(LuminosityUnit.Milliwatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanowatts => As(LuminosityUnit.Nanowatt); + public QuantityValue Nanowatts => As(LuminosityUnit.Nanowatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Petawatts => As(LuminosityUnit.Petawatt); + public QuantityValue Petawatts => As(LuminosityUnit.Petawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Picowatts => As(LuminosityUnit.Picowatt); + public QuantityValue Picowatts => As(LuminosityUnit.Picowatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SolarLuminosities => As(LuminosityUnit.SolarLuminosity); + public QuantityValue SolarLuminosities => As(LuminosityUnit.SolarLuminosity); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Terawatts => As(LuminosityUnit.Terawatt); + public QuantityValue Terawatts => As(LuminosityUnit.Terawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Watts => As(LuminosityUnit.Watt); + public QuantityValue Watts => As(LuminosityUnit.Watt); #endregion @@ -335,7 +338,7 @@ public static string GetAbbreviation(LuminosityUnit unit, IFormatProvider? provi /// If value is NaN or Infinity. public static Luminosity FromDecawatts(QuantityValue decawatts) { - double value = (double) decawatts; + QuantityValue value = (QuantityValue) decawatts; return new Luminosity(value, LuminosityUnit.Decawatt); } @@ -345,7 +348,7 @@ public static Luminosity FromDecawatts(QuantityValue decawatts) /// If value is NaN or Infinity. public static Luminosity FromDeciwatts(QuantityValue deciwatts) { - double value = (double) deciwatts; + QuantityValue value = (QuantityValue) deciwatts; return new Luminosity(value, LuminosityUnit.Deciwatt); } @@ -355,7 +358,7 @@ public static Luminosity FromDeciwatts(QuantityValue deciwatts) /// If value is NaN or Infinity. public static Luminosity FromFemtowatts(QuantityValue femtowatts) { - double value = (double) femtowatts; + QuantityValue value = (QuantityValue) femtowatts; return new Luminosity(value, LuminosityUnit.Femtowatt); } @@ -365,7 +368,7 @@ public static Luminosity FromFemtowatts(QuantityValue femtowatts) /// If value is NaN or Infinity. public static Luminosity FromGigawatts(QuantityValue gigawatts) { - double value = (double) gigawatts; + QuantityValue value = (QuantityValue) gigawatts; return new Luminosity(value, LuminosityUnit.Gigawatt); } @@ -375,7 +378,7 @@ public static Luminosity FromGigawatts(QuantityValue gigawatts) /// If value is NaN or Infinity. public static Luminosity FromKilowatts(QuantityValue kilowatts) { - double value = (double) kilowatts; + QuantityValue value = (QuantityValue) kilowatts; return new Luminosity(value, LuminosityUnit.Kilowatt); } @@ -385,7 +388,7 @@ public static Luminosity FromKilowatts(QuantityValue kilowatts) /// If value is NaN or Infinity. public static Luminosity FromMegawatts(QuantityValue megawatts) { - double value = (double) megawatts; + QuantityValue value = (QuantityValue) megawatts; return new Luminosity(value, LuminosityUnit.Megawatt); } @@ -395,7 +398,7 @@ public static Luminosity FromMegawatts(QuantityValue megawatts) /// If value is NaN or Infinity. public static Luminosity FromMicrowatts(QuantityValue microwatts) { - double value = (double) microwatts; + QuantityValue value = (QuantityValue) microwatts; return new Luminosity(value, LuminosityUnit.Microwatt); } @@ -405,7 +408,7 @@ public static Luminosity FromMicrowatts(QuantityValue microwatts) /// If value is NaN or Infinity. public static Luminosity FromMilliwatts(QuantityValue milliwatts) { - double value = (double) milliwatts; + QuantityValue value = (QuantityValue) milliwatts; return new Luminosity(value, LuminosityUnit.Milliwatt); } @@ -415,7 +418,7 @@ public static Luminosity FromMilliwatts(QuantityValue milliwatts) /// If value is NaN or Infinity. public static Luminosity FromNanowatts(QuantityValue nanowatts) { - double value = (double) nanowatts; + QuantityValue value = (QuantityValue) nanowatts; return new Luminosity(value, LuminosityUnit.Nanowatt); } @@ -425,7 +428,7 @@ public static Luminosity FromNanowatts(QuantityValue nanowatts) /// If value is NaN or Infinity. public static Luminosity FromPetawatts(QuantityValue petawatts) { - double value = (double) petawatts; + QuantityValue value = (QuantityValue) petawatts; return new Luminosity(value, LuminosityUnit.Petawatt); } @@ -435,7 +438,7 @@ public static Luminosity FromPetawatts(QuantityValue petawatts) /// If value is NaN or Infinity. public static Luminosity FromPicowatts(QuantityValue picowatts) { - double value = (double) picowatts; + QuantityValue value = (QuantityValue) picowatts; return new Luminosity(value, LuminosityUnit.Picowatt); } @@ -445,7 +448,7 @@ public static Luminosity FromPicowatts(QuantityValue picowatts) /// If value is NaN or Infinity. public static Luminosity FromSolarLuminosities(QuantityValue solarluminosities) { - double value = (double) solarluminosities; + QuantityValue value = (QuantityValue) solarluminosities; return new Luminosity(value, LuminosityUnit.SolarLuminosity); } @@ -455,7 +458,7 @@ public static Luminosity FromSolarLuminosities(QuantityValue solarluminosities) /// If value is NaN or Infinity. public static Luminosity FromTerawatts(QuantityValue terawatts) { - double value = (double) terawatts; + QuantityValue value = (QuantityValue) terawatts; return new Luminosity(value, LuminosityUnit.Terawatt); } @@ -465,7 +468,7 @@ public static Luminosity FromTerawatts(QuantityValue terawatts) /// If value is NaN or Infinity. public static Luminosity FromWatts(QuantityValue watts) { - double value = (double) watts; + QuantityValue value = (QuantityValue) watts; return new Luminosity(value, LuminosityUnit.Watt); } @@ -477,7 +480,7 @@ public static Luminosity FromWatts(QuantityValue watts) /// Luminosity unit value. public static Luminosity From(QuantityValue value, LuminosityUnit fromUnit) { - return new Luminosity((double)value, fromUnit); + return new Luminosity((QuantityValue)value, fromUnit); } #endregion @@ -647,25 +650,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin } /// Get from multiplying value and . - public static Luminosity operator *(double left, Luminosity right) + public static Luminosity operator *(QuantityValue left, Luminosity right) { return new Luminosity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Luminosity operator *(Luminosity left, double right) + public static Luminosity operator *(Luminosity left, QuantityValue right) { return new Luminosity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Luminosity operator /(Luminosity left, double right) + public static Luminosity operator /(Luminosity left, QuantityValue right) { return new Luminosity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Luminosity left, Luminosity right) + public static QuantityValue operator /(Luminosity left, Luminosity right) { return left.Watts / right.Watts; } @@ -698,6 +701,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Luminosity left, Luminosity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Luminosity left, Luminosity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -710,7 +726,29 @@ public int CompareTo(object obj) /// public int CompareTo(Luminosity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Luminosity objLuminosity)) + return false; + return Equals(objLuminosity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Luminosity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -753,13 +791,13 @@ public int CompareTo(Luminosity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Luminosity other, double tolerance, ComparisonType comparisonType) + public bool Equals(Luminosity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -770,7 +808,7 @@ public bool Equals(Luminosity other, double tolerance, ComparisonType comparison /// A hash code for the current Luminosity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -781,17 +819,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(LuminosityUnit unit) + public QuantityValue As(LuminosityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -806,12 +843,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is LuminosityUnit unitAsLuminosityUnit)) + if (!(unit is LuminosityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminosityUnit)} is supported.", nameof(unit)); - return As(unitAsLuminosityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -843,7 +880,7 @@ public Luminosity ToUnit(LuminosityUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Luminosity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(LuminosityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -851,17 +888,17 @@ public Luminosity ToUnit(LuminosityUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LuminosityUnit unitAsLuminosityUnit)) + if (!(unit is LuminosityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminosityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLuminosityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -888,10 +925,10 @@ public Luminosity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(LuminosityUnit unit) + private QuantityValue GetValueAs(LuminosityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs index debe7b5dd7..815f8a24de 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminous_flux /// [DataContract] - public partial struct LuminousFlux : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct LuminousFlux : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static LuminousFlux() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public LuminousFlux(double value, LuminousFluxUnit unit) + public LuminousFlux(QuantityValue value, LuminousFluxUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public LuminousFlux(double value, LuminousFluxUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public LuminousFlux(double value, UnitSystem unitSystem) + public LuminousFlux(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public LuminousFlux(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public LuminousFlux(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Lumens => As(LuminousFluxUnit.Lumen); + public QuantityValue Lumens => As(LuminousFluxUnit.Lumen); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(LuminousFluxUnit unit, IFormatProvider? pro /// If value is NaN or Infinity. public static LuminousFlux FromLumens(QuantityValue lumens) { - double value = (double) lumens; + QuantityValue value = (QuantityValue) lumens; return new LuminousFlux(value, LuminousFluxUnit.Lumen); } @@ -230,7 +233,7 @@ public static LuminousFlux FromLumens(QuantityValue lumens) /// LuminousFlux unit value. public static LuminousFlux From(QuantityValue value, LuminousFluxUnit fromUnit) { - return new LuminousFlux((double)value, fromUnit); + return new LuminousFlux((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin } /// Get from multiplying value and . - public static LuminousFlux operator *(double left, LuminousFlux right) + public static LuminousFlux operator *(QuantityValue left, LuminousFlux right) { return new LuminousFlux(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static LuminousFlux operator *(LuminousFlux left, double right) + public static LuminousFlux operator *(LuminousFlux left, QuantityValue right) { return new LuminousFlux(left.Value * right, left.Unit); } /// Get from dividing by value. - public static LuminousFlux operator /(LuminousFlux left, double right) + public static LuminousFlux operator /(LuminousFlux left, QuantityValue right) { return new LuminousFlux(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(LuminousFlux left, LuminousFlux right) + public static QuantityValue operator /(LuminousFlux left, LuminousFlux right) { return left.Lumens / right.Lumens; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(LuminousFlux left, LuminousFlux right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(LuminousFlux left, LuminousFlux right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(LuminousFlux other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is LuminousFlux objLuminousFlux)) + return false; + return Equals(objLuminousFlux); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(LuminousFlux other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(LuminousFlux other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LuminousFlux other, double tolerance, ComparisonType comparisonType) + public bool Equals(LuminousFlux other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(LuminousFlux other, double tolerance, ComparisonType comparis /// A hash code for the current LuminousFlux. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(LuminousFluxUnit unit) + public QuantityValue As(LuminousFluxUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is LuminousFluxUnit unitAsLuminousFluxUnit)) + if (!(unit is LuminousFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousFluxUnit)} is supported.", nameof(unit)); - return As(unitAsLuminousFluxUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public LuminousFlux ToUnit(LuminousFluxUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (LuminousFlux)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(LuminousFluxUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public LuminousFlux ToUnit(LuminousFluxUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LuminousFluxUnit unitAsLuminousFluxUnit)) + if (!(unit is LuminousFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousFluxUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLuminousFluxUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public LuminousFlux ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(LuminousFluxUnit unit) + private QuantityValue GetValueAs(LuminousFluxUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs index 82199274f5..0e338c9e86 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminous_intensity /// [DataContract] - public partial struct LuminousIntensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct LuminousIntensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static LuminousIntensity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public LuminousIntensity(double value, LuminousIntensityUnit unit) + public LuminousIntensity(QuantityValue value, LuminousIntensityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public LuminousIntensity(double value, LuminousIntensityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public LuminousIntensity(double value, UnitSystem unitSystem) + public LuminousIntensity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public LuminousIntensity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public LuminousIntensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Candela => As(LuminousIntensityUnit.Candela); + public QuantityValue Candela => As(LuminousIntensityUnit.Candela); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(LuminousIntensityUnit unit, IFormatProvider /// If value is NaN or Infinity. public static LuminousIntensity FromCandela(QuantityValue candela) { - double value = (double) candela; + QuantityValue value = (QuantityValue) candela; return new LuminousIntensity(value, LuminousIntensityUnit.Candela); } @@ -230,7 +233,7 @@ public static LuminousIntensity FromCandela(QuantityValue candela) /// LuminousIntensity unit value. public static LuminousIntensity From(QuantityValue value, LuminousIntensityUnit fromUnit) { - return new LuminousIntensity((double)value, fromUnit); + return new LuminousIntensity((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin } /// Get from multiplying value and . - public static LuminousIntensity operator *(double left, LuminousIntensity right) + public static LuminousIntensity operator *(QuantityValue left, LuminousIntensity right) { return new LuminousIntensity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static LuminousIntensity operator *(LuminousIntensity left, double right) + public static LuminousIntensity operator *(LuminousIntensity left, QuantityValue right) { return new LuminousIntensity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static LuminousIntensity operator /(LuminousIntensity left, double right) + public static LuminousIntensity operator /(LuminousIntensity left, QuantityValue right) { return new LuminousIntensity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(LuminousIntensity left, LuminousIntensity right) + public static QuantityValue operator /(LuminousIntensity left, LuminousIntensity right) { return left.Candela / right.Candela; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(LuminousIntensity left, LuminousIntensity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(LuminousIntensity left, LuminousIntensity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(LuminousIntensity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is LuminousIntensity objLuminousIntensity)) + return false; + return Equals(objLuminousIntensity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(LuminousIntensity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(LuminousIntensity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LuminousIntensity other, double tolerance, ComparisonType comparisonType) + public bool Equals(LuminousIntensity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(LuminousIntensity other, double tolerance, ComparisonType com /// A hash code for the current LuminousIntensity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(LuminousIntensityUnit unit) + public QuantityValue As(LuminousIntensityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is LuminousIntensityUnit unitAsLuminousIntensityUnit)) + if (!(unit is LuminousIntensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousIntensityUnit)} is supported.", nameof(unit)); - return As(unitAsLuminousIntensityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public LuminousIntensity ToUnit(LuminousIntensityUnit unit, UnitConverter unitCo var converted = conversionFunction(this); return (LuminousIntensity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(LuminousIntensityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public LuminousIntensity ToUnit(LuminousIntensityUnit unit, UnitConverter unitCo } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LuminousIntensityUnit unitAsLuminousIntensityUnit)) + if (!(unit is LuminousIntensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousIntensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLuminousIntensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public LuminousIntensity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(LuminousIntensityUnit unit) + private QuantityValue GetValueAs(LuminousIntensityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs index 6103ff0bc9..11250ee88c 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Magnetic_field /// [DataContract] - public partial struct MagneticField : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MagneticField : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -80,9 +80,9 @@ static MagneticField() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MagneticField(double value, MagneticFieldUnit unit) + public MagneticField(QuantityValue value, MagneticFieldUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -94,14 +94,14 @@ public MagneticField(double value, MagneticFieldUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MagneticField(double value, UnitSystem unitSystem) + public MagneticField(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -142,7 +142,10 @@ public MagneticField(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -165,34 +168,34 @@ public MagneticField(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gausses => As(MagneticFieldUnit.Gauss); + public QuantityValue Gausses => As(MagneticFieldUnit.Gauss); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microteslas => As(MagneticFieldUnit.Microtesla); + public QuantityValue Microteslas => As(MagneticFieldUnit.Microtesla); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milligausses => As(MagneticFieldUnit.Milligauss); + public QuantityValue Milligausses => As(MagneticFieldUnit.Milligauss); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milliteslas => As(MagneticFieldUnit.Millitesla); + public QuantityValue Milliteslas => As(MagneticFieldUnit.Millitesla); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanoteslas => As(MagneticFieldUnit.Nanotesla); + public QuantityValue Nanoteslas => As(MagneticFieldUnit.Nanotesla); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Teslas => As(MagneticFieldUnit.Tesla); + public QuantityValue Teslas => As(MagneticFieldUnit.Tesla); #endregion @@ -263,7 +266,7 @@ public static string GetAbbreviation(MagneticFieldUnit unit, IFormatProvider? pr /// If value is NaN or Infinity. public static MagneticField FromGausses(QuantityValue gausses) { - double value = (double) gausses; + QuantityValue value = (QuantityValue) gausses; return new MagneticField(value, MagneticFieldUnit.Gauss); } @@ -273,7 +276,7 @@ public static MagneticField FromGausses(QuantityValue gausses) /// If value is NaN or Infinity. public static MagneticField FromMicroteslas(QuantityValue microteslas) { - double value = (double) microteslas; + QuantityValue value = (QuantityValue) microteslas; return new MagneticField(value, MagneticFieldUnit.Microtesla); } @@ -283,7 +286,7 @@ public static MagneticField FromMicroteslas(QuantityValue microteslas) /// If value is NaN or Infinity. public static MagneticField FromMilligausses(QuantityValue milligausses) { - double value = (double) milligausses; + QuantityValue value = (QuantityValue) milligausses; return new MagneticField(value, MagneticFieldUnit.Milligauss); } @@ -293,7 +296,7 @@ public static MagneticField FromMilligausses(QuantityValue milligausses) /// If value is NaN or Infinity. public static MagneticField FromMilliteslas(QuantityValue milliteslas) { - double value = (double) milliteslas; + QuantityValue value = (QuantityValue) milliteslas; return new MagneticField(value, MagneticFieldUnit.Millitesla); } @@ -303,7 +306,7 @@ public static MagneticField FromMilliteslas(QuantityValue milliteslas) /// If value is NaN or Infinity. public static MagneticField FromNanoteslas(QuantityValue nanoteslas) { - double value = (double) nanoteslas; + QuantityValue value = (QuantityValue) nanoteslas; return new MagneticField(value, MagneticFieldUnit.Nanotesla); } @@ -313,7 +316,7 @@ public static MagneticField FromNanoteslas(QuantityValue nanoteslas) /// If value is NaN or Infinity. public static MagneticField FromTeslas(QuantityValue teslas) { - double value = (double) teslas; + QuantityValue value = (QuantityValue) teslas; return new MagneticField(value, MagneticFieldUnit.Tesla); } @@ -325,7 +328,7 @@ public static MagneticField FromTeslas(QuantityValue teslas) /// MagneticField unit value. public static MagneticField From(QuantityValue value, MagneticFieldUnit fromUnit) { - return new MagneticField((double)value, fromUnit); + return new MagneticField((QuantityValue)value, fromUnit); } #endregion @@ -495,25 +498,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Magne } /// Get from multiplying value and . - public static MagneticField operator *(double left, MagneticField right) + public static MagneticField operator *(QuantityValue left, MagneticField right) { return new MagneticField(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MagneticField operator *(MagneticField left, double right) + public static MagneticField operator *(MagneticField left, QuantityValue right) { return new MagneticField(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MagneticField operator /(MagneticField left, double right) + public static MagneticField operator /(MagneticField left, QuantityValue right) { return new MagneticField(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MagneticField left, MagneticField right) + public static QuantityValue operator /(MagneticField left, MagneticField right) { return left.Teslas / right.Teslas; } @@ -546,6 +549,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Magne return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MagneticField left, MagneticField right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MagneticField left, MagneticField right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -558,7 +574,29 @@ public int CompareTo(object obj) /// public int CompareTo(MagneticField other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MagneticField objMagneticField)) + return false; + return Equals(objMagneticField); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MagneticField other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -601,13 +639,13 @@ public int CompareTo(MagneticField other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MagneticField other, double tolerance, ComparisonType comparisonType) + public bool Equals(MagneticField other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -618,7 +656,7 @@ public bool Equals(MagneticField other, double tolerance, ComparisonType compari /// A hash code for the current MagneticField. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -629,17 +667,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MagneticFieldUnit unit) + public QuantityValue As(MagneticFieldUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -654,12 +691,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MagneticFieldUnit unitAsMagneticFieldUnit)) + if (!(unit is MagneticFieldUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFieldUnit)} is supported.", nameof(unit)); - return As(unitAsMagneticFieldUnit); + return (QuantityValue)As(typedUnit); } /// @@ -691,7 +728,7 @@ public MagneticField ToUnit(MagneticFieldUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (MagneticField)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MagneticFieldUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -699,17 +736,17 @@ public MagneticField ToUnit(MagneticFieldUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MagneticFieldUnit unitAsMagneticFieldUnit)) + if (!(unit is MagneticFieldUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFieldUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMagneticFieldUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -736,10 +773,10 @@ public MagneticField ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MagneticFieldUnit unit) + private QuantityValue GetValueAs(MagneticFieldUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs index 4be6d9f2f7..d5bd23d80a 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Magnetic_flux /// [DataContract] - public partial struct MagneticFlux : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MagneticFlux : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static MagneticFlux() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MagneticFlux(double value, MagneticFluxUnit unit) + public MagneticFlux(QuantityValue value, MagneticFluxUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public MagneticFlux(double value, MagneticFluxUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MagneticFlux(double value, UnitSystem unitSystem) + public MagneticFlux(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public MagneticFlux(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public MagneticFlux(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Webers => As(MagneticFluxUnit.Weber); + public QuantityValue Webers => As(MagneticFluxUnit.Weber); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(MagneticFluxUnit unit, IFormatProvider? pro /// If value is NaN or Infinity. public static MagneticFlux FromWebers(QuantityValue webers) { - double value = (double) webers; + QuantityValue value = (QuantityValue) webers; return new MagneticFlux(value, MagneticFluxUnit.Weber); } @@ -230,7 +233,7 @@ public static MagneticFlux FromWebers(QuantityValue webers) /// MagneticFlux unit value. public static MagneticFlux From(QuantityValue value, MagneticFluxUnit fromUnit) { - return new MagneticFlux((double)value, fromUnit); + return new MagneticFlux((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Magne } /// Get from multiplying value and . - public static MagneticFlux operator *(double left, MagneticFlux right) + public static MagneticFlux operator *(QuantityValue left, MagneticFlux right) { return new MagneticFlux(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MagneticFlux operator *(MagneticFlux left, double right) + public static MagneticFlux operator *(MagneticFlux left, QuantityValue right) { return new MagneticFlux(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MagneticFlux operator /(MagneticFlux left, double right) + public static MagneticFlux operator /(MagneticFlux left, QuantityValue right) { return new MagneticFlux(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MagneticFlux left, MagneticFlux right) + public static QuantityValue operator /(MagneticFlux left, MagneticFlux right) { return left.Webers / right.Webers; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Magne return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MagneticFlux left, MagneticFlux right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MagneticFlux left, MagneticFlux right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(MagneticFlux other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MagneticFlux objMagneticFlux)) + return false; + return Equals(objMagneticFlux); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MagneticFlux other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(MagneticFlux other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MagneticFlux other, double tolerance, ComparisonType comparisonType) + public bool Equals(MagneticFlux other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(MagneticFlux other, double tolerance, ComparisonType comparis /// A hash code for the current MagneticFlux. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MagneticFluxUnit unit) + public QuantityValue As(MagneticFluxUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MagneticFluxUnit unitAsMagneticFluxUnit)) + if (!(unit is MagneticFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFluxUnit)} is supported.", nameof(unit)); - return As(unitAsMagneticFluxUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public MagneticFlux ToUnit(MagneticFluxUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (MagneticFlux)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MagneticFluxUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public MagneticFlux ToUnit(MagneticFluxUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MagneticFluxUnit unitAsMagneticFluxUnit)) + if (!(unit is MagneticFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFluxUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMagneticFluxUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public MagneticFlux ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MagneticFluxUnit unit) + private QuantityValue GetValueAs(MagneticFluxUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs index f9a7bc0f03..1696417a38 100644 --- a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Magnetization /// [DataContract] - public partial struct Magnetization : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Magnetization : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static Magnetization() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Magnetization(double value, MagnetizationUnit unit) + public Magnetization(QuantityValue value, MagnetizationUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public Magnetization(double value, MagnetizationUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Magnetization(double value, UnitSystem unitSystem) + public Magnetization(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public Magnetization(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public Magnetization(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); + public QuantityValue AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(MagnetizationUnit unit, IFormatProvider? pr /// If value is NaN or Infinity. public static Magnetization FromAmperesPerMeter(QuantityValue amperespermeter) { - double value = (double) amperespermeter; + QuantityValue value = (QuantityValue) amperespermeter; return new Magnetization(value, MagnetizationUnit.AmperePerMeter); } @@ -230,7 +233,7 @@ public static Magnetization FromAmperesPerMeter(QuantityValue amperespermeter) /// Magnetization unit value. public static Magnetization From(QuantityValue value, MagnetizationUnit fromUnit) { - return new Magnetization((double)value, fromUnit); + return new Magnetization((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Magne } /// Get from multiplying value and . - public static Magnetization operator *(double left, Magnetization right) + public static Magnetization operator *(QuantityValue left, Magnetization right) { return new Magnetization(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Magnetization operator *(Magnetization left, double right) + public static Magnetization operator *(Magnetization left, QuantityValue right) { return new Magnetization(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Magnetization operator /(Magnetization left, double right) + public static Magnetization operator /(Magnetization left, QuantityValue right) { return new Magnetization(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Magnetization left, Magnetization right) + public static QuantityValue operator /(Magnetization left, Magnetization right) { return left.AmperesPerMeter / right.AmperesPerMeter; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Magne return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Magnetization left, Magnetization right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Magnetization left, Magnetization right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(Magnetization other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Magnetization objMagnetization)) + return false; + return Equals(objMagnetization); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Magnetization other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(Magnetization other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Magnetization other, double tolerance, ComparisonType comparisonType) + public bool Equals(Magnetization other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(Magnetization other, double tolerance, ComparisonType compari /// A hash code for the current Magnetization. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MagnetizationUnit unit) + public QuantityValue As(MagnetizationUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MagnetizationUnit unitAsMagnetizationUnit)) + if (!(unit is MagnetizationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagnetizationUnit)} is supported.", nameof(unit)); - return As(unitAsMagnetizationUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public Magnetization ToUnit(MagnetizationUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Magnetization)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MagnetizationUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public Magnetization ToUnit(MagnetizationUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MagnetizationUnit unitAsMagnetizationUnit)) + if (!(unit is MagnetizationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagnetizationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMagnetizationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public Magnetization ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MagnetizationUnit unit) + private QuantityValue GetValueAs(MagnetizationUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs index 16ecf48781..968a692d08 100644 --- a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In physics, mass (from Greek μᾶζα "barley cake, lump [of dough]") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg). /// [DataContract] - public partial struct Mass : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Mass : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -96,9 +96,9 @@ static Mass() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Mass(double value, MassUnit unit) + public Mass(QuantityValue value, MassUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -110,14 +110,14 @@ public Mass(double value, MassUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Mass(double value, UnitSystem unitSystem) + public Mass(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -158,7 +158,10 @@ public Mass(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -181,129 +184,129 @@ public Mass(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Centigrams => As(MassUnit.Centigram); + public QuantityValue Centigrams => As(MassUnit.Centigram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decagrams => As(MassUnit.Decagram); + public QuantityValue Decagrams => As(MassUnit.Decagram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decigrams => As(MassUnit.Decigram); + public QuantityValue Decigrams => As(MassUnit.Decigram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double EarthMasses => As(MassUnit.EarthMass); + public QuantityValue EarthMasses => As(MassUnit.EarthMass); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Grains => As(MassUnit.Grain); + public QuantityValue Grains => As(MassUnit.Grain); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Grams => As(MassUnit.Gram); + public QuantityValue Grams => As(MassUnit.Gram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Hectograms => As(MassUnit.Hectogram); + public QuantityValue Hectograms => As(MassUnit.Hectogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilograms => As(MassUnit.Kilogram); + public QuantityValue Kilograms => As(MassUnit.Kilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilopounds => As(MassUnit.Kilopound); + public QuantityValue Kilopounds => As(MassUnit.Kilopound); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilotonnes => As(MassUnit.Kilotonne); + public QuantityValue Kilotonnes => As(MassUnit.Kilotonne); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LongHundredweight => As(MassUnit.LongHundredweight); + public QuantityValue LongHundredweight => As(MassUnit.LongHundredweight); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LongTons => As(MassUnit.LongTon); + public QuantityValue LongTons => As(MassUnit.LongTon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megapounds => As(MassUnit.Megapound); + public QuantityValue Megapounds => As(MassUnit.Megapound); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megatonnes => As(MassUnit.Megatonne); + public QuantityValue Megatonnes => As(MassUnit.Megatonne); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Micrograms => As(MassUnit.Microgram); + public QuantityValue Micrograms => As(MassUnit.Microgram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milligrams => As(MassUnit.Milligram); + public QuantityValue Milligrams => As(MassUnit.Milligram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanograms => As(MassUnit.Nanogram); + public QuantityValue Nanograms => As(MassUnit.Nanogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Ounces => As(MassUnit.Ounce); + public QuantityValue Ounces => As(MassUnit.Ounce); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Pounds => As(MassUnit.Pound); + public QuantityValue Pounds => As(MassUnit.Pound); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ShortHundredweight => As(MassUnit.ShortHundredweight); + public QuantityValue ShortHundredweight => As(MassUnit.ShortHundredweight); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ShortTons => As(MassUnit.ShortTon); + public QuantityValue ShortTons => As(MassUnit.ShortTon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Slugs => As(MassUnit.Slug); + public QuantityValue Slugs => As(MassUnit.Slug); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SolarMasses => As(MassUnit.SolarMass); + public QuantityValue SolarMasses => As(MassUnit.SolarMass); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Stone => As(MassUnit.Stone); + public QuantityValue Stone => As(MassUnit.Stone); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Tonnes => As(MassUnit.Tonne); + public QuantityValue Tonnes => As(MassUnit.Tonne); #endregion @@ -466,7 +469,7 @@ public static string GetAbbreviation(MassUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Mass FromCentigrams(QuantityValue centigrams) { - double value = (double) centigrams; + QuantityValue value = (QuantityValue) centigrams; return new Mass(value, MassUnit.Centigram); } @@ -476,7 +479,7 @@ public static Mass FromCentigrams(QuantityValue centigrams) /// If value is NaN or Infinity. public static Mass FromDecagrams(QuantityValue decagrams) { - double value = (double) decagrams; + QuantityValue value = (QuantityValue) decagrams; return new Mass(value, MassUnit.Decagram); } @@ -486,7 +489,7 @@ public static Mass FromDecagrams(QuantityValue decagrams) /// If value is NaN or Infinity. public static Mass FromDecigrams(QuantityValue decigrams) { - double value = (double) decigrams; + QuantityValue value = (QuantityValue) decigrams; return new Mass(value, MassUnit.Decigram); } @@ -496,7 +499,7 @@ public static Mass FromDecigrams(QuantityValue decigrams) /// If value is NaN or Infinity. public static Mass FromEarthMasses(QuantityValue earthmasses) { - double value = (double) earthmasses; + QuantityValue value = (QuantityValue) earthmasses; return new Mass(value, MassUnit.EarthMass); } @@ -506,7 +509,7 @@ public static Mass FromEarthMasses(QuantityValue earthmasses) /// If value is NaN or Infinity. public static Mass FromGrains(QuantityValue grains) { - double value = (double) grains; + QuantityValue value = (QuantityValue) grains; return new Mass(value, MassUnit.Grain); } @@ -516,7 +519,7 @@ public static Mass FromGrains(QuantityValue grains) /// If value is NaN or Infinity. public static Mass FromGrams(QuantityValue grams) { - double value = (double) grams; + QuantityValue value = (QuantityValue) grams; return new Mass(value, MassUnit.Gram); } @@ -526,7 +529,7 @@ public static Mass FromGrams(QuantityValue grams) /// If value is NaN or Infinity. public static Mass FromHectograms(QuantityValue hectograms) { - double value = (double) hectograms; + QuantityValue value = (QuantityValue) hectograms; return new Mass(value, MassUnit.Hectogram); } @@ -536,7 +539,7 @@ public static Mass FromHectograms(QuantityValue hectograms) /// If value is NaN or Infinity. public static Mass FromKilograms(QuantityValue kilograms) { - double value = (double) kilograms; + QuantityValue value = (QuantityValue) kilograms; return new Mass(value, MassUnit.Kilogram); } @@ -546,7 +549,7 @@ public static Mass FromKilograms(QuantityValue kilograms) /// If value is NaN or Infinity. public static Mass FromKilopounds(QuantityValue kilopounds) { - double value = (double) kilopounds; + QuantityValue value = (QuantityValue) kilopounds; return new Mass(value, MassUnit.Kilopound); } @@ -556,7 +559,7 @@ public static Mass FromKilopounds(QuantityValue kilopounds) /// If value is NaN or Infinity. public static Mass FromKilotonnes(QuantityValue kilotonnes) { - double value = (double) kilotonnes; + QuantityValue value = (QuantityValue) kilotonnes; return new Mass(value, MassUnit.Kilotonne); } @@ -566,7 +569,7 @@ public static Mass FromKilotonnes(QuantityValue kilotonnes) /// If value is NaN or Infinity. public static Mass FromLongHundredweight(QuantityValue longhundredweight) { - double value = (double) longhundredweight; + QuantityValue value = (QuantityValue) longhundredweight; return new Mass(value, MassUnit.LongHundredweight); } @@ -576,7 +579,7 @@ public static Mass FromLongHundredweight(QuantityValue longhundredweight) /// If value is NaN or Infinity. public static Mass FromLongTons(QuantityValue longtons) { - double value = (double) longtons; + QuantityValue value = (QuantityValue) longtons; return new Mass(value, MassUnit.LongTon); } @@ -586,7 +589,7 @@ public static Mass FromLongTons(QuantityValue longtons) /// If value is NaN or Infinity. public static Mass FromMegapounds(QuantityValue megapounds) { - double value = (double) megapounds; + QuantityValue value = (QuantityValue) megapounds; return new Mass(value, MassUnit.Megapound); } @@ -596,7 +599,7 @@ public static Mass FromMegapounds(QuantityValue megapounds) /// If value is NaN or Infinity. public static Mass FromMegatonnes(QuantityValue megatonnes) { - double value = (double) megatonnes; + QuantityValue value = (QuantityValue) megatonnes; return new Mass(value, MassUnit.Megatonne); } @@ -606,7 +609,7 @@ public static Mass FromMegatonnes(QuantityValue megatonnes) /// If value is NaN or Infinity. public static Mass FromMicrograms(QuantityValue micrograms) { - double value = (double) micrograms; + QuantityValue value = (QuantityValue) micrograms; return new Mass(value, MassUnit.Microgram); } @@ -616,7 +619,7 @@ public static Mass FromMicrograms(QuantityValue micrograms) /// If value is NaN or Infinity. public static Mass FromMilligrams(QuantityValue milligrams) { - double value = (double) milligrams; + QuantityValue value = (QuantityValue) milligrams; return new Mass(value, MassUnit.Milligram); } @@ -626,7 +629,7 @@ public static Mass FromMilligrams(QuantityValue milligrams) /// If value is NaN or Infinity. public static Mass FromNanograms(QuantityValue nanograms) { - double value = (double) nanograms; + QuantityValue value = (QuantityValue) nanograms; return new Mass(value, MassUnit.Nanogram); } @@ -636,7 +639,7 @@ public static Mass FromNanograms(QuantityValue nanograms) /// If value is NaN or Infinity. public static Mass FromOunces(QuantityValue ounces) { - double value = (double) ounces; + QuantityValue value = (QuantityValue) ounces; return new Mass(value, MassUnit.Ounce); } @@ -646,7 +649,7 @@ public static Mass FromOunces(QuantityValue ounces) /// If value is NaN or Infinity. public static Mass FromPounds(QuantityValue pounds) { - double value = (double) pounds; + QuantityValue value = (QuantityValue) pounds; return new Mass(value, MassUnit.Pound); } @@ -656,7 +659,7 @@ public static Mass FromPounds(QuantityValue pounds) /// If value is NaN or Infinity. public static Mass FromShortHundredweight(QuantityValue shorthundredweight) { - double value = (double) shorthundredweight; + QuantityValue value = (QuantityValue) shorthundredweight; return new Mass(value, MassUnit.ShortHundredweight); } @@ -666,7 +669,7 @@ public static Mass FromShortHundredweight(QuantityValue shorthundredweight) /// If value is NaN or Infinity. public static Mass FromShortTons(QuantityValue shorttons) { - double value = (double) shorttons; + QuantityValue value = (QuantityValue) shorttons; return new Mass(value, MassUnit.ShortTon); } @@ -676,7 +679,7 @@ public static Mass FromShortTons(QuantityValue shorttons) /// If value is NaN or Infinity. public static Mass FromSlugs(QuantityValue slugs) { - double value = (double) slugs; + QuantityValue value = (QuantityValue) slugs; return new Mass(value, MassUnit.Slug); } @@ -686,7 +689,7 @@ public static Mass FromSlugs(QuantityValue slugs) /// If value is NaN or Infinity. public static Mass FromSolarMasses(QuantityValue solarmasses) { - double value = (double) solarmasses; + QuantityValue value = (QuantityValue) solarmasses; return new Mass(value, MassUnit.SolarMass); } @@ -696,7 +699,7 @@ public static Mass FromSolarMasses(QuantityValue solarmasses) /// If value is NaN or Infinity. public static Mass FromStone(QuantityValue stone) { - double value = (double) stone; + QuantityValue value = (QuantityValue) stone; return new Mass(value, MassUnit.Stone); } @@ -706,7 +709,7 @@ public static Mass FromStone(QuantityValue stone) /// If value is NaN or Infinity. public static Mass FromTonnes(QuantityValue tonnes) { - double value = (double) tonnes; + QuantityValue value = (QuantityValue) tonnes; return new Mass(value, MassUnit.Tonne); } @@ -718,7 +721,7 @@ public static Mass FromTonnes(QuantityValue tonnes) /// Mass unit value. public static Mass From(QuantityValue value, MassUnit fromUnit) { - return new Mass((double)value, fromUnit); + return new Mass((QuantityValue)value, fromUnit); } #endregion @@ -888,25 +891,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassU } /// Get from multiplying value and . - public static Mass operator *(double left, Mass right) + public static Mass operator *(QuantityValue left, Mass right) { return new Mass(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Mass operator *(Mass left, double right) + public static Mass operator *(Mass left, QuantityValue right) { return new Mass(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Mass operator /(Mass left, double right) + public static Mass operator /(Mass left, QuantityValue right) { return new Mass(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Mass left, Mass right) + public static QuantityValue operator /(Mass left, Mass right) { return left.Kilograms / right.Kilograms; } @@ -939,6 +942,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassU return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Mass left, Mass right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Mass left, Mass right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -951,7 +967,29 @@ public int CompareTo(object obj) /// public int CompareTo(Mass other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Mass objMass)) + return false; + return Equals(objMass); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Mass other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -994,13 +1032,13 @@ public int CompareTo(Mass other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Mass other, double tolerance, ComparisonType comparisonType) + public bool Equals(Mass other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1011,7 +1049,7 @@ public bool Equals(Mass other, double tolerance, ComparisonType comparisonType) /// A hash code for the current Mass. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1022,17 +1060,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MassUnit unit) + public QuantityValue As(MassUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1047,12 +1084,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MassUnit unitAsMassUnit)) + if (!(unit is MassUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassUnit)} is supported.", nameof(unit)); - return As(unitAsMassUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1084,7 +1121,7 @@ public Mass ToUnit(MassUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Mass)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MassUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1092,17 +1129,17 @@ public Mass ToUnit(MassUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassUnit unitAsMassUnit)) + if (!(unit is MassUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1129,10 +1166,10 @@ public Mass ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MassUnit unit) + private QuantityValue GetValueAs(MassUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs index 4e0adad314..23e88d2caa 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Mass_concentration_(chemistry) /// [DataContract] - public partial struct MassConcentration : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MassConcentration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -123,9 +123,9 @@ static MassConcentration() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MassConcentration(double value, MassConcentrationUnit unit) + public MassConcentration(QuantityValue value, MassConcentrationUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -137,14 +137,14 @@ public MassConcentration(double value, MassConcentrationUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MassConcentration(double value, UnitSystem unitSystem) + public MassConcentration(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -185,7 +185,10 @@ public MassConcentration(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -208,249 +211,249 @@ public MassConcentration(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerDeciliter => As(MassConcentrationUnit.CentigramPerDeciliter); + public QuantityValue CentigramsPerDeciliter => As(MassConcentrationUnit.CentigramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerLiter => As(MassConcentrationUnit.CentigramPerLiter); + public QuantityValue CentigramsPerLiter => As(MassConcentrationUnit.CentigramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerMicroliter => As(MassConcentrationUnit.CentigramPerMicroliter); + public QuantityValue CentigramsPerMicroliter => As(MassConcentrationUnit.CentigramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerMilliliter => As(MassConcentrationUnit.CentigramPerMilliliter); + public QuantityValue CentigramsPerMilliliter => As(MassConcentrationUnit.CentigramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerDeciliter => As(MassConcentrationUnit.DecigramPerDeciliter); + public QuantityValue DecigramsPerDeciliter => As(MassConcentrationUnit.DecigramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerLiter => As(MassConcentrationUnit.DecigramPerLiter); + public QuantityValue DecigramsPerLiter => As(MassConcentrationUnit.DecigramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerMicroliter => As(MassConcentrationUnit.DecigramPerMicroliter); + public QuantityValue DecigramsPerMicroliter => As(MassConcentrationUnit.DecigramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerMilliliter => As(MassConcentrationUnit.DecigramPerMilliliter); + public QuantityValue DecigramsPerMilliliter => As(MassConcentrationUnit.DecigramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerCubicCentimeter => As(MassConcentrationUnit.GramPerCubicCentimeter); + public QuantityValue GramsPerCubicCentimeter => As(MassConcentrationUnit.GramPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerCubicMeter => As(MassConcentrationUnit.GramPerCubicMeter); + public QuantityValue GramsPerCubicMeter => As(MassConcentrationUnit.GramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerCubicMillimeter => As(MassConcentrationUnit.GramPerCubicMillimeter); + public QuantityValue GramsPerCubicMillimeter => As(MassConcentrationUnit.GramPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerDeciliter => As(MassConcentrationUnit.GramPerDeciliter); + public QuantityValue GramsPerDeciliter => As(MassConcentrationUnit.GramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerLiter => As(MassConcentrationUnit.GramPerLiter); + public QuantityValue GramsPerLiter => As(MassConcentrationUnit.GramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerMicroliter => As(MassConcentrationUnit.GramPerMicroliter); + public QuantityValue GramsPerMicroliter => As(MassConcentrationUnit.GramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerMilliliter => As(MassConcentrationUnit.GramPerMilliliter); + public QuantityValue GramsPerMilliliter => As(MassConcentrationUnit.GramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerCubicCentimeter => As(MassConcentrationUnit.KilogramPerCubicCentimeter); + public QuantityValue KilogramsPerCubicCentimeter => As(MassConcentrationUnit.KilogramPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerCubicMeter => As(MassConcentrationUnit.KilogramPerCubicMeter); + public QuantityValue KilogramsPerCubicMeter => As(MassConcentrationUnit.KilogramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerCubicMillimeter => As(MassConcentrationUnit.KilogramPerCubicMillimeter); + public QuantityValue KilogramsPerCubicMillimeter => As(MassConcentrationUnit.KilogramPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerLiter => As(MassConcentrationUnit.KilogramPerLiter); + public QuantityValue KilogramsPerLiter => As(MassConcentrationUnit.KilogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsPerCubicFoot => As(MassConcentrationUnit.KilopoundPerCubicFoot); + public QuantityValue KilopoundsPerCubicFoot => As(MassConcentrationUnit.KilopoundPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsPerCubicInch => As(MassConcentrationUnit.KilopoundPerCubicInch); + public QuantityValue KilopoundsPerCubicInch => As(MassConcentrationUnit.KilopoundPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerCubicMeter => As(MassConcentrationUnit.MicrogramPerCubicMeter); + public QuantityValue MicrogramsPerCubicMeter => As(MassConcentrationUnit.MicrogramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerDeciliter => As(MassConcentrationUnit.MicrogramPerDeciliter); + public QuantityValue MicrogramsPerDeciliter => As(MassConcentrationUnit.MicrogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerLiter => As(MassConcentrationUnit.MicrogramPerLiter); + public QuantityValue MicrogramsPerLiter => As(MassConcentrationUnit.MicrogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerMicroliter => As(MassConcentrationUnit.MicrogramPerMicroliter); + public QuantityValue MicrogramsPerMicroliter => As(MassConcentrationUnit.MicrogramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerMilliliter => As(MassConcentrationUnit.MicrogramPerMilliliter); + public QuantityValue MicrogramsPerMilliliter => As(MassConcentrationUnit.MicrogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerCubicMeter => As(MassConcentrationUnit.MilligramPerCubicMeter); + public QuantityValue MilligramsPerCubicMeter => As(MassConcentrationUnit.MilligramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerDeciliter => As(MassConcentrationUnit.MilligramPerDeciliter); + public QuantityValue MilligramsPerDeciliter => As(MassConcentrationUnit.MilligramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerLiter => As(MassConcentrationUnit.MilligramPerLiter); + public QuantityValue MilligramsPerLiter => As(MassConcentrationUnit.MilligramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerMicroliter => As(MassConcentrationUnit.MilligramPerMicroliter); + public QuantityValue MilligramsPerMicroliter => As(MassConcentrationUnit.MilligramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerMilliliter => As(MassConcentrationUnit.MilligramPerMilliliter); + public QuantityValue MilligramsPerMilliliter => As(MassConcentrationUnit.MilligramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerDeciliter => As(MassConcentrationUnit.NanogramPerDeciliter); + public QuantityValue NanogramsPerDeciliter => As(MassConcentrationUnit.NanogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerLiter => As(MassConcentrationUnit.NanogramPerLiter); + public QuantityValue NanogramsPerLiter => As(MassConcentrationUnit.NanogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerMicroliter => As(MassConcentrationUnit.NanogramPerMicroliter); + public QuantityValue NanogramsPerMicroliter => As(MassConcentrationUnit.NanogramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerMilliliter => As(MassConcentrationUnit.NanogramPerMilliliter); + public QuantityValue NanogramsPerMilliliter => As(MassConcentrationUnit.NanogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OuncesPerImperialGallon => As(MassConcentrationUnit.OuncePerImperialGallon); + public QuantityValue OuncesPerImperialGallon => As(MassConcentrationUnit.OuncePerImperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OuncesPerUSGallon => As(MassConcentrationUnit.OuncePerUSGallon); + public QuantityValue OuncesPerUSGallon => As(MassConcentrationUnit.OuncePerUSGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicogramsPerDeciliter => As(MassConcentrationUnit.PicogramPerDeciliter); + public QuantityValue PicogramsPerDeciliter => As(MassConcentrationUnit.PicogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicogramsPerLiter => As(MassConcentrationUnit.PicogramPerLiter); + public QuantityValue PicogramsPerLiter => As(MassConcentrationUnit.PicogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicogramsPerMicroliter => As(MassConcentrationUnit.PicogramPerMicroliter); + public QuantityValue PicogramsPerMicroliter => As(MassConcentrationUnit.PicogramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicogramsPerMilliliter => As(MassConcentrationUnit.PicogramPerMilliliter); + public QuantityValue PicogramsPerMilliliter => As(MassConcentrationUnit.PicogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerCubicFoot => As(MassConcentrationUnit.PoundPerCubicFoot); + public QuantityValue PoundsPerCubicFoot => As(MassConcentrationUnit.PoundPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerCubicInch => As(MassConcentrationUnit.PoundPerCubicInch); + public QuantityValue PoundsPerCubicInch => As(MassConcentrationUnit.PoundPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerImperialGallon => As(MassConcentrationUnit.PoundPerImperialGallon); + public QuantityValue PoundsPerImperialGallon => As(MassConcentrationUnit.PoundPerImperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerUSGallon => As(MassConcentrationUnit.PoundPerUSGallon); + public QuantityValue PoundsPerUSGallon => As(MassConcentrationUnit.PoundPerUSGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SlugsPerCubicFoot => As(MassConcentrationUnit.SlugPerCubicFoot); + public QuantityValue SlugsPerCubicFoot => As(MassConcentrationUnit.SlugPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerCubicCentimeter => As(MassConcentrationUnit.TonnePerCubicCentimeter); + public QuantityValue TonnesPerCubicCentimeter => As(MassConcentrationUnit.TonnePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerCubicMeter => As(MassConcentrationUnit.TonnePerCubicMeter); + public QuantityValue TonnesPerCubicMeter => As(MassConcentrationUnit.TonnePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerCubicMillimeter => As(MassConcentrationUnit.TonnePerCubicMillimeter); + public QuantityValue TonnesPerCubicMillimeter => As(MassConcentrationUnit.TonnePerCubicMillimeter); #endregion @@ -654,7 +657,7 @@ public static string GetAbbreviation(MassConcentrationUnit unit, IFormatProvider /// If value is NaN or Infinity. public static MassConcentration FromCentigramsPerDeciliter(QuantityValue centigramsperdeciliter) { - double value = (double) centigramsperdeciliter; + QuantityValue value = (QuantityValue) centigramsperdeciliter; return new MassConcentration(value, MassConcentrationUnit.CentigramPerDeciliter); } @@ -664,7 +667,7 @@ public static MassConcentration FromCentigramsPerDeciliter(QuantityValue centigr /// If value is NaN or Infinity. public static MassConcentration FromCentigramsPerLiter(QuantityValue centigramsperliter) { - double value = (double) centigramsperliter; + QuantityValue value = (QuantityValue) centigramsperliter; return new MassConcentration(value, MassConcentrationUnit.CentigramPerLiter); } @@ -674,7 +677,7 @@ public static MassConcentration FromCentigramsPerLiter(QuantityValue centigramsp /// If value is NaN or Infinity. public static MassConcentration FromCentigramsPerMicroliter(QuantityValue centigramspermicroliter) { - double value = (double) centigramspermicroliter; + QuantityValue value = (QuantityValue) centigramspermicroliter; return new MassConcentration(value, MassConcentrationUnit.CentigramPerMicroliter); } @@ -684,7 +687,7 @@ public static MassConcentration FromCentigramsPerMicroliter(QuantityValue centig /// If value is NaN or Infinity. public static MassConcentration FromCentigramsPerMilliliter(QuantityValue centigramspermilliliter) { - double value = (double) centigramspermilliliter; + QuantityValue value = (QuantityValue) centigramspermilliliter; return new MassConcentration(value, MassConcentrationUnit.CentigramPerMilliliter); } @@ -694,7 +697,7 @@ public static MassConcentration FromCentigramsPerMilliliter(QuantityValue centig /// If value is NaN or Infinity. public static MassConcentration FromDecigramsPerDeciliter(QuantityValue decigramsperdeciliter) { - double value = (double) decigramsperdeciliter; + QuantityValue value = (QuantityValue) decigramsperdeciliter; return new MassConcentration(value, MassConcentrationUnit.DecigramPerDeciliter); } @@ -704,7 +707,7 @@ public static MassConcentration FromDecigramsPerDeciliter(QuantityValue decigram /// If value is NaN or Infinity. public static MassConcentration FromDecigramsPerLiter(QuantityValue decigramsperliter) { - double value = (double) decigramsperliter; + QuantityValue value = (QuantityValue) decigramsperliter; return new MassConcentration(value, MassConcentrationUnit.DecigramPerLiter); } @@ -714,7 +717,7 @@ public static MassConcentration FromDecigramsPerLiter(QuantityValue decigramsper /// If value is NaN or Infinity. public static MassConcentration FromDecigramsPerMicroliter(QuantityValue decigramspermicroliter) { - double value = (double) decigramspermicroliter; + QuantityValue value = (QuantityValue) decigramspermicroliter; return new MassConcentration(value, MassConcentrationUnit.DecigramPerMicroliter); } @@ -724,7 +727,7 @@ public static MassConcentration FromDecigramsPerMicroliter(QuantityValue decigra /// If value is NaN or Infinity. public static MassConcentration FromDecigramsPerMilliliter(QuantityValue decigramspermilliliter) { - double value = (double) decigramspermilliliter; + QuantityValue value = (QuantityValue) decigramspermilliliter; return new MassConcentration(value, MassConcentrationUnit.DecigramPerMilliliter); } @@ -734,7 +737,7 @@ public static MassConcentration FromDecigramsPerMilliliter(QuantityValue decigra /// If value is NaN or Infinity. public static MassConcentration FromGramsPerCubicCentimeter(QuantityValue gramspercubiccentimeter) { - double value = (double) gramspercubiccentimeter; + QuantityValue value = (QuantityValue) gramspercubiccentimeter; return new MassConcentration(value, MassConcentrationUnit.GramPerCubicCentimeter); } @@ -744,7 +747,7 @@ public static MassConcentration FromGramsPerCubicCentimeter(QuantityValue gramsp /// If value is NaN or Infinity. public static MassConcentration FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) { - double value = (double) gramspercubicmeter; + QuantityValue value = (QuantityValue) gramspercubicmeter; return new MassConcentration(value, MassConcentrationUnit.GramPerCubicMeter); } @@ -754,7 +757,7 @@ public static MassConcentration FromGramsPerCubicMeter(QuantityValue gramspercub /// If value is NaN or Infinity. public static MassConcentration FromGramsPerCubicMillimeter(QuantityValue gramspercubicmillimeter) { - double value = (double) gramspercubicmillimeter; + QuantityValue value = (QuantityValue) gramspercubicmillimeter; return new MassConcentration(value, MassConcentrationUnit.GramPerCubicMillimeter); } @@ -764,7 +767,7 @@ public static MassConcentration FromGramsPerCubicMillimeter(QuantityValue gramsp /// If value is NaN or Infinity. public static MassConcentration FromGramsPerDeciliter(QuantityValue gramsperdeciliter) { - double value = (double) gramsperdeciliter; + QuantityValue value = (QuantityValue) gramsperdeciliter; return new MassConcentration(value, MassConcentrationUnit.GramPerDeciliter); } @@ -774,7 +777,7 @@ public static MassConcentration FromGramsPerDeciliter(QuantityValue gramsperdeci /// If value is NaN or Infinity. public static MassConcentration FromGramsPerLiter(QuantityValue gramsperliter) { - double value = (double) gramsperliter; + QuantityValue value = (QuantityValue) gramsperliter; return new MassConcentration(value, MassConcentrationUnit.GramPerLiter); } @@ -784,7 +787,7 @@ public static MassConcentration FromGramsPerLiter(QuantityValue gramsperliter) /// If value is NaN or Infinity. public static MassConcentration FromGramsPerMicroliter(QuantityValue gramspermicroliter) { - double value = (double) gramspermicroliter; + QuantityValue value = (QuantityValue) gramspermicroliter; return new MassConcentration(value, MassConcentrationUnit.GramPerMicroliter); } @@ -794,7 +797,7 @@ public static MassConcentration FromGramsPerMicroliter(QuantityValue gramspermic /// If value is NaN or Infinity. public static MassConcentration FromGramsPerMilliliter(QuantityValue gramspermilliliter) { - double value = (double) gramspermilliliter; + QuantityValue value = (QuantityValue) gramspermilliliter; return new MassConcentration(value, MassConcentrationUnit.GramPerMilliliter); } @@ -804,7 +807,7 @@ public static MassConcentration FromGramsPerMilliliter(QuantityValue gramspermil /// If value is NaN or Infinity. public static MassConcentration FromKilogramsPerCubicCentimeter(QuantityValue kilogramspercubiccentimeter) { - double value = (double) kilogramspercubiccentimeter; + QuantityValue value = (QuantityValue) kilogramspercubiccentimeter; return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicCentimeter); } @@ -814,7 +817,7 @@ public static MassConcentration FromKilogramsPerCubicCentimeter(QuantityValue ki /// If value is NaN or Infinity. public static MassConcentration FromKilogramsPerCubicMeter(QuantityValue kilogramspercubicmeter) { - double value = (double) kilogramspercubicmeter; + QuantityValue value = (QuantityValue) kilogramspercubicmeter; return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicMeter); } @@ -824,7 +827,7 @@ public static MassConcentration FromKilogramsPerCubicMeter(QuantityValue kilogra /// If value is NaN or Infinity. public static MassConcentration FromKilogramsPerCubicMillimeter(QuantityValue kilogramspercubicmillimeter) { - double value = (double) kilogramspercubicmillimeter; + QuantityValue value = (QuantityValue) kilogramspercubicmillimeter; return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicMillimeter); } @@ -834,7 +837,7 @@ public static MassConcentration FromKilogramsPerCubicMillimeter(QuantityValue ki /// If value is NaN or Infinity. public static MassConcentration FromKilogramsPerLiter(QuantityValue kilogramsperliter) { - double value = (double) kilogramsperliter; + QuantityValue value = (QuantityValue) kilogramsperliter; return new MassConcentration(value, MassConcentrationUnit.KilogramPerLiter); } @@ -844,7 +847,7 @@ public static MassConcentration FromKilogramsPerLiter(QuantityValue kilogramsper /// If value is NaN or Infinity. public static MassConcentration FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubicfoot) { - double value = (double) kilopoundspercubicfoot; + QuantityValue value = (QuantityValue) kilopoundspercubicfoot; return new MassConcentration(value, MassConcentrationUnit.KilopoundPerCubicFoot); } @@ -854,7 +857,7 @@ public static MassConcentration FromKilopoundsPerCubicFoot(QuantityValue kilopou /// If value is NaN or Infinity. public static MassConcentration FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubicinch) { - double value = (double) kilopoundspercubicinch; + QuantityValue value = (QuantityValue) kilopoundspercubicinch; return new MassConcentration(value, MassConcentrationUnit.KilopoundPerCubicInch); } @@ -864,7 +867,7 @@ public static MassConcentration FromKilopoundsPerCubicInch(QuantityValue kilopou /// If value is NaN or Infinity. public static MassConcentration FromMicrogramsPerCubicMeter(QuantityValue microgramspercubicmeter) { - double value = (double) microgramspercubicmeter; + QuantityValue value = (QuantityValue) microgramspercubicmeter; return new MassConcentration(value, MassConcentrationUnit.MicrogramPerCubicMeter); } @@ -874,7 +877,7 @@ public static MassConcentration FromMicrogramsPerCubicMeter(QuantityValue microg /// If value is NaN or Infinity. public static MassConcentration FromMicrogramsPerDeciliter(QuantityValue microgramsperdeciliter) { - double value = (double) microgramsperdeciliter; + QuantityValue value = (QuantityValue) microgramsperdeciliter; return new MassConcentration(value, MassConcentrationUnit.MicrogramPerDeciliter); } @@ -884,7 +887,7 @@ public static MassConcentration FromMicrogramsPerDeciliter(QuantityValue microgr /// If value is NaN or Infinity. public static MassConcentration FromMicrogramsPerLiter(QuantityValue microgramsperliter) { - double value = (double) microgramsperliter; + QuantityValue value = (QuantityValue) microgramsperliter; return new MassConcentration(value, MassConcentrationUnit.MicrogramPerLiter); } @@ -894,7 +897,7 @@ public static MassConcentration FromMicrogramsPerLiter(QuantityValue microgramsp /// If value is NaN or Infinity. public static MassConcentration FromMicrogramsPerMicroliter(QuantityValue microgramspermicroliter) { - double value = (double) microgramspermicroliter; + QuantityValue value = (QuantityValue) microgramspermicroliter; return new MassConcentration(value, MassConcentrationUnit.MicrogramPerMicroliter); } @@ -904,7 +907,7 @@ public static MassConcentration FromMicrogramsPerMicroliter(QuantityValue microg /// If value is NaN or Infinity. public static MassConcentration FromMicrogramsPerMilliliter(QuantityValue microgramspermilliliter) { - double value = (double) microgramspermilliliter; + QuantityValue value = (QuantityValue) microgramspermilliliter; return new MassConcentration(value, MassConcentrationUnit.MicrogramPerMilliliter); } @@ -914,7 +917,7 @@ public static MassConcentration FromMicrogramsPerMilliliter(QuantityValue microg /// If value is NaN or Infinity. public static MassConcentration FromMilligramsPerCubicMeter(QuantityValue milligramspercubicmeter) { - double value = (double) milligramspercubicmeter; + QuantityValue value = (QuantityValue) milligramspercubicmeter; return new MassConcentration(value, MassConcentrationUnit.MilligramPerCubicMeter); } @@ -924,7 +927,7 @@ public static MassConcentration FromMilligramsPerCubicMeter(QuantityValue millig /// If value is NaN or Infinity. public static MassConcentration FromMilligramsPerDeciliter(QuantityValue milligramsperdeciliter) { - double value = (double) milligramsperdeciliter; + QuantityValue value = (QuantityValue) milligramsperdeciliter; return new MassConcentration(value, MassConcentrationUnit.MilligramPerDeciliter); } @@ -934,7 +937,7 @@ public static MassConcentration FromMilligramsPerDeciliter(QuantityValue milligr /// If value is NaN or Infinity. public static MassConcentration FromMilligramsPerLiter(QuantityValue milligramsperliter) { - double value = (double) milligramsperliter; + QuantityValue value = (QuantityValue) milligramsperliter; return new MassConcentration(value, MassConcentrationUnit.MilligramPerLiter); } @@ -944,7 +947,7 @@ public static MassConcentration FromMilligramsPerLiter(QuantityValue milligramsp /// If value is NaN or Infinity. public static MassConcentration FromMilligramsPerMicroliter(QuantityValue milligramspermicroliter) { - double value = (double) milligramspermicroliter; + QuantityValue value = (QuantityValue) milligramspermicroliter; return new MassConcentration(value, MassConcentrationUnit.MilligramPerMicroliter); } @@ -954,7 +957,7 @@ public static MassConcentration FromMilligramsPerMicroliter(QuantityValue millig /// If value is NaN or Infinity. public static MassConcentration FromMilligramsPerMilliliter(QuantityValue milligramspermilliliter) { - double value = (double) milligramspermilliliter; + QuantityValue value = (QuantityValue) milligramspermilliliter; return new MassConcentration(value, MassConcentrationUnit.MilligramPerMilliliter); } @@ -964,7 +967,7 @@ public static MassConcentration FromMilligramsPerMilliliter(QuantityValue millig /// If value is NaN or Infinity. public static MassConcentration FromNanogramsPerDeciliter(QuantityValue nanogramsperdeciliter) { - double value = (double) nanogramsperdeciliter; + QuantityValue value = (QuantityValue) nanogramsperdeciliter; return new MassConcentration(value, MassConcentrationUnit.NanogramPerDeciliter); } @@ -974,7 +977,7 @@ public static MassConcentration FromNanogramsPerDeciliter(QuantityValue nanogram /// If value is NaN or Infinity. public static MassConcentration FromNanogramsPerLiter(QuantityValue nanogramsperliter) { - double value = (double) nanogramsperliter; + QuantityValue value = (QuantityValue) nanogramsperliter; return new MassConcentration(value, MassConcentrationUnit.NanogramPerLiter); } @@ -984,7 +987,7 @@ public static MassConcentration FromNanogramsPerLiter(QuantityValue nanogramsper /// If value is NaN or Infinity. public static MassConcentration FromNanogramsPerMicroliter(QuantityValue nanogramspermicroliter) { - double value = (double) nanogramspermicroliter; + QuantityValue value = (QuantityValue) nanogramspermicroliter; return new MassConcentration(value, MassConcentrationUnit.NanogramPerMicroliter); } @@ -994,7 +997,7 @@ public static MassConcentration FromNanogramsPerMicroliter(QuantityValue nanogra /// If value is NaN or Infinity. public static MassConcentration FromNanogramsPerMilliliter(QuantityValue nanogramspermilliliter) { - double value = (double) nanogramspermilliliter; + QuantityValue value = (QuantityValue) nanogramspermilliliter; return new MassConcentration(value, MassConcentrationUnit.NanogramPerMilliliter); } @@ -1004,7 +1007,7 @@ public static MassConcentration FromNanogramsPerMilliliter(QuantityValue nanogra /// If value is NaN or Infinity. public static MassConcentration FromOuncesPerImperialGallon(QuantityValue ouncesperimperialgallon) { - double value = (double) ouncesperimperialgallon; + QuantityValue value = (QuantityValue) ouncesperimperialgallon; return new MassConcentration(value, MassConcentrationUnit.OuncePerImperialGallon); } @@ -1014,7 +1017,7 @@ public static MassConcentration FromOuncesPerImperialGallon(QuantityValue ounces /// If value is NaN or Infinity. public static MassConcentration FromOuncesPerUSGallon(QuantityValue ouncesperusgallon) { - double value = (double) ouncesperusgallon; + QuantityValue value = (QuantityValue) ouncesperusgallon; return new MassConcentration(value, MassConcentrationUnit.OuncePerUSGallon); } @@ -1024,7 +1027,7 @@ public static MassConcentration FromOuncesPerUSGallon(QuantityValue ouncesperusg /// If value is NaN or Infinity. public static MassConcentration FromPicogramsPerDeciliter(QuantityValue picogramsperdeciliter) { - double value = (double) picogramsperdeciliter; + QuantityValue value = (QuantityValue) picogramsperdeciliter; return new MassConcentration(value, MassConcentrationUnit.PicogramPerDeciliter); } @@ -1034,7 +1037,7 @@ public static MassConcentration FromPicogramsPerDeciliter(QuantityValue picogram /// If value is NaN or Infinity. public static MassConcentration FromPicogramsPerLiter(QuantityValue picogramsperliter) { - double value = (double) picogramsperliter; + QuantityValue value = (QuantityValue) picogramsperliter; return new MassConcentration(value, MassConcentrationUnit.PicogramPerLiter); } @@ -1044,7 +1047,7 @@ public static MassConcentration FromPicogramsPerLiter(QuantityValue picogramsper /// If value is NaN or Infinity. public static MassConcentration FromPicogramsPerMicroliter(QuantityValue picogramspermicroliter) { - double value = (double) picogramspermicroliter; + QuantityValue value = (QuantityValue) picogramspermicroliter; return new MassConcentration(value, MassConcentrationUnit.PicogramPerMicroliter); } @@ -1054,7 +1057,7 @@ public static MassConcentration FromPicogramsPerMicroliter(QuantityValue picogra /// If value is NaN or Infinity. public static MassConcentration FromPicogramsPerMilliliter(QuantityValue picogramspermilliliter) { - double value = (double) picogramspermilliliter; + QuantityValue value = (QuantityValue) picogramspermilliliter; return new MassConcentration(value, MassConcentrationUnit.PicogramPerMilliliter); } @@ -1064,7 +1067,7 @@ public static MassConcentration FromPicogramsPerMilliliter(QuantityValue picogra /// If value is NaN or Infinity. public static MassConcentration FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) { - double value = (double) poundspercubicfoot; + QuantityValue value = (QuantityValue) poundspercubicfoot; return new MassConcentration(value, MassConcentrationUnit.PoundPerCubicFoot); } @@ -1074,7 +1077,7 @@ public static MassConcentration FromPoundsPerCubicFoot(QuantityValue poundspercu /// If value is NaN or Infinity. public static MassConcentration FromPoundsPerCubicInch(QuantityValue poundspercubicinch) { - double value = (double) poundspercubicinch; + QuantityValue value = (QuantityValue) poundspercubicinch; return new MassConcentration(value, MassConcentrationUnit.PoundPerCubicInch); } @@ -1084,7 +1087,7 @@ public static MassConcentration FromPoundsPerCubicInch(QuantityValue poundspercu /// If value is NaN or Infinity. public static MassConcentration FromPoundsPerImperialGallon(QuantityValue poundsperimperialgallon) { - double value = (double) poundsperimperialgallon; + QuantityValue value = (QuantityValue) poundsperimperialgallon; return new MassConcentration(value, MassConcentrationUnit.PoundPerImperialGallon); } @@ -1094,7 +1097,7 @@ public static MassConcentration FromPoundsPerImperialGallon(QuantityValue pounds /// If value is NaN or Infinity. public static MassConcentration FromPoundsPerUSGallon(QuantityValue poundsperusgallon) { - double value = (double) poundsperusgallon; + QuantityValue value = (QuantityValue) poundsperusgallon; return new MassConcentration(value, MassConcentrationUnit.PoundPerUSGallon); } @@ -1104,7 +1107,7 @@ public static MassConcentration FromPoundsPerUSGallon(QuantityValue poundsperusg /// If value is NaN or Infinity. public static MassConcentration FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) { - double value = (double) slugspercubicfoot; + QuantityValue value = (QuantityValue) slugspercubicfoot; return new MassConcentration(value, MassConcentrationUnit.SlugPerCubicFoot); } @@ -1114,7 +1117,7 @@ public static MassConcentration FromSlugsPerCubicFoot(QuantityValue slugspercubi /// If value is NaN or Infinity. public static MassConcentration FromTonnesPerCubicCentimeter(QuantityValue tonnespercubiccentimeter) { - double value = (double) tonnespercubiccentimeter; + QuantityValue value = (QuantityValue) tonnespercubiccentimeter; return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicCentimeter); } @@ -1124,7 +1127,7 @@ public static MassConcentration FromTonnesPerCubicCentimeter(QuantityValue tonne /// If value is NaN or Infinity. public static MassConcentration FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) { - double value = (double) tonnespercubicmeter; + QuantityValue value = (QuantityValue) tonnespercubicmeter; return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicMeter); } @@ -1134,7 +1137,7 @@ public static MassConcentration FromTonnesPerCubicMeter(QuantityValue tonnesperc /// If value is NaN or Infinity. public static MassConcentration FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicmillimeter) { - double value = (double) tonnespercubicmillimeter; + QuantityValue value = (QuantityValue) tonnespercubicmillimeter; return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicMillimeter); } @@ -1146,7 +1149,7 @@ public static MassConcentration FromTonnesPerCubicMillimeter(QuantityValue tonne /// MassConcentration unit value. public static MassConcentration From(QuantityValue value, MassConcentrationUnit fromUnit) { - return new MassConcentration((double)value, fromUnit); + return new MassConcentration((QuantityValue)value, fromUnit); } #endregion @@ -1316,25 +1319,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassC } /// Get from multiplying value and . - public static MassConcentration operator *(double left, MassConcentration right) + public static MassConcentration operator *(QuantityValue left, MassConcentration right) { return new MassConcentration(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MassConcentration operator *(MassConcentration left, double right) + public static MassConcentration operator *(MassConcentration left, QuantityValue right) { return new MassConcentration(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MassConcentration operator /(MassConcentration left, double right) + public static MassConcentration operator /(MassConcentration left, QuantityValue right) { return new MassConcentration(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MassConcentration left, MassConcentration right) + public static QuantityValue operator /(MassConcentration left, MassConcentration right) { return left.KilogramsPerCubicMeter / right.KilogramsPerCubicMeter; } @@ -1367,6 +1370,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassC return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MassConcentration left, MassConcentration right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MassConcentration left, MassConcentration right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1379,7 +1395,29 @@ public int CompareTo(object obj) /// public int CompareTo(MassConcentration other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MassConcentration objMassConcentration)) + return false; + return Equals(objMassConcentration); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MassConcentration other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1422,13 +1460,13 @@ public int CompareTo(MassConcentration other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassConcentration other, double tolerance, ComparisonType comparisonType) + public bool Equals(MassConcentration other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1439,7 +1477,7 @@ public bool Equals(MassConcentration other, double tolerance, ComparisonType com /// A hash code for the current MassConcentration. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1450,17 +1488,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MassConcentrationUnit unit) + public QuantityValue As(MassConcentrationUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1475,12 +1512,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MassConcentrationUnit unitAsMassConcentrationUnit)) + if (!(unit is MassConcentrationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassConcentrationUnit)} is supported.", nameof(unit)); - return As(unitAsMassConcentrationUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1512,7 +1549,7 @@ public MassConcentration ToUnit(MassConcentrationUnit unit, UnitConverter unitCo var converted = conversionFunction(this); return (MassConcentration)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MassConcentrationUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1520,17 +1557,17 @@ public MassConcentration ToUnit(MassConcentrationUnit unit, UnitConverter unitCo } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassConcentrationUnit unitAsMassConcentrationUnit)) + if (!(unit is MassConcentrationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassConcentrationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassConcentrationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1557,10 +1594,10 @@ public MassConcentration ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MassConcentrationUnit unit) + private QuantityValue GetValueAs(MassConcentrationUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs index 30ce043051..e20dfffc3b 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time). /// [DataContract] - public partial struct MassFlow : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MassFlow : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -104,9 +104,9 @@ static MassFlow() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MassFlow(double value, MassFlowUnit unit) + public MassFlow(QuantityValue value, MassFlowUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -118,14 +118,14 @@ public MassFlow(double value, MassFlowUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MassFlow(double value, UnitSystem unitSystem) + public MassFlow(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -166,7 +166,10 @@ public MassFlow(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -189,169 +192,169 @@ public MassFlow(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerDay => As(MassFlowUnit.CentigramPerDay); + public QuantityValue CentigramsPerDay => As(MassFlowUnit.CentigramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); + public QuantityValue CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecagramsPerDay => As(MassFlowUnit.DecagramPerDay); + public QuantityValue DecagramsPerDay => As(MassFlowUnit.DecagramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); + public QuantityValue DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerDay => As(MassFlowUnit.DecigramPerDay); + public QuantityValue DecigramsPerDay => As(MassFlowUnit.DecigramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); + public QuantityValue DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerDay => As(MassFlowUnit.GramPerDay); + public QuantityValue GramsPerDay => As(MassFlowUnit.GramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerHour => As(MassFlowUnit.GramPerHour); + public QuantityValue GramsPerHour => As(MassFlowUnit.GramPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerSecond => As(MassFlowUnit.GramPerSecond); + public QuantityValue GramsPerSecond => As(MassFlowUnit.GramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HectogramsPerDay => As(MassFlowUnit.HectogramPerDay); + public QuantityValue HectogramsPerDay => As(MassFlowUnit.HectogramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); + public QuantityValue HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerDay => As(MassFlowUnit.KilogramPerDay); + public QuantityValue KilogramsPerDay => As(MassFlowUnit.KilogramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); + public QuantityValue KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerMinute => As(MassFlowUnit.KilogramPerMinute); + public QuantityValue KilogramsPerMinute => As(MassFlowUnit.KilogramPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); + public QuantityValue KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegagramsPerDay => As(MassFlowUnit.MegagramPerDay); + public QuantityValue MegagramsPerDay => As(MassFlowUnit.MegagramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundsPerDay => As(MassFlowUnit.MegapoundPerDay); + public QuantityValue MegapoundsPerDay => As(MassFlowUnit.MegapoundPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); + public QuantityValue MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); + public QuantityValue MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundsPerSecond => As(MassFlowUnit.MegapoundPerSecond); + public QuantityValue MegapoundsPerSecond => As(MassFlowUnit.MegapoundPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerDay => As(MassFlowUnit.MicrogramPerDay); + public QuantityValue MicrogramsPerDay => As(MassFlowUnit.MicrogramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); + public QuantityValue MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerDay => As(MassFlowUnit.MilligramPerDay); + public QuantityValue MilligramsPerDay => As(MassFlowUnit.MilligramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); + public QuantityValue MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerDay => As(MassFlowUnit.NanogramPerDay); + public QuantityValue NanogramsPerDay => As(MassFlowUnit.NanogramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); + public QuantityValue NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerDay => As(MassFlowUnit.PoundPerDay); + public QuantityValue PoundsPerDay => As(MassFlowUnit.PoundPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerHour => As(MassFlowUnit.PoundPerHour); + public QuantityValue PoundsPerHour => As(MassFlowUnit.PoundPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); + public QuantityValue PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerSecond => As(MassFlowUnit.PoundPerSecond); + public QuantityValue PoundsPerSecond => As(MassFlowUnit.PoundPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); + public QuantityValue ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerDay => As(MassFlowUnit.TonnePerDay); + public QuantityValue TonnesPerDay => As(MassFlowUnit.TonnePerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesPerHour => As(MassFlowUnit.TonnePerHour); + public QuantityValue TonnesPerHour => As(MassFlowUnit.TonnePerHour); #endregion @@ -505,7 +508,7 @@ public static string GetAbbreviation(MassFlowUnit unit, IFormatProvider? provide /// If value is NaN or Infinity. public static MassFlow FromCentigramsPerDay(QuantityValue centigramsperday) { - double value = (double) centigramsperday; + QuantityValue value = (QuantityValue) centigramsperday; return new MassFlow(value, MassFlowUnit.CentigramPerDay); } @@ -515,7 +518,7 @@ public static MassFlow FromCentigramsPerDay(QuantityValue centigramsperday) /// If value is NaN or Infinity. public static MassFlow FromCentigramsPerSecond(QuantityValue centigramspersecond) { - double value = (double) centigramspersecond; + QuantityValue value = (QuantityValue) centigramspersecond; return new MassFlow(value, MassFlowUnit.CentigramPerSecond); } @@ -525,7 +528,7 @@ public static MassFlow FromCentigramsPerSecond(QuantityValue centigramspersecond /// If value is NaN or Infinity. public static MassFlow FromDecagramsPerDay(QuantityValue decagramsperday) { - double value = (double) decagramsperday; + QuantityValue value = (QuantityValue) decagramsperday; return new MassFlow(value, MassFlowUnit.DecagramPerDay); } @@ -535,7 +538,7 @@ public static MassFlow FromDecagramsPerDay(QuantityValue decagramsperday) /// If value is NaN or Infinity. public static MassFlow FromDecagramsPerSecond(QuantityValue decagramspersecond) { - double value = (double) decagramspersecond; + QuantityValue value = (QuantityValue) decagramspersecond; return new MassFlow(value, MassFlowUnit.DecagramPerSecond); } @@ -545,7 +548,7 @@ public static MassFlow FromDecagramsPerSecond(QuantityValue decagramspersecond) /// If value is NaN or Infinity. public static MassFlow FromDecigramsPerDay(QuantityValue decigramsperday) { - double value = (double) decigramsperday; + QuantityValue value = (QuantityValue) decigramsperday; return new MassFlow(value, MassFlowUnit.DecigramPerDay); } @@ -555,7 +558,7 @@ public static MassFlow FromDecigramsPerDay(QuantityValue decigramsperday) /// If value is NaN or Infinity. public static MassFlow FromDecigramsPerSecond(QuantityValue decigramspersecond) { - double value = (double) decigramspersecond; + QuantityValue value = (QuantityValue) decigramspersecond; return new MassFlow(value, MassFlowUnit.DecigramPerSecond); } @@ -565,7 +568,7 @@ public static MassFlow FromDecigramsPerSecond(QuantityValue decigramspersecond) /// If value is NaN or Infinity. public static MassFlow FromGramsPerDay(QuantityValue gramsperday) { - double value = (double) gramsperday; + QuantityValue value = (QuantityValue) gramsperday; return new MassFlow(value, MassFlowUnit.GramPerDay); } @@ -575,7 +578,7 @@ public static MassFlow FromGramsPerDay(QuantityValue gramsperday) /// If value is NaN or Infinity. public static MassFlow FromGramsPerHour(QuantityValue gramsperhour) { - double value = (double) gramsperhour; + QuantityValue value = (QuantityValue) gramsperhour; return new MassFlow(value, MassFlowUnit.GramPerHour); } @@ -585,7 +588,7 @@ public static MassFlow FromGramsPerHour(QuantityValue gramsperhour) /// If value is NaN or Infinity. public static MassFlow FromGramsPerSecond(QuantityValue gramspersecond) { - double value = (double) gramspersecond; + QuantityValue value = (QuantityValue) gramspersecond; return new MassFlow(value, MassFlowUnit.GramPerSecond); } @@ -595,7 +598,7 @@ public static MassFlow FromGramsPerSecond(QuantityValue gramspersecond) /// If value is NaN or Infinity. public static MassFlow FromHectogramsPerDay(QuantityValue hectogramsperday) { - double value = (double) hectogramsperday; + QuantityValue value = (QuantityValue) hectogramsperday; return new MassFlow(value, MassFlowUnit.HectogramPerDay); } @@ -605,7 +608,7 @@ public static MassFlow FromHectogramsPerDay(QuantityValue hectogramsperday) /// If value is NaN or Infinity. public static MassFlow FromHectogramsPerSecond(QuantityValue hectogramspersecond) { - double value = (double) hectogramspersecond; + QuantityValue value = (QuantityValue) hectogramspersecond; return new MassFlow(value, MassFlowUnit.HectogramPerSecond); } @@ -615,7 +618,7 @@ public static MassFlow FromHectogramsPerSecond(QuantityValue hectogramspersecond /// If value is NaN or Infinity. public static MassFlow FromKilogramsPerDay(QuantityValue kilogramsperday) { - double value = (double) kilogramsperday; + QuantityValue value = (QuantityValue) kilogramsperday; return new MassFlow(value, MassFlowUnit.KilogramPerDay); } @@ -625,7 +628,7 @@ public static MassFlow FromKilogramsPerDay(QuantityValue kilogramsperday) /// If value is NaN or Infinity. public static MassFlow FromKilogramsPerHour(QuantityValue kilogramsperhour) { - double value = (double) kilogramsperhour; + QuantityValue value = (QuantityValue) kilogramsperhour; return new MassFlow(value, MassFlowUnit.KilogramPerHour); } @@ -635,7 +638,7 @@ public static MassFlow FromKilogramsPerHour(QuantityValue kilogramsperhour) /// If value is NaN or Infinity. public static MassFlow FromKilogramsPerMinute(QuantityValue kilogramsperminute) { - double value = (double) kilogramsperminute; + QuantityValue value = (QuantityValue) kilogramsperminute; return new MassFlow(value, MassFlowUnit.KilogramPerMinute); } @@ -645,7 +648,7 @@ public static MassFlow FromKilogramsPerMinute(QuantityValue kilogramsperminute) /// If value is NaN or Infinity. public static MassFlow FromKilogramsPerSecond(QuantityValue kilogramspersecond) { - double value = (double) kilogramspersecond; + QuantityValue value = (QuantityValue) kilogramspersecond; return new MassFlow(value, MassFlowUnit.KilogramPerSecond); } @@ -655,7 +658,7 @@ public static MassFlow FromKilogramsPerSecond(QuantityValue kilogramspersecond) /// If value is NaN or Infinity. public static MassFlow FromMegagramsPerDay(QuantityValue megagramsperday) { - double value = (double) megagramsperday; + QuantityValue value = (QuantityValue) megagramsperday; return new MassFlow(value, MassFlowUnit.MegagramPerDay); } @@ -665,7 +668,7 @@ public static MassFlow FromMegagramsPerDay(QuantityValue megagramsperday) /// If value is NaN or Infinity. public static MassFlow FromMegapoundsPerDay(QuantityValue megapoundsperday) { - double value = (double) megapoundsperday; + QuantityValue value = (QuantityValue) megapoundsperday; return new MassFlow(value, MassFlowUnit.MegapoundPerDay); } @@ -675,7 +678,7 @@ public static MassFlow FromMegapoundsPerDay(QuantityValue megapoundsperday) /// If value is NaN or Infinity. public static MassFlow FromMegapoundsPerHour(QuantityValue megapoundsperhour) { - double value = (double) megapoundsperhour; + QuantityValue value = (QuantityValue) megapoundsperhour; return new MassFlow(value, MassFlowUnit.MegapoundPerHour); } @@ -685,7 +688,7 @@ public static MassFlow FromMegapoundsPerHour(QuantityValue megapoundsperhour) /// If value is NaN or Infinity. public static MassFlow FromMegapoundsPerMinute(QuantityValue megapoundsperminute) { - double value = (double) megapoundsperminute; + QuantityValue value = (QuantityValue) megapoundsperminute; return new MassFlow(value, MassFlowUnit.MegapoundPerMinute); } @@ -695,7 +698,7 @@ public static MassFlow FromMegapoundsPerMinute(QuantityValue megapoundsperminute /// If value is NaN or Infinity. public static MassFlow FromMegapoundsPerSecond(QuantityValue megapoundspersecond) { - double value = (double) megapoundspersecond; + QuantityValue value = (QuantityValue) megapoundspersecond; return new MassFlow(value, MassFlowUnit.MegapoundPerSecond); } @@ -705,7 +708,7 @@ public static MassFlow FromMegapoundsPerSecond(QuantityValue megapoundspersecond /// If value is NaN or Infinity. public static MassFlow FromMicrogramsPerDay(QuantityValue microgramsperday) { - double value = (double) microgramsperday; + QuantityValue value = (QuantityValue) microgramsperday; return new MassFlow(value, MassFlowUnit.MicrogramPerDay); } @@ -715,7 +718,7 @@ public static MassFlow FromMicrogramsPerDay(QuantityValue microgramsperday) /// If value is NaN or Infinity. public static MassFlow FromMicrogramsPerSecond(QuantityValue microgramspersecond) { - double value = (double) microgramspersecond; + QuantityValue value = (QuantityValue) microgramspersecond; return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); } @@ -725,7 +728,7 @@ public static MassFlow FromMicrogramsPerSecond(QuantityValue microgramspersecond /// If value is NaN or Infinity. public static MassFlow FromMilligramsPerDay(QuantityValue milligramsperday) { - double value = (double) milligramsperday; + QuantityValue value = (QuantityValue) milligramsperday; return new MassFlow(value, MassFlowUnit.MilligramPerDay); } @@ -735,7 +738,7 @@ public static MassFlow FromMilligramsPerDay(QuantityValue milligramsperday) /// If value is NaN or Infinity. public static MassFlow FromMilligramsPerSecond(QuantityValue milligramspersecond) { - double value = (double) milligramspersecond; + QuantityValue value = (QuantityValue) milligramspersecond; return new MassFlow(value, MassFlowUnit.MilligramPerSecond); } @@ -745,7 +748,7 @@ public static MassFlow FromMilligramsPerSecond(QuantityValue milligramspersecond /// If value is NaN or Infinity. public static MassFlow FromNanogramsPerDay(QuantityValue nanogramsperday) { - double value = (double) nanogramsperday; + QuantityValue value = (QuantityValue) nanogramsperday; return new MassFlow(value, MassFlowUnit.NanogramPerDay); } @@ -755,7 +758,7 @@ public static MassFlow FromNanogramsPerDay(QuantityValue nanogramsperday) /// If value is NaN or Infinity. public static MassFlow FromNanogramsPerSecond(QuantityValue nanogramspersecond) { - double value = (double) nanogramspersecond; + QuantityValue value = (QuantityValue) nanogramspersecond; return new MassFlow(value, MassFlowUnit.NanogramPerSecond); } @@ -765,7 +768,7 @@ public static MassFlow FromNanogramsPerSecond(QuantityValue nanogramspersecond) /// If value is NaN or Infinity. public static MassFlow FromPoundsPerDay(QuantityValue poundsperday) { - double value = (double) poundsperday; + QuantityValue value = (QuantityValue) poundsperday; return new MassFlow(value, MassFlowUnit.PoundPerDay); } @@ -775,7 +778,7 @@ public static MassFlow FromPoundsPerDay(QuantityValue poundsperday) /// If value is NaN or Infinity. public static MassFlow FromPoundsPerHour(QuantityValue poundsperhour) { - double value = (double) poundsperhour; + QuantityValue value = (QuantityValue) poundsperhour; return new MassFlow(value, MassFlowUnit.PoundPerHour); } @@ -785,7 +788,7 @@ public static MassFlow FromPoundsPerHour(QuantityValue poundsperhour) /// If value is NaN or Infinity. public static MassFlow FromPoundsPerMinute(QuantityValue poundsperminute) { - double value = (double) poundsperminute; + QuantityValue value = (QuantityValue) poundsperminute; return new MassFlow(value, MassFlowUnit.PoundPerMinute); } @@ -795,7 +798,7 @@ public static MassFlow FromPoundsPerMinute(QuantityValue poundsperminute) /// If value is NaN or Infinity. public static MassFlow FromPoundsPerSecond(QuantityValue poundspersecond) { - double value = (double) poundspersecond; + QuantityValue value = (QuantityValue) poundspersecond; return new MassFlow(value, MassFlowUnit.PoundPerSecond); } @@ -805,7 +808,7 @@ public static MassFlow FromPoundsPerSecond(QuantityValue poundspersecond) /// If value is NaN or Infinity. public static MassFlow FromShortTonsPerHour(QuantityValue shorttonsperhour) { - double value = (double) shorttonsperhour; + QuantityValue value = (QuantityValue) shorttonsperhour; return new MassFlow(value, MassFlowUnit.ShortTonPerHour); } @@ -815,7 +818,7 @@ public static MassFlow FromShortTonsPerHour(QuantityValue shorttonsperhour) /// If value is NaN or Infinity. public static MassFlow FromTonnesPerDay(QuantityValue tonnesperday) { - double value = (double) tonnesperday; + QuantityValue value = (QuantityValue) tonnesperday; return new MassFlow(value, MassFlowUnit.TonnePerDay); } @@ -825,7 +828,7 @@ public static MassFlow FromTonnesPerDay(QuantityValue tonnesperday) /// If value is NaN or Infinity. public static MassFlow FromTonnesPerHour(QuantityValue tonnesperhour) { - double value = (double) tonnesperhour; + QuantityValue value = (QuantityValue) tonnesperhour; return new MassFlow(value, MassFlowUnit.TonnePerHour); } @@ -837,7 +840,7 @@ public static MassFlow FromTonnesPerHour(QuantityValue tonnesperhour) /// MassFlow unit value. public static MassFlow From(QuantityValue value, MassFlowUnit fromUnit) { - return new MassFlow((double)value, fromUnit); + return new MassFlow((QuantityValue)value, fromUnit); } #endregion @@ -1007,25 +1010,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassF } /// Get from multiplying value and . - public static MassFlow operator *(double left, MassFlow right) + public static MassFlow operator *(QuantityValue left, MassFlow right) { return new MassFlow(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MassFlow operator *(MassFlow left, double right) + public static MassFlow operator *(MassFlow left, QuantityValue right) { return new MassFlow(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MassFlow operator /(MassFlow left, double right) + public static MassFlow operator /(MassFlow left, QuantityValue right) { return new MassFlow(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MassFlow left, MassFlow right) + public static QuantityValue operator /(MassFlow left, MassFlow right) { return left.GramsPerSecond / right.GramsPerSecond; } @@ -1058,6 +1061,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassF return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MassFlow left, MassFlow right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MassFlow left, MassFlow right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1070,7 +1086,29 @@ public int CompareTo(object obj) /// public int CompareTo(MassFlow other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MassFlow objMassFlow)) + return false; + return Equals(objMassFlow); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MassFlow other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1113,13 +1151,13 @@ public int CompareTo(MassFlow other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassFlow other, double tolerance, ComparisonType comparisonType) + public bool Equals(MassFlow other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1130,7 +1168,7 @@ public bool Equals(MassFlow other, double tolerance, ComparisonType comparisonTy /// A hash code for the current MassFlow. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1141,17 +1179,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MassFlowUnit unit) + public QuantityValue As(MassFlowUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1166,12 +1203,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MassFlowUnit unitAsMassFlowUnit)) + if (!(unit is MassFlowUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFlowUnit)} is supported.", nameof(unit)); - return As(unitAsMassFlowUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1203,7 +1240,7 @@ public MassFlow ToUnit(MassFlowUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (MassFlow)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MassFlowUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1211,17 +1248,17 @@ public MassFlow ToUnit(MassFlowUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassFlowUnit unitAsMassFlowUnit)) + if (!(unit is MassFlowUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFlowUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassFlowUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1248,10 +1285,10 @@ public MassFlow ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MassFlowUnit unit) + private QuantityValue GetValueAs(MassFlowUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs index 48a6bb8a9a..b4836741f1 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Mass flux is the mass flow rate per unit area. /// [DataContract] - public partial struct MassFlux : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MassFlux : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -83,9 +83,9 @@ static MassFlux() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MassFlux(double value, MassFluxUnit unit) + public MassFlux(QuantityValue value, MassFluxUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -97,14 +97,14 @@ public MassFlux(double value, MassFluxUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MassFlux(double value, UnitSystem unitSystem) + public MassFlux(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -145,7 +145,10 @@ public MassFlux(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -168,64 +171,64 @@ public MassFlux(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerHourPerSquareCentimeter => As(MassFluxUnit.GramPerHourPerSquareCentimeter); + public QuantityValue GramsPerHourPerSquareCentimeter => As(MassFluxUnit.GramPerHourPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerHourPerSquareMeter => As(MassFluxUnit.GramPerHourPerSquareMeter); + public QuantityValue GramsPerHourPerSquareMeter => As(MassFluxUnit.GramPerHourPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerHourPerSquareMillimeter => As(MassFluxUnit.GramPerHourPerSquareMillimeter); + public QuantityValue GramsPerHourPerSquareMillimeter => As(MassFluxUnit.GramPerHourPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerSecondPerSquareCentimeter => As(MassFluxUnit.GramPerSecondPerSquareCentimeter); + public QuantityValue GramsPerSecondPerSquareCentimeter => As(MassFluxUnit.GramPerSecondPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); + public QuantityValue GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerSecondPerSquareMillimeter => As(MassFluxUnit.GramPerSecondPerSquareMillimeter); + public QuantityValue GramsPerSecondPerSquareMillimeter => As(MassFluxUnit.GramPerSecondPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerHourPerSquareCentimeter => As(MassFluxUnit.KilogramPerHourPerSquareCentimeter); + public QuantityValue KilogramsPerHourPerSquareCentimeter => As(MassFluxUnit.KilogramPerHourPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerHourPerSquareMeter => As(MassFluxUnit.KilogramPerHourPerSquareMeter); + public QuantityValue KilogramsPerHourPerSquareMeter => As(MassFluxUnit.KilogramPerHourPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerHourPerSquareMillimeter => As(MassFluxUnit.KilogramPerHourPerSquareMillimeter); + public QuantityValue KilogramsPerHourPerSquareMillimeter => As(MassFluxUnit.KilogramPerHourPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerSecondPerSquareCentimeter => As(MassFluxUnit.KilogramPerSecondPerSquareCentimeter); + public QuantityValue KilogramsPerSecondPerSquareCentimeter => As(MassFluxUnit.KilogramPerSecondPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); + public QuantityValue KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerSecondPerSquareMillimeter => As(MassFluxUnit.KilogramPerSecondPerSquareMillimeter); + public QuantityValue KilogramsPerSecondPerSquareMillimeter => As(MassFluxUnit.KilogramPerSecondPerSquareMillimeter); #endregion @@ -314,7 +317,7 @@ public static string GetAbbreviation(MassFluxUnit unit, IFormatProvider? provide /// If value is NaN or Infinity. public static MassFlux FromGramsPerHourPerSquareCentimeter(QuantityValue gramsperhourpersquarecentimeter) { - double value = (double) gramsperhourpersquarecentimeter; + QuantityValue value = (QuantityValue) gramsperhourpersquarecentimeter; return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareCentimeter); } @@ -324,7 +327,7 @@ public static MassFlux FromGramsPerHourPerSquareCentimeter(QuantityValue gramspe /// If value is NaN or Infinity. public static MassFlux FromGramsPerHourPerSquareMeter(QuantityValue gramsperhourpersquaremeter) { - double value = (double) gramsperhourpersquaremeter; + QuantityValue value = (QuantityValue) gramsperhourpersquaremeter; return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareMeter); } @@ -334,7 +337,7 @@ public static MassFlux FromGramsPerHourPerSquareMeter(QuantityValue gramsperhour /// If value is NaN or Infinity. public static MassFlux FromGramsPerHourPerSquareMillimeter(QuantityValue gramsperhourpersquaremillimeter) { - double value = (double) gramsperhourpersquaremillimeter; + QuantityValue value = (QuantityValue) gramsperhourpersquaremillimeter; return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareMillimeter); } @@ -344,7 +347,7 @@ public static MassFlux FromGramsPerHourPerSquareMillimeter(QuantityValue gramspe /// If value is NaN or Infinity. public static MassFlux FromGramsPerSecondPerSquareCentimeter(QuantityValue gramspersecondpersquarecentimeter) { - double value = (double) gramspersecondpersquarecentimeter; + QuantityValue value = (QuantityValue) gramspersecondpersquarecentimeter; return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareCentimeter); } @@ -354,7 +357,7 @@ public static MassFlux FromGramsPerSecondPerSquareCentimeter(QuantityValue grams /// If value is NaN or Infinity. public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue gramspersecondpersquaremeter) { - double value = (double) gramspersecondpersquaremeter; + QuantityValue value = (QuantityValue) gramspersecondpersquaremeter; return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); } @@ -364,7 +367,7 @@ public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue gramsperse /// If value is NaN or Infinity. public static MassFlux FromGramsPerSecondPerSquareMillimeter(QuantityValue gramspersecondpersquaremillimeter) { - double value = (double) gramspersecondpersquaremillimeter; + QuantityValue value = (QuantityValue) gramspersecondpersquaremillimeter; return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMillimeter); } @@ -374,7 +377,7 @@ public static MassFlux FromGramsPerSecondPerSquareMillimeter(QuantityValue grams /// If value is NaN or Infinity. public static MassFlux FromKilogramsPerHourPerSquareCentimeter(QuantityValue kilogramsperhourpersquarecentimeter) { - double value = (double) kilogramsperhourpersquarecentimeter; + QuantityValue value = (QuantityValue) kilogramsperhourpersquarecentimeter; return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareCentimeter); } @@ -384,7 +387,7 @@ public static MassFlux FromKilogramsPerHourPerSquareCentimeter(QuantityValue kil /// If value is NaN or Infinity. public static MassFlux FromKilogramsPerHourPerSquareMeter(QuantityValue kilogramsperhourpersquaremeter) { - double value = (double) kilogramsperhourpersquaremeter; + QuantityValue value = (QuantityValue) kilogramsperhourpersquaremeter; return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareMeter); } @@ -394,7 +397,7 @@ public static MassFlux FromKilogramsPerHourPerSquareMeter(QuantityValue kilogram /// If value is NaN or Infinity. public static MassFlux FromKilogramsPerHourPerSquareMillimeter(QuantityValue kilogramsperhourpersquaremillimeter) { - double value = (double) kilogramsperhourpersquaremillimeter; + QuantityValue value = (QuantityValue) kilogramsperhourpersquaremillimeter; return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareMillimeter); } @@ -404,7 +407,7 @@ public static MassFlux FromKilogramsPerHourPerSquareMillimeter(QuantityValue kil /// If value is NaN or Infinity. public static MassFlux FromKilogramsPerSecondPerSquareCentimeter(QuantityValue kilogramspersecondpersquarecentimeter) { - double value = (double) kilogramspersecondpersquarecentimeter; + QuantityValue value = (QuantityValue) kilogramspersecondpersquarecentimeter; return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareCentimeter); } @@ -414,7 +417,7 @@ public static MassFlux FromKilogramsPerSecondPerSquareCentimeter(QuantityValue k /// If value is NaN or Infinity. public static MassFlux FromKilogramsPerSecondPerSquareMeter(QuantityValue kilogramspersecondpersquaremeter) { - double value = (double) kilogramspersecondpersquaremeter; + QuantityValue value = (QuantityValue) kilogramspersecondpersquaremeter; return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMeter); } @@ -424,7 +427,7 @@ public static MassFlux FromKilogramsPerSecondPerSquareMeter(QuantityValue kilogr /// If value is NaN or Infinity. public static MassFlux FromKilogramsPerSecondPerSquareMillimeter(QuantityValue kilogramspersecondpersquaremillimeter) { - double value = (double) kilogramspersecondpersquaremillimeter; + QuantityValue value = (QuantityValue) kilogramspersecondpersquaremillimeter; return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMillimeter); } @@ -436,7 +439,7 @@ public static MassFlux FromKilogramsPerSecondPerSquareMillimeter(QuantityValue k /// MassFlux unit value. public static MassFlux From(QuantityValue value, MassFluxUnit fromUnit) { - return new MassFlux((double)value, fromUnit); + return new MassFlux((QuantityValue)value, fromUnit); } #endregion @@ -606,25 +609,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassF } /// Get from multiplying value and . - public static MassFlux operator *(double left, MassFlux right) + public static MassFlux operator *(QuantityValue left, MassFlux right) { return new MassFlux(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MassFlux operator *(MassFlux left, double right) + public static MassFlux operator *(MassFlux left, QuantityValue right) { return new MassFlux(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MassFlux operator /(MassFlux left, double right) + public static MassFlux operator /(MassFlux left, QuantityValue right) { return new MassFlux(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MassFlux left, MassFlux right) + public static QuantityValue operator /(MassFlux left, MassFlux right) { return left.KilogramsPerSecondPerSquareMeter / right.KilogramsPerSecondPerSquareMeter; } @@ -657,6 +660,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassF return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MassFlux left, MassFlux right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MassFlux left, MassFlux right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -669,7 +685,29 @@ public int CompareTo(object obj) /// public int CompareTo(MassFlux other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MassFlux objMassFlux)) + return false; + return Equals(objMassFlux); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MassFlux other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -712,13 +750,13 @@ public int CompareTo(MassFlux other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassFlux other, double tolerance, ComparisonType comparisonType) + public bool Equals(MassFlux other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -729,7 +767,7 @@ public bool Equals(MassFlux other, double tolerance, ComparisonType comparisonTy /// A hash code for the current MassFlux. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -740,17 +778,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MassFluxUnit unit) + public QuantityValue As(MassFluxUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -765,12 +802,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MassFluxUnit unitAsMassFluxUnit)) + if (!(unit is MassFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFluxUnit)} is supported.", nameof(unit)); - return As(unitAsMassFluxUnit); + return (QuantityValue)As(typedUnit); } /// @@ -802,7 +839,7 @@ public MassFlux ToUnit(MassFluxUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (MassFlux)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MassFluxUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -810,17 +847,17 @@ public MassFlux ToUnit(MassFluxUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassFluxUnit unitAsMassFluxUnit)) + if (!(unit is MassFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFluxUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassFluxUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -847,10 +884,10 @@ public MassFlux ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MassFluxUnit unit) + private QuantityValue GetValueAs(MassFluxUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs index 2f4b8fe473..56da91983a 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Mass_fraction_(chemistry) /// [DataContract] - public partial struct MassFraction : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MassFraction : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -98,9 +98,9 @@ static MassFraction() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MassFraction(double value, MassFractionUnit unit) + public MassFraction(QuantityValue value, MassFractionUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -112,14 +112,14 @@ public MassFraction(double value, MassFractionUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MassFraction(double value, UnitSystem unitSystem) + public MassFraction(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -160,7 +160,10 @@ public MassFraction(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -183,124 +186,124 @@ public MassFraction(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerGram => As(MassFractionUnit.CentigramPerGram); + public QuantityValue CentigramsPerGram => As(MassFractionUnit.CentigramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerKilogram => As(MassFractionUnit.CentigramPerKilogram); + public QuantityValue CentigramsPerKilogram => As(MassFractionUnit.CentigramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecagramsPerGram => As(MassFractionUnit.DecagramPerGram); + public QuantityValue DecagramsPerGram => As(MassFractionUnit.DecagramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecagramsPerKilogram => As(MassFractionUnit.DecagramPerKilogram); + public QuantityValue DecagramsPerKilogram => As(MassFractionUnit.DecagramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerGram => As(MassFractionUnit.DecigramPerGram); + public QuantityValue DecigramsPerGram => As(MassFractionUnit.DecigramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerKilogram => As(MassFractionUnit.DecigramPerKilogram); + public QuantityValue DecigramsPerKilogram => As(MassFractionUnit.DecigramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimalFractions => As(MassFractionUnit.DecimalFraction); + public QuantityValue DecimalFractions => As(MassFractionUnit.DecimalFraction); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerGram => As(MassFractionUnit.GramPerGram); + public QuantityValue GramsPerGram => As(MassFractionUnit.GramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerKilogram => As(MassFractionUnit.GramPerKilogram); + public QuantityValue GramsPerKilogram => As(MassFractionUnit.GramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HectogramsPerGram => As(MassFractionUnit.HectogramPerGram); + public QuantityValue HectogramsPerGram => As(MassFractionUnit.HectogramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HectogramsPerKilogram => As(MassFractionUnit.HectogramPerKilogram); + public QuantityValue HectogramsPerKilogram => As(MassFractionUnit.HectogramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerGram => As(MassFractionUnit.KilogramPerGram); + public QuantityValue KilogramsPerGram => As(MassFractionUnit.KilogramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerKilogram => As(MassFractionUnit.KilogramPerKilogram); + public QuantityValue KilogramsPerKilogram => As(MassFractionUnit.KilogramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerGram => As(MassFractionUnit.MicrogramPerGram); + public QuantityValue MicrogramsPerGram => As(MassFractionUnit.MicrogramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerKilogram => As(MassFractionUnit.MicrogramPerKilogram); + public QuantityValue MicrogramsPerKilogram => As(MassFractionUnit.MicrogramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerGram => As(MassFractionUnit.MilligramPerGram); + public QuantityValue MilligramsPerGram => As(MassFractionUnit.MilligramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerKilogram => As(MassFractionUnit.MilligramPerKilogram); + public QuantityValue MilligramsPerKilogram => As(MassFractionUnit.MilligramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerGram => As(MassFractionUnit.NanogramPerGram); + public QuantityValue NanogramsPerGram => As(MassFractionUnit.NanogramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerKilogram => As(MassFractionUnit.NanogramPerKilogram); + public QuantityValue NanogramsPerKilogram => As(MassFractionUnit.NanogramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerBillion => As(MassFractionUnit.PartPerBillion); + public QuantityValue PartsPerBillion => As(MassFractionUnit.PartPerBillion); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerMillion => As(MassFractionUnit.PartPerMillion); + public QuantityValue PartsPerMillion => As(MassFractionUnit.PartPerMillion); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerThousand => As(MassFractionUnit.PartPerThousand); + public QuantityValue PartsPerThousand => As(MassFractionUnit.PartPerThousand); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerTrillion => As(MassFractionUnit.PartPerTrillion); + public QuantityValue PartsPerTrillion => As(MassFractionUnit.PartPerTrillion); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Percent => As(MassFractionUnit.Percent); + public QuantityValue Percent => As(MassFractionUnit.Percent); #endregion @@ -425,7 +428,7 @@ public static string GetAbbreviation(MassFractionUnit unit, IFormatProvider? pro /// If value is NaN or Infinity. public static MassFraction FromCentigramsPerGram(QuantityValue centigramspergram) { - double value = (double) centigramspergram; + QuantityValue value = (QuantityValue) centigramspergram; return new MassFraction(value, MassFractionUnit.CentigramPerGram); } @@ -435,7 +438,7 @@ public static MassFraction FromCentigramsPerGram(QuantityValue centigramspergram /// If value is NaN or Infinity. public static MassFraction FromCentigramsPerKilogram(QuantityValue centigramsperkilogram) { - double value = (double) centigramsperkilogram; + QuantityValue value = (QuantityValue) centigramsperkilogram; return new MassFraction(value, MassFractionUnit.CentigramPerKilogram); } @@ -445,7 +448,7 @@ public static MassFraction FromCentigramsPerKilogram(QuantityValue centigramsper /// If value is NaN or Infinity. public static MassFraction FromDecagramsPerGram(QuantityValue decagramspergram) { - double value = (double) decagramspergram; + QuantityValue value = (QuantityValue) decagramspergram; return new MassFraction(value, MassFractionUnit.DecagramPerGram); } @@ -455,7 +458,7 @@ public static MassFraction FromDecagramsPerGram(QuantityValue decagramspergram) /// If value is NaN or Infinity. public static MassFraction FromDecagramsPerKilogram(QuantityValue decagramsperkilogram) { - double value = (double) decagramsperkilogram; + QuantityValue value = (QuantityValue) decagramsperkilogram; return new MassFraction(value, MassFractionUnit.DecagramPerKilogram); } @@ -465,7 +468,7 @@ public static MassFraction FromDecagramsPerKilogram(QuantityValue decagramsperki /// If value is NaN or Infinity. public static MassFraction FromDecigramsPerGram(QuantityValue decigramspergram) { - double value = (double) decigramspergram; + QuantityValue value = (QuantityValue) decigramspergram; return new MassFraction(value, MassFractionUnit.DecigramPerGram); } @@ -475,7 +478,7 @@ public static MassFraction FromDecigramsPerGram(QuantityValue decigramspergram) /// If value is NaN or Infinity. public static MassFraction FromDecigramsPerKilogram(QuantityValue decigramsperkilogram) { - double value = (double) decigramsperkilogram; + QuantityValue value = (QuantityValue) decigramsperkilogram; return new MassFraction(value, MassFractionUnit.DecigramPerKilogram); } @@ -485,7 +488,7 @@ public static MassFraction FromDecigramsPerKilogram(QuantityValue decigramsperki /// If value is NaN or Infinity. public static MassFraction FromDecimalFractions(QuantityValue decimalfractions) { - double value = (double) decimalfractions; + QuantityValue value = (QuantityValue) decimalfractions; return new MassFraction(value, MassFractionUnit.DecimalFraction); } @@ -495,7 +498,7 @@ public static MassFraction FromDecimalFractions(QuantityValue decimalfractions) /// If value is NaN or Infinity. public static MassFraction FromGramsPerGram(QuantityValue gramspergram) { - double value = (double) gramspergram; + QuantityValue value = (QuantityValue) gramspergram; return new MassFraction(value, MassFractionUnit.GramPerGram); } @@ -505,7 +508,7 @@ public static MassFraction FromGramsPerGram(QuantityValue gramspergram) /// If value is NaN or Infinity. public static MassFraction FromGramsPerKilogram(QuantityValue gramsperkilogram) { - double value = (double) gramsperkilogram; + QuantityValue value = (QuantityValue) gramsperkilogram; return new MassFraction(value, MassFractionUnit.GramPerKilogram); } @@ -515,7 +518,7 @@ public static MassFraction FromGramsPerKilogram(QuantityValue gramsperkilogram) /// If value is NaN or Infinity. public static MassFraction FromHectogramsPerGram(QuantityValue hectogramspergram) { - double value = (double) hectogramspergram; + QuantityValue value = (QuantityValue) hectogramspergram; return new MassFraction(value, MassFractionUnit.HectogramPerGram); } @@ -525,7 +528,7 @@ public static MassFraction FromHectogramsPerGram(QuantityValue hectogramspergram /// If value is NaN or Infinity. public static MassFraction FromHectogramsPerKilogram(QuantityValue hectogramsperkilogram) { - double value = (double) hectogramsperkilogram; + QuantityValue value = (QuantityValue) hectogramsperkilogram; return new MassFraction(value, MassFractionUnit.HectogramPerKilogram); } @@ -535,7 +538,7 @@ public static MassFraction FromHectogramsPerKilogram(QuantityValue hectogramsper /// If value is NaN or Infinity. public static MassFraction FromKilogramsPerGram(QuantityValue kilogramspergram) { - double value = (double) kilogramspergram; + QuantityValue value = (QuantityValue) kilogramspergram; return new MassFraction(value, MassFractionUnit.KilogramPerGram); } @@ -545,7 +548,7 @@ public static MassFraction FromKilogramsPerGram(QuantityValue kilogramspergram) /// If value is NaN or Infinity. public static MassFraction FromKilogramsPerKilogram(QuantityValue kilogramsperkilogram) { - double value = (double) kilogramsperkilogram; + QuantityValue value = (QuantityValue) kilogramsperkilogram; return new MassFraction(value, MassFractionUnit.KilogramPerKilogram); } @@ -555,7 +558,7 @@ public static MassFraction FromKilogramsPerKilogram(QuantityValue kilogramsperki /// If value is NaN or Infinity. public static MassFraction FromMicrogramsPerGram(QuantityValue microgramspergram) { - double value = (double) microgramspergram; + QuantityValue value = (QuantityValue) microgramspergram; return new MassFraction(value, MassFractionUnit.MicrogramPerGram); } @@ -565,7 +568,7 @@ public static MassFraction FromMicrogramsPerGram(QuantityValue microgramspergram /// If value is NaN or Infinity. public static MassFraction FromMicrogramsPerKilogram(QuantityValue microgramsperkilogram) { - double value = (double) microgramsperkilogram; + QuantityValue value = (QuantityValue) microgramsperkilogram; return new MassFraction(value, MassFractionUnit.MicrogramPerKilogram); } @@ -575,7 +578,7 @@ public static MassFraction FromMicrogramsPerKilogram(QuantityValue microgramsper /// If value is NaN or Infinity. public static MassFraction FromMilligramsPerGram(QuantityValue milligramspergram) { - double value = (double) milligramspergram; + QuantityValue value = (QuantityValue) milligramspergram; return new MassFraction(value, MassFractionUnit.MilligramPerGram); } @@ -585,7 +588,7 @@ public static MassFraction FromMilligramsPerGram(QuantityValue milligramspergram /// If value is NaN or Infinity. public static MassFraction FromMilligramsPerKilogram(QuantityValue milligramsperkilogram) { - double value = (double) milligramsperkilogram; + QuantityValue value = (QuantityValue) milligramsperkilogram; return new MassFraction(value, MassFractionUnit.MilligramPerKilogram); } @@ -595,7 +598,7 @@ public static MassFraction FromMilligramsPerKilogram(QuantityValue milligramsper /// If value is NaN or Infinity. public static MassFraction FromNanogramsPerGram(QuantityValue nanogramspergram) { - double value = (double) nanogramspergram; + QuantityValue value = (QuantityValue) nanogramspergram; return new MassFraction(value, MassFractionUnit.NanogramPerGram); } @@ -605,7 +608,7 @@ public static MassFraction FromNanogramsPerGram(QuantityValue nanogramspergram) /// If value is NaN or Infinity. public static MassFraction FromNanogramsPerKilogram(QuantityValue nanogramsperkilogram) { - double value = (double) nanogramsperkilogram; + QuantityValue value = (QuantityValue) nanogramsperkilogram; return new MassFraction(value, MassFractionUnit.NanogramPerKilogram); } @@ -615,7 +618,7 @@ public static MassFraction FromNanogramsPerKilogram(QuantityValue nanogramsperki /// If value is NaN or Infinity. public static MassFraction FromPartsPerBillion(QuantityValue partsperbillion) { - double value = (double) partsperbillion; + QuantityValue value = (QuantityValue) partsperbillion; return new MassFraction(value, MassFractionUnit.PartPerBillion); } @@ -625,7 +628,7 @@ public static MassFraction FromPartsPerBillion(QuantityValue partsperbillion) /// If value is NaN or Infinity. public static MassFraction FromPartsPerMillion(QuantityValue partspermillion) { - double value = (double) partspermillion; + QuantityValue value = (QuantityValue) partspermillion; return new MassFraction(value, MassFractionUnit.PartPerMillion); } @@ -635,7 +638,7 @@ public static MassFraction FromPartsPerMillion(QuantityValue partspermillion) /// If value is NaN or Infinity. public static MassFraction FromPartsPerThousand(QuantityValue partsperthousand) { - double value = (double) partsperthousand; + QuantityValue value = (QuantityValue) partsperthousand; return new MassFraction(value, MassFractionUnit.PartPerThousand); } @@ -645,7 +648,7 @@ public static MassFraction FromPartsPerThousand(QuantityValue partsperthousand) /// If value is NaN or Infinity. public static MassFraction FromPartsPerTrillion(QuantityValue partspertrillion) { - double value = (double) partspertrillion; + QuantityValue value = (QuantityValue) partspertrillion; return new MassFraction(value, MassFractionUnit.PartPerTrillion); } @@ -655,7 +658,7 @@ public static MassFraction FromPartsPerTrillion(QuantityValue partspertrillion) /// If value is NaN or Infinity. public static MassFraction FromPercent(QuantityValue percent) { - double value = (double) percent; + QuantityValue value = (QuantityValue) percent; return new MassFraction(value, MassFractionUnit.Percent); } @@ -667,7 +670,7 @@ public static MassFraction FromPercent(QuantityValue percent) /// MassFraction unit value. public static MassFraction From(QuantityValue value, MassFractionUnit fromUnit) { - return new MassFraction((double)value, fromUnit); + return new MassFraction((QuantityValue)value, fromUnit); } #endregion @@ -837,25 +840,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassF } /// Get from multiplying value and . - public static MassFraction operator *(double left, MassFraction right) + public static MassFraction operator *(QuantityValue left, MassFraction right) { return new MassFraction(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MassFraction operator *(MassFraction left, double right) + public static MassFraction operator *(MassFraction left, QuantityValue right) { return new MassFraction(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MassFraction operator /(MassFraction left, double right) + public static MassFraction operator /(MassFraction left, QuantityValue right) { return new MassFraction(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MassFraction left, MassFraction right) + public static QuantityValue operator /(MassFraction left, MassFraction right) { return left.DecimalFractions / right.DecimalFractions; } @@ -888,6 +891,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassF return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MassFraction left, MassFraction right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MassFraction left, MassFraction right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -900,7 +916,29 @@ public int CompareTo(object obj) /// public int CompareTo(MassFraction other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MassFraction objMassFraction)) + return false; + return Equals(objMassFraction); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MassFraction other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -943,13 +981,13 @@ public int CompareTo(MassFraction other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassFraction other, double tolerance, ComparisonType comparisonType) + public bool Equals(MassFraction other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -960,7 +998,7 @@ public bool Equals(MassFraction other, double tolerance, ComparisonType comparis /// A hash code for the current MassFraction. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -971,17 +1009,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MassFractionUnit unit) + public QuantityValue As(MassFractionUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -996,12 +1033,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MassFractionUnit unitAsMassFractionUnit)) + if (!(unit is MassFractionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFractionUnit)} is supported.", nameof(unit)); - return As(unitAsMassFractionUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1033,7 +1070,7 @@ public MassFraction ToUnit(MassFractionUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (MassFraction)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MassFractionUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1041,17 +1078,17 @@ public MassFraction ToUnit(MassFractionUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassFractionUnit unitAsMassFractionUnit)) + if (!(unit is MassFractionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFractionUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassFractionUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1078,10 +1115,10 @@ public MassFraction ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MassFractionUnit unit) + private QuantityValue GetValueAs(MassFractionUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs index 50edc3fea1..5af13e39b5 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// A property of body reflects how its mass is distributed with regard to an axis. /// [DataContract] - public partial struct MassMomentOfInertia : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MassMomentOfInertia : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -99,9 +99,9 @@ static MassMomentOfInertia() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MassMomentOfInertia(double value, MassMomentOfInertiaUnit unit) + public MassMomentOfInertia(QuantityValue value, MassMomentOfInertiaUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -113,14 +113,14 @@ public MassMomentOfInertia(double value, MassMomentOfInertiaUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MassMomentOfInertia(double value, UnitSystem unitSystem) + public MassMomentOfInertia(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -161,7 +161,10 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -184,144 +187,144 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); + public QuantityValue GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); + public QuantityValue GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); + public QuantityValue GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); + public QuantityValue GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); + public QuantityValue KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); + public QuantityValue KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); + public QuantityValue KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); + public QuantityValue KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); + public QuantityValue KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); + public QuantityValue KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); + public QuantityValue KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilotonneSquareMilimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); + public QuantityValue KilotonneSquareMilimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); + public QuantityValue MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); + public QuantityValue MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); + public QuantityValue MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegatonneSquareMilimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); + public QuantityValue MegatonneSquareMilimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); + public QuantityValue MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); + public QuantityValue MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); + public QuantityValue MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); + public QuantityValue MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); + public QuantityValue PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); + public QuantityValue PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SlugSquareFeet => As(MassMomentOfInertiaUnit.SlugSquareFoot); + public QuantityValue SlugSquareFeet => As(MassMomentOfInertiaUnit.SlugSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SlugSquareInches => As(MassMomentOfInertiaUnit.SlugSquareInch); + public QuantityValue SlugSquareInches => As(MassMomentOfInertiaUnit.SlugSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); + public QuantityValue TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); + public QuantityValue TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); + public QuantityValue TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneSquareMilimeters => As(MassMomentOfInertiaUnit.TonneSquareMilimeter); + public QuantityValue TonneSquareMilimeters => As(MassMomentOfInertiaUnit.TonneSquareMilimeter); #endregion @@ -458,7 +461,7 @@ public static string GetAbbreviation(MassMomentOfInertiaUnit unit, IFormatProvid /// If value is NaN or Infinity. public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue gramsquarecentimeters) { - double value = (double) gramsquarecentimeters; + QuantityValue value = (QuantityValue) gramsquarecentimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); } @@ -468,7 +471,7 @@ public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue gramsq /// If value is NaN or Infinity. public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue gramsquaredecimeters) { - double value = (double) gramsquaredecimeters; + QuantityValue value = (QuantityValue) gramsquaredecimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); } @@ -478,7 +481,7 @@ public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue gramsqu /// If value is NaN or Infinity. public static MassMomentOfInertia FromGramSquareMeters(QuantityValue gramsquaremeters) { - double value = (double) gramsquaremeters; + QuantityValue value = (QuantityValue) gramsquaremeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); } @@ -488,7 +491,7 @@ public static MassMomentOfInertia FromGramSquareMeters(QuantityValue gramsquarem /// If value is NaN or Infinity. public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue gramsquaremillimeters) { - double value = (double) gramsquaremillimeters; + QuantityValue value = (QuantityValue) gramsquaremillimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); } @@ -498,7 +501,7 @@ public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue gramsq /// If value is NaN or Infinity. public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue kilogramsquarecentimeters) { - double value = (double) kilogramsquarecentimeters; + QuantityValue value = (QuantityValue) kilogramsquarecentimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); } @@ -508,7 +511,7 @@ public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue ki /// If value is NaN or Infinity. public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue kilogramsquaredecimeters) { - double value = (double) kilogramsquaredecimeters; + QuantityValue value = (QuantityValue) kilogramsquaredecimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); } @@ -518,7 +521,7 @@ public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue kil /// If value is NaN or Infinity. public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue kilogramsquaremeters) { - double value = (double) kilogramsquaremeters; + QuantityValue value = (QuantityValue) kilogramsquaremeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); } @@ -528,7 +531,7 @@ public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue kilogra /// If value is NaN or Infinity. public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue kilogramsquaremillimeters) { - double value = (double) kilogramsquaremillimeters; + QuantityValue value = (QuantityValue) kilogramsquaremillimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); } @@ -538,7 +541,7 @@ public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue ki /// If value is NaN or Infinity. public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue kilotonnesquarecentimeters) { - double value = (double) kilotonnesquarecentimeters; + QuantityValue value = (QuantityValue) kilotonnesquarecentimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); } @@ -548,7 +551,7 @@ public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue k /// If value is NaN or Infinity. public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue kilotonnesquaredecimeters) { - double value = (double) kilotonnesquaredecimeters; + QuantityValue value = (QuantityValue) kilotonnesquaredecimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); } @@ -558,7 +561,7 @@ public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue ki /// If value is NaN or Infinity. public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue kilotonnesquaremeters) { - double value = (double) kilotonnesquaremeters; + QuantityValue value = (QuantityValue) kilotonnesquaremeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); } @@ -568,7 +571,7 @@ public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue kiloto /// If value is NaN or Infinity. public static MassMomentOfInertia FromKilotonneSquareMilimeters(QuantityValue kilotonnesquaremilimeters) { - double value = (double) kilotonnesquaremilimeters; + QuantityValue value = (QuantityValue) kilotonnesquaremilimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); } @@ -578,7 +581,7 @@ public static MassMomentOfInertia FromKilotonneSquareMilimeters(QuantityValue ki /// If value is NaN or Infinity. public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue megatonnesquarecentimeters) { - double value = (double) megatonnesquarecentimeters; + QuantityValue value = (QuantityValue) megatonnesquarecentimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); } @@ -588,7 +591,7 @@ public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue m /// If value is NaN or Infinity. public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue megatonnesquaredecimeters) { - double value = (double) megatonnesquaredecimeters; + QuantityValue value = (QuantityValue) megatonnesquaredecimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); } @@ -598,7 +601,7 @@ public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue me /// If value is NaN or Infinity. public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue megatonnesquaremeters) { - double value = (double) megatonnesquaremeters; + QuantityValue value = (QuantityValue) megatonnesquaremeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); } @@ -608,7 +611,7 @@ public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue megato /// If value is NaN or Infinity. public static MassMomentOfInertia FromMegatonneSquareMilimeters(QuantityValue megatonnesquaremilimeters) { - double value = (double) megatonnesquaremilimeters; + QuantityValue value = (QuantityValue) megatonnesquaremilimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); } @@ -618,7 +621,7 @@ public static MassMomentOfInertia FromMegatonneSquareMilimeters(QuantityValue me /// If value is NaN or Infinity. public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue milligramsquarecentimeters) { - double value = (double) milligramsquarecentimeters; + QuantityValue value = (QuantityValue) milligramsquarecentimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); } @@ -628,7 +631,7 @@ public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue m /// If value is NaN or Infinity. public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue milligramsquaredecimeters) { - double value = (double) milligramsquaredecimeters; + QuantityValue value = (QuantityValue) milligramsquaredecimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); } @@ -638,7 +641,7 @@ public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue mi /// If value is NaN or Infinity. public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue milligramsquaremeters) { - double value = (double) milligramsquaremeters; + QuantityValue value = (QuantityValue) milligramsquaremeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); } @@ -648,7 +651,7 @@ public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue millig /// If value is NaN or Infinity. public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue milligramsquaremillimeters) { - double value = (double) milligramsquaremillimeters; + QuantityValue value = (QuantityValue) milligramsquaremillimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); } @@ -658,7 +661,7 @@ public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue m /// If value is NaN or Infinity. public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue poundsquarefeet) { - double value = (double) poundsquarefeet; + QuantityValue value = (QuantityValue) poundsquarefeet; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); } @@ -668,7 +671,7 @@ public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue poundsquaref /// If value is NaN or Infinity. public static MassMomentOfInertia FromPoundSquareInches(QuantityValue poundsquareinches) { - double value = (double) poundsquareinches; + QuantityValue value = (QuantityValue) poundsquareinches; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); } @@ -678,7 +681,7 @@ public static MassMomentOfInertia FromPoundSquareInches(QuantityValue poundsquar /// If value is NaN or Infinity. public static MassMomentOfInertia FromSlugSquareFeet(QuantityValue slugsquarefeet) { - double value = (double) slugsquarefeet; + QuantityValue value = (QuantityValue) slugsquarefeet; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); } @@ -688,7 +691,7 @@ public static MassMomentOfInertia FromSlugSquareFeet(QuantityValue slugsquarefee /// If value is NaN or Infinity. public static MassMomentOfInertia FromSlugSquareInches(QuantityValue slugsquareinches) { - double value = (double) slugsquareinches; + QuantityValue value = (QuantityValue) slugsquareinches; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); } @@ -698,7 +701,7 @@ public static MassMomentOfInertia FromSlugSquareInches(QuantityValue slugsquarei /// If value is NaN or Infinity. public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue tonnesquarecentimeters) { - double value = (double) tonnesquarecentimeters; + QuantityValue value = (QuantityValue) tonnesquarecentimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); } @@ -708,7 +711,7 @@ public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue tonne /// If value is NaN or Infinity. public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue tonnesquaredecimeters) { - double value = (double) tonnesquaredecimeters; + QuantityValue value = (QuantityValue) tonnesquaredecimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); } @@ -718,7 +721,7 @@ public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue tonnes /// If value is NaN or Infinity. public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue tonnesquaremeters) { - double value = (double) tonnesquaremeters; + QuantityValue value = (QuantityValue) tonnesquaremeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); } @@ -728,7 +731,7 @@ public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue tonnesquar /// If value is NaN or Infinity. public static MassMomentOfInertia FromTonneSquareMilimeters(QuantityValue tonnesquaremilimeters) { - double value = (double) tonnesquaremilimeters; + QuantityValue value = (QuantityValue) tonnesquaremilimeters; return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMilimeter); } @@ -740,7 +743,7 @@ public static MassMomentOfInertia FromTonneSquareMilimeters(QuantityValue tonnes /// MassMomentOfInertia unit value. public static MassMomentOfInertia From(QuantityValue value, MassMomentOfInertiaUnit fromUnit) { - return new MassMomentOfInertia((double)value, fromUnit); + return new MassMomentOfInertia((QuantityValue)value, fromUnit); } #endregion @@ -910,25 +913,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassM } /// Get from multiplying value and . - public static MassMomentOfInertia operator *(double left, MassMomentOfInertia right) + public static MassMomentOfInertia operator *(QuantityValue left, MassMomentOfInertia right) { return new MassMomentOfInertia(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MassMomentOfInertia operator *(MassMomentOfInertia left, double right) + public static MassMomentOfInertia operator *(MassMomentOfInertia left, QuantityValue right) { return new MassMomentOfInertia(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MassMomentOfInertia operator /(MassMomentOfInertia left, double right) + public static MassMomentOfInertia operator /(MassMomentOfInertia left, QuantityValue right) { return new MassMomentOfInertia(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MassMomentOfInertia left, MassMomentOfInertia right) + public static QuantityValue operator /(MassMomentOfInertia left, MassMomentOfInertia right) { return left.KilogramSquareMeters / right.KilogramSquareMeters; } @@ -961,6 +964,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassM return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MassMomentOfInertia left, MassMomentOfInertia right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -973,7 +989,29 @@ public int CompareTo(object obj) /// public int CompareTo(MassMomentOfInertia other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MassMomentOfInertia objMassMomentOfInertia)) + return false; + return Equals(objMassMomentOfInertia); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MassMomentOfInertia other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1016,13 +1054,13 @@ public int CompareTo(MassMomentOfInertia other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassMomentOfInertia other, double tolerance, ComparisonType comparisonType) + public bool Equals(MassMomentOfInertia other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1033,7 +1071,7 @@ public bool Equals(MassMomentOfInertia other, double tolerance, ComparisonType c /// A hash code for the current MassMomentOfInertia. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1044,17 +1082,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MassMomentOfInertiaUnit unit) + public QuantityValue As(MassMomentOfInertiaUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1069,12 +1106,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MassMomentOfInertiaUnit unitAsMassMomentOfInertiaUnit)) + if (!(unit is MassMomentOfInertiaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassMomentOfInertiaUnit)} is supported.", nameof(unit)); - return As(unitAsMassMomentOfInertiaUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1106,7 +1143,7 @@ public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit, UnitConverter un var converted = conversionFunction(this); return (MassMomentOfInertia)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MassMomentOfInertiaUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1114,17 +1151,17 @@ public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassMomentOfInertiaUnit unitAsMassMomentOfInertiaUnit)) + if (!(unit is MassMomentOfInertiaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassMomentOfInertiaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMassMomentOfInertiaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1151,10 +1188,10 @@ public MassMomentOfInertia ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MassMomentOfInertiaUnit unit) + private QuantityValue GetValueAs(MassMomentOfInertiaUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs index 3b11d29f12..4979bd2a8d 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Molar energy is the amount of energy stored in 1 mole of a substance. /// [DataContract] - public partial struct MolarEnergy : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MolarEnergy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -74,9 +74,9 @@ static MolarEnergy() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MolarEnergy(double value, MolarEnergyUnit unit) + public MolarEnergy(QuantityValue value, MolarEnergyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -88,14 +88,14 @@ public MolarEnergy(double value, MolarEnergyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MolarEnergy(double value, UnitSystem unitSystem) + public MolarEnergy(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -136,7 +136,10 @@ public MolarEnergy(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -159,19 +162,19 @@ public MolarEnergy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); + public QuantityValue JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); + public QuantityValue KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); + public QuantityValue MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); #endregion @@ -233,7 +236,7 @@ public static string GetAbbreviation(MolarEnergyUnit unit, IFormatProvider? prov /// If value is NaN or Infinity. public static MolarEnergy FromJoulesPerMole(QuantityValue joulespermole) { - double value = (double) joulespermole; + QuantityValue value = (QuantityValue) joulespermole; return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); } @@ -243,7 +246,7 @@ public static MolarEnergy FromJoulesPerMole(QuantityValue joulespermole) /// If value is NaN or Infinity. public static MolarEnergy FromKilojoulesPerMole(QuantityValue kilojoulespermole) { - double value = (double) kilojoulespermole; + QuantityValue value = (QuantityValue) kilojoulespermole; return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); } @@ -253,7 +256,7 @@ public static MolarEnergy FromKilojoulesPerMole(QuantityValue kilojoulespermole) /// If value is NaN or Infinity. public static MolarEnergy FromMegajoulesPerMole(QuantityValue megajoulespermole) { - double value = (double) megajoulespermole; + QuantityValue value = (QuantityValue) megajoulespermole; return new MolarEnergy(value, MolarEnergyUnit.MegajoulePerMole); } @@ -265,7 +268,7 @@ public static MolarEnergy FromMegajoulesPerMole(QuantityValue megajoulespermole) /// MolarEnergy unit value. public static MolarEnergy From(QuantityValue value, MolarEnergyUnit fromUnit) { - return new MolarEnergy((double)value, fromUnit); + return new MolarEnergy((QuantityValue)value, fromUnit); } #endregion @@ -435,25 +438,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar } /// Get from multiplying value and . - public static MolarEnergy operator *(double left, MolarEnergy right) + public static MolarEnergy operator *(QuantityValue left, MolarEnergy right) { return new MolarEnergy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MolarEnergy operator *(MolarEnergy left, double right) + public static MolarEnergy operator *(MolarEnergy left, QuantityValue right) { return new MolarEnergy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MolarEnergy operator /(MolarEnergy left, double right) + public static MolarEnergy operator /(MolarEnergy left, QuantityValue right) { return new MolarEnergy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MolarEnergy left, MolarEnergy right) + public static QuantityValue operator /(MolarEnergy left, MolarEnergy right) { return left.JoulesPerMole / right.JoulesPerMole; } @@ -486,6 +489,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MolarEnergy left, MolarEnergy right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MolarEnergy left, MolarEnergy right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -498,7 +514,29 @@ public int CompareTo(object obj) /// public int CompareTo(MolarEnergy other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MolarEnergy objMolarEnergy)) + return false; + return Equals(objMolarEnergy); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MolarEnergy other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -541,13 +579,13 @@ public int CompareTo(MolarEnergy other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MolarEnergy other, double tolerance, ComparisonType comparisonType) + public bool Equals(MolarEnergy other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -558,7 +596,7 @@ public bool Equals(MolarEnergy other, double tolerance, ComparisonType compariso /// A hash code for the current MolarEnergy. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -569,17 +607,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MolarEnergyUnit unit) + public QuantityValue As(MolarEnergyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -594,12 +631,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MolarEnergyUnit unitAsMolarEnergyUnit)) + if (!(unit is MolarEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEnergyUnit)} is supported.", nameof(unit)); - return As(unitAsMolarEnergyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -631,7 +668,7 @@ public MolarEnergy ToUnit(MolarEnergyUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (MolarEnergy)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MolarEnergyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -639,17 +676,17 @@ public MolarEnergy ToUnit(MolarEnergyUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MolarEnergyUnit unitAsMolarEnergyUnit)) + if (!(unit is MolarEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMolarEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -676,10 +713,10 @@ public MolarEnergy ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MolarEnergyUnit unit) + private QuantityValue GetValueAs(MolarEnergyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs index 857fcdaf4a..c11e95ba80 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. /// [DataContract] - public partial struct MolarEntropy : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MolarEntropy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -74,9 +74,9 @@ static MolarEntropy() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MolarEntropy(double value, MolarEntropyUnit unit) + public MolarEntropy(QuantityValue value, MolarEntropyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -88,14 +88,14 @@ public MolarEntropy(double value, MolarEntropyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MolarEntropy(double value, UnitSystem unitSystem) + public MolarEntropy(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -136,7 +136,10 @@ public MolarEntropy(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -159,19 +162,19 @@ public MolarEntropy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); + public QuantityValue JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); + public QuantityValue KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); + public QuantityValue MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); #endregion @@ -233,7 +236,7 @@ public static string GetAbbreviation(MolarEntropyUnit unit, IFormatProvider? pro /// If value is NaN or Infinity. public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue joulespermolekelvin) { - double value = (double) joulespermolekelvin; + QuantityValue value = (QuantityValue) joulespermolekelvin; return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); } @@ -243,7 +246,7 @@ public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue joulespermoleke /// If value is NaN or Infinity. public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue kilojoulespermolekelvin) { - double value = (double) kilojoulespermolekelvin; + QuantityValue value = (QuantityValue) kilojoulespermolekelvin; return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); } @@ -253,7 +256,7 @@ public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue kilojoulesp /// If value is NaN or Infinity. public static MolarEntropy FromMegajoulesPerMoleKelvin(QuantityValue megajoulespermolekelvin) { - double value = (double) megajoulespermolekelvin; + QuantityValue value = (QuantityValue) megajoulespermolekelvin; return new MolarEntropy(value, MolarEntropyUnit.MegajoulePerMoleKelvin); } @@ -265,7 +268,7 @@ public static MolarEntropy FromMegajoulesPerMoleKelvin(QuantityValue megajoulesp /// MolarEntropy unit value. public static MolarEntropy From(QuantityValue value, MolarEntropyUnit fromUnit) { - return new MolarEntropy((double)value, fromUnit); + return new MolarEntropy((QuantityValue)value, fromUnit); } #endregion @@ -435,25 +438,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar } /// Get from multiplying value and . - public static MolarEntropy operator *(double left, MolarEntropy right) + public static MolarEntropy operator *(QuantityValue left, MolarEntropy right) { return new MolarEntropy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MolarEntropy operator *(MolarEntropy left, double right) + public static MolarEntropy operator *(MolarEntropy left, QuantityValue right) { return new MolarEntropy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MolarEntropy operator /(MolarEntropy left, double right) + public static MolarEntropy operator /(MolarEntropy left, QuantityValue right) { return new MolarEntropy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MolarEntropy left, MolarEntropy right) + public static QuantityValue operator /(MolarEntropy left, MolarEntropy right) { return left.JoulesPerMoleKelvin / right.JoulesPerMoleKelvin; } @@ -486,6 +489,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MolarEntropy left, MolarEntropy right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MolarEntropy left, MolarEntropy right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -498,7 +514,29 @@ public int CompareTo(object obj) /// public int CompareTo(MolarEntropy other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MolarEntropy objMolarEntropy)) + return false; + return Equals(objMolarEntropy); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MolarEntropy other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -541,13 +579,13 @@ public int CompareTo(MolarEntropy other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MolarEntropy other, double tolerance, ComparisonType comparisonType) + public bool Equals(MolarEntropy other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -558,7 +596,7 @@ public bool Equals(MolarEntropy other, double tolerance, ComparisonType comparis /// A hash code for the current MolarEntropy. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -569,17 +607,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MolarEntropyUnit unit) + public QuantityValue As(MolarEntropyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -594,12 +631,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MolarEntropyUnit unitAsMolarEntropyUnit)) + if (!(unit is MolarEntropyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEntropyUnit)} is supported.", nameof(unit)); - return As(unitAsMolarEntropyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -631,7 +668,7 @@ public MolarEntropy ToUnit(MolarEntropyUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (MolarEntropy)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MolarEntropyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -639,17 +676,17 @@ public MolarEntropy ToUnit(MolarEntropyUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MolarEntropyUnit unitAsMolarEntropyUnit)) + if (!(unit is MolarEntropyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEntropyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMolarEntropyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -676,10 +713,10 @@ public MolarEntropy ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MolarEntropyUnit unit) + private QuantityValue GetValueAs(MolarEntropyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs index 1bc540caa7..94f91b9b40 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance. /// [DataContract] - public partial struct MolarMass : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct MolarMass : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -83,9 +83,9 @@ static MolarMass() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public MolarMass(double value, MolarMassUnit unit) + public MolarMass(QuantityValue value, MolarMassUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -97,14 +97,14 @@ public MolarMass(double value, MolarMassUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MolarMass(double value, UnitSystem unitSystem) + public MolarMass(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -145,7 +145,10 @@ public MolarMass(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -168,64 +171,64 @@ public MolarMass(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); + public QuantityValue CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); + public QuantityValue DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); + public QuantityValue DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerMole => As(MolarMassUnit.GramPerMole); + public QuantityValue GramsPerMole => As(MolarMassUnit.GramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); + public QuantityValue HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); + public QuantityValue KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); + public QuantityValue KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); + public QuantityValue MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); + public QuantityValue MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); + public QuantityValue MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); + public QuantityValue NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); + public QuantityValue PoundsPerMole => As(MolarMassUnit.PoundPerMole); #endregion @@ -326,7 +329,7 @@ public static string GetAbbreviation(MolarMassUnit unit, IFormatProvider? provid /// If value is NaN or Infinity. public static MolarMass FromCentigramsPerMole(QuantityValue centigramspermole) { - double value = (double) centigramspermole; + QuantityValue value = (QuantityValue) centigramspermole; return new MolarMass(value, MolarMassUnit.CentigramPerMole); } @@ -336,7 +339,7 @@ public static MolarMass FromCentigramsPerMole(QuantityValue centigramspermole) /// If value is NaN or Infinity. public static MolarMass FromDecagramsPerMole(QuantityValue decagramspermole) { - double value = (double) decagramspermole; + QuantityValue value = (QuantityValue) decagramspermole; return new MolarMass(value, MolarMassUnit.DecagramPerMole); } @@ -346,7 +349,7 @@ public static MolarMass FromDecagramsPerMole(QuantityValue decagramspermole) /// If value is NaN or Infinity. public static MolarMass FromDecigramsPerMole(QuantityValue decigramspermole) { - double value = (double) decigramspermole; + QuantityValue value = (QuantityValue) decigramspermole; return new MolarMass(value, MolarMassUnit.DecigramPerMole); } @@ -356,7 +359,7 @@ public static MolarMass FromDecigramsPerMole(QuantityValue decigramspermole) /// If value is NaN or Infinity. public static MolarMass FromGramsPerMole(QuantityValue gramspermole) { - double value = (double) gramspermole; + QuantityValue value = (QuantityValue) gramspermole; return new MolarMass(value, MolarMassUnit.GramPerMole); } @@ -366,7 +369,7 @@ public static MolarMass FromGramsPerMole(QuantityValue gramspermole) /// If value is NaN or Infinity. public static MolarMass FromHectogramsPerMole(QuantityValue hectogramspermole) { - double value = (double) hectogramspermole; + QuantityValue value = (QuantityValue) hectogramspermole; return new MolarMass(value, MolarMassUnit.HectogramPerMole); } @@ -376,7 +379,7 @@ public static MolarMass FromHectogramsPerMole(QuantityValue hectogramspermole) /// If value is NaN or Infinity. public static MolarMass FromKilogramsPerMole(QuantityValue kilogramspermole) { - double value = (double) kilogramspermole; + QuantityValue value = (QuantityValue) kilogramspermole; return new MolarMass(value, MolarMassUnit.KilogramPerMole); } @@ -386,7 +389,7 @@ public static MolarMass FromKilogramsPerMole(QuantityValue kilogramspermole) /// If value is NaN or Infinity. public static MolarMass FromKilopoundsPerMole(QuantityValue kilopoundspermole) { - double value = (double) kilopoundspermole; + QuantityValue value = (QuantityValue) kilopoundspermole; return new MolarMass(value, MolarMassUnit.KilopoundPerMole); } @@ -396,7 +399,7 @@ public static MolarMass FromKilopoundsPerMole(QuantityValue kilopoundspermole) /// If value is NaN or Infinity. public static MolarMass FromMegapoundsPerMole(QuantityValue megapoundspermole) { - double value = (double) megapoundspermole; + QuantityValue value = (QuantityValue) megapoundspermole; return new MolarMass(value, MolarMassUnit.MegapoundPerMole); } @@ -406,7 +409,7 @@ public static MolarMass FromMegapoundsPerMole(QuantityValue megapoundspermole) /// If value is NaN or Infinity. public static MolarMass FromMicrogramsPerMole(QuantityValue microgramspermole) { - double value = (double) microgramspermole; + QuantityValue value = (QuantityValue) microgramspermole; return new MolarMass(value, MolarMassUnit.MicrogramPerMole); } @@ -416,7 +419,7 @@ public static MolarMass FromMicrogramsPerMole(QuantityValue microgramspermole) /// If value is NaN or Infinity. public static MolarMass FromMilligramsPerMole(QuantityValue milligramspermole) { - double value = (double) milligramspermole; + QuantityValue value = (QuantityValue) milligramspermole; return new MolarMass(value, MolarMassUnit.MilligramPerMole); } @@ -426,7 +429,7 @@ public static MolarMass FromMilligramsPerMole(QuantityValue milligramspermole) /// If value is NaN or Infinity. public static MolarMass FromNanogramsPerMole(QuantityValue nanogramspermole) { - double value = (double) nanogramspermole; + QuantityValue value = (QuantityValue) nanogramspermole; return new MolarMass(value, MolarMassUnit.NanogramPerMole); } @@ -436,7 +439,7 @@ public static MolarMass FromNanogramsPerMole(QuantityValue nanogramspermole) /// If value is NaN or Infinity. public static MolarMass FromPoundsPerMole(QuantityValue poundspermole) { - double value = (double) poundspermole; + QuantityValue value = (QuantityValue) poundspermole; return new MolarMass(value, MolarMassUnit.PoundPerMole); } @@ -448,7 +451,7 @@ public static MolarMass FromPoundsPerMole(QuantityValue poundspermole) /// MolarMass unit value. public static MolarMass From(QuantityValue value, MolarMassUnit fromUnit) { - return new MolarMass((double)value, fromUnit); + return new MolarMass((QuantityValue)value, fromUnit); } #endregion @@ -618,25 +621,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar } /// Get from multiplying value and . - public static MolarMass operator *(double left, MolarMass right) + public static MolarMass operator *(QuantityValue left, MolarMass right) { return new MolarMass(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MolarMass operator *(MolarMass left, double right) + public static MolarMass operator *(MolarMass left, QuantityValue right) { return new MolarMass(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MolarMass operator /(MolarMass left, double right) + public static MolarMass operator /(MolarMass left, QuantityValue right) { return new MolarMass(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MolarMass left, MolarMass right) + public static QuantityValue operator /(MolarMass left, MolarMass right) { return left.KilogramsPerMole / right.KilogramsPerMole; } @@ -669,6 +672,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(MolarMass left, MolarMass right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(MolarMass left, MolarMass right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -681,7 +697,29 @@ public int CompareTo(object obj) /// public int CompareTo(MolarMass other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is MolarMass objMolarMass)) + return false; + return Equals(objMolarMass); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(MolarMass other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -724,13 +762,13 @@ public int CompareTo(MolarMass other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MolarMass other, double tolerance, ComparisonType comparisonType) + public bool Equals(MolarMass other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -741,7 +779,7 @@ public bool Equals(MolarMass other, double tolerance, ComparisonType comparisonT /// A hash code for the current MolarMass. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -752,17 +790,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MolarMassUnit unit) + public QuantityValue As(MolarMassUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -777,12 +814,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MolarMassUnit unitAsMolarMassUnit)) + if (!(unit is MolarMassUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarMassUnit)} is supported.", nameof(unit)); - return As(unitAsMolarMassUnit); + return (QuantityValue)As(typedUnit); } /// @@ -814,7 +851,7 @@ public MolarMass ToUnit(MolarMassUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (MolarMass)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MolarMassUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -822,17 +859,17 @@ public MolarMass ToUnit(MolarMassUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MolarMassUnit unitAsMolarMassUnit)) + if (!(unit is MolarMassUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarMassUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMolarMassUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -859,10 +896,10 @@ public MolarMass ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MolarMassUnit unit) + private QuantityValue GetValueAs(MolarMassUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs index 0403f2c28f..e654cdedfc 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Molar_concentration /// [DataContract] - public partial struct Molarity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Molarity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -91,9 +91,9 @@ static Molarity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Molarity(double value, MolarityUnit unit) + public Molarity(QuantityValue value, MolarityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -105,14 +105,14 @@ public Molarity(double value, MolarityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Molarity(double value, UnitSystem unitSystem) + public Molarity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -153,7 +153,10 @@ public Molarity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -176,49 +179,49 @@ public Molarity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentimolesPerLiter => As(MolarityUnit.CentimolePerLiter); + public QuantityValue CentimolesPerLiter => As(MolarityUnit.CentimolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimolesPerLiter => As(MolarityUnit.DecimolePerLiter); + public QuantityValue DecimolesPerLiter => As(MolarityUnit.DecimolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FemtomolesPerLiter => As(MolarityUnit.FemtomolePerLiter); + public QuantityValue FemtomolesPerLiter => As(MolarityUnit.FemtomolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicromolesPerLiter => As(MolarityUnit.MicromolePerLiter); + public QuantityValue MicromolesPerLiter => As(MolarityUnit.MicromolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimolesPerLiter => As(MolarityUnit.MillimolePerLiter); + public QuantityValue MillimolesPerLiter => As(MolarityUnit.MillimolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MolesPerCubicMeter => As(MolarityUnit.MolePerCubicMeter); + public QuantityValue MolesPerCubicMeter => As(MolarityUnit.MolePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MolesPerLiter => As(MolarityUnit.MolePerLiter); + public QuantityValue MolesPerLiter => As(MolarityUnit.MolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanomolesPerLiter => As(MolarityUnit.NanomolePerLiter); + public QuantityValue NanomolesPerLiter => As(MolarityUnit.NanomolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicomolesPerLiter => As(MolarityUnit.PicomolePerLiter); + public QuantityValue PicomolesPerLiter => As(MolarityUnit.PicomolePerLiter); #endregion @@ -322,7 +325,7 @@ public static string GetAbbreviation(MolarityUnit unit, IFormatProvider? provide /// If value is NaN or Infinity. public static Molarity FromCentimolesPerLiter(QuantityValue centimolesperliter) { - double value = (double) centimolesperliter; + QuantityValue value = (QuantityValue) centimolesperliter; return new Molarity(value, MolarityUnit.CentimolePerLiter); } @@ -332,7 +335,7 @@ public static Molarity FromCentimolesPerLiter(QuantityValue centimolesperliter) /// If value is NaN or Infinity. public static Molarity FromDecimolesPerLiter(QuantityValue decimolesperliter) { - double value = (double) decimolesperliter; + QuantityValue value = (QuantityValue) decimolesperliter; return new Molarity(value, MolarityUnit.DecimolePerLiter); } @@ -342,7 +345,7 @@ public static Molarity FromDecimolesPerLiter(QuantityValue decimolesperliter) /// If value is NaN or Infinity. public static Molarity FromFemtomolesPerLiter(QuantityValue femtomolesperliter) { - double value = (double) femtomolesperliter; + QuantityValue value = (QuantityValue) femtomolesperliter; return new Molarity(value, MolarityUnit.FemtomolePerLiter); } @@ -352,7 +355,7 @@ public static Molarity FromFemtomolesPerLiter(QuantityValue femtomolesperliter) /// If value is NaN or Infinity. public static Molarity FromMicromolesPerLiter(QuantityValue micromolesperliter) { - double value = (double) micromolesperliter; + QuantityValue value = (QuantityValue) micromolesperliter; return new Molarity(value, MolarityUnit.MicromolePerLiter); } @@ -362,7 +365,7 @@ public static Molarity FromMicromolesPerLiter(QuantityValue micromolesperliter) /// If value is NaN or Infinity. public static Molarity FromMillimolesPerLiter(QuantityValue millimolesperliter) { - double value = (double) millimolesperliter; + QuantityValue value = (QuantityValue) millimolesperliter; return new Molarity(value, MolarityUnit.MillimolePerLiter); } @@ -372,7 +375,7 @@ public static Molarity FromMillimolesPerLiter(QuantityValue millimolesperliter) /// If value is NaN or Infinity. public static Molarity FromMolesPerCubicMeter(QuantityValue molespercubicmeter) { - double value = (double) molespercubicmeter; + QuantityValue value = (QuantityValue) molespercubicmeter; return new Molarity(value, MolarityUnit.MolePerCubicMeter); } @@ -382,7 +385,7 @@ public static Molarity FromMolesPerCubicMeter(QuantityValue molespercubicmeter) /// If value is NaN or Infinity. public static Molarity FromMolesPerLiter(QuantityValue molesperliter) { - double value = (double) molesperliter; + QuantityValue value = (QuantityValue) molesperliter; return new Molarity(value, MolarityUnit.MolePerLiter); } @@ -392,7 +395,7 @@ public static Molarity FromMolesPerLiter(QuantityValue molesperliter) /// If value is NaN or Infinity. public static Molarity FromNanomolesPerLiter(QuantityValue nanomolesperliter) { - double value = (double) nanomolesperliter; + QuantityValue value = (QuantityValue) nanomolesperliter; return new Molarity(value, MolarityUnit.NanomolePerLiter); } @@ -402,7 +405,7 @@ public static Molarity FromNanomolesPerLiter(QuantityValue nanomolesperliter) /// If value is NaN or Infinity. public static Molarity FromPicomolesPerLiter(QuantityValue picomolesperliter) { - double value = (double) picomolesperliter; + QuantityValue value = (QuantityValue) picomolesperliter; return new Molarity(value, MolarityUnit.PicomolePerLiter); } @@ -414,7 +417,7 @@ public static Molarity FromPicomolesPerLiter(QuantityValue picomolesperliter) /// Molarity unit value. public static Molarity From(QuantityValue value, MolarityUnit fromUnit) { - return new Molarity((double)value, fromUnit); + return new Molarity((QuantityValue)value, fromUnit); } #endregion @@ -584,25 +587,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar } /// Get from multiplying value and . - public static Molarity operator *(double left, Molarity right) + public static Molarity operator *(QuantityValue left, Molarity right) { return new Molarity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Molarity operator *(Molarity left, double right) + public static Molarity operator *(Molarity left, QuantityValue right) { return new Molarity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Molarity operator /(Molarity left, double right) + public static Molarity operator /(Molarity left, QuantityValue right) { return new Molarity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Molarity left, Molarity right) + public static QuantityValue operator /(Molarity left, Molarity right) { return left.MolesPerCubicMeter / right.MolesPerCubicMeter; } @@ -635,6 +638,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Molarity left, Molarity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Molarity left, Molarity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -647,7 +663,29 @@ public int CompareTo(object obj) /// public int CompareTo(Molarity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Molarity objMolarity)) + return false; + return Equals(objMolarity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Molarity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -690,13 +728,13 @@ public int CompareTo(Molarity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Molarity other, double tolerance, ComparisonType comparisonType) + public bool Equals(Molarity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -707,7 +745,7 @@ public bool Equals(Molarity other, double tolerance, ComparisonType comparisonTy /// A hash code for the current Molarity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -718,17 +756,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(MolarityUnit unit) + public QuantityValue As(MolarityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -743,12 +780,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is MolarityUnit unitAsMolarityUnit)) + if (!(unit is MolarityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarityUnit)} is supported.", nameof(unit)); - return As(unitAsMolarityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -780,7 +817,7 @@ public Molarity ToUnit(MolarityUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Molarity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(MolarityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -788,17 +825,17 @@ public Molarity ToUnit(MolarityUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MolarityUnit unitAsMolarityUnit)) + if (!(unit is MolarityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsMolarityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -825,10 +862,10 @@ public Molarity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(MolarityUnit unit) + private QuantityValue GetValueAs(MolarityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs index 8f4f597901..859e80a650 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Permeability_(electromagnetism) /// [DataContract] - public partial struct Permeability : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Permeability : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static Permeability() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Permeability(double value, PermeabilityUnit unit) + public Permeability(QuantityValue value, PermeabilityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public Permeability(double value, PermeabilityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Permeability(double value, UnitSystem unitSystem) + public Permeability(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public Permeability(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public Permeability(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); + public QuantityValue HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(PermeabilityUnit unit, IFormatProvider? pro /// If value is NaN or Infinity. public static Permeability FromHenriesPerMeter(QuantityValue henriespermeter) { - double value = (double) henriespermeter; + QuantityValue value = (QuantityValue) henriespermeter; return new Permeability(value, PermeabilityUnit.HenryPerMeter); } @@ -230,7 +233,7 @@ public static Permeability FromHenriesPerMeter(QuantityValue henriespermeter) /// Permeability unit value. public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit) { - return new Permeability((double)value, fromUnit); + return new Permeability((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Perme } /// Get from multiplying value and . - public static Permeability operator *(double left, Permeability right) + public static Permeability operator *(QuantityValue left, Permeability right) { return new Permeability(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Permeability operator *(Permeability left, double right) + public static Permeability operator *(Permeability left, QuantityValue right) { return new Permeability(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Permeability operator /(Permeability left, double right) + public static Permeability operator /(Permeability left, QuantityValue right) { return new Permeability(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Permeability left, Permeability right) + public static QuantityValue operator /(Permeability left, Permeability right) { return left.HenriesPerMeter / right.HenriesPerMeter; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Perme return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Permeability left, Permeability right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Permeability left, Permeability right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(Permeability other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Permeability objPermeability)) + return false; + return Equals(objPermeability); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Permeability other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(Permeability other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Permeability other, double tolerance, ComparisonType comparisonType) + public bool Equals(Permeability other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(Permeability other, double tolerance, ComparisonType comparis /// A hash code for the current Permeability. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(PermeabilityUnit unit) + public QuantityValue As(PermeabilityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is PermeabilityUnit unitAsPermeabilityUnit)) + if (!(unit is PermeabilityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit)); - return As(unitAsPermeabilityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public Permeability ToUnit(PermeabilityUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Permeability)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(PermeabilityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public Permeability ToUnit(PermeabilityUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PermeabilityUnit unitAsPermeabilityUnit)) + if (!(unit is PermeabilityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPermeabilityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public Permeability ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(PermeabilityUnit unit) + private QuantityValue GetValueAs(PermeabilityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs index a375f49800..666aeab093 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Permittivity /// [DataContract] - public partial struct Permittivity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Permittivity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static Permittivity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Permittivity(double value, PermittivityUnit unit) + public Permittivity(QuantityValue value, PermittivityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public Permittivity(double value, PermittivityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Permittivity(double value, UnitSystem unitSystem) + public Permittivity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public Permittivity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public Permittivity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); + public QuantityValue FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(PermittivityUnit unit, IFormatProvider? pro /// If value is NaN or Infinity. public static Permittivity FromFaradsPerMeter(QuantityValue faradspermeter) { - double value = (double) faradspermeter; + QuantityValue value = (QuantityValue) faradspermeter; return new Permittivity(value, PermittivityUnit.FaradPerMeter); } @@ -230,7 +233,7 @@ public static Permittivity FromFaradsPerMeter(QuantityValue faradspermeter) /// Permittivity unit value. public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit) { - return new Permittivity((double)value, fromUnit); + return new Permittivity((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Permi } /// Get from multiplying value and . - public static Permittivity operator *(double left, Permittivity right) + public static Permittivity operator *(QuantityValue left, Permittivity right) { return new Permittivity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Permittivity operator *(Permittivity left, double right) + public static Permittivity operator *(Permittivity left, QuantityValue right) { return new Permittivity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Permittivity operator /(Permittivity left, double right) + public static Permittivity operator /(Permittivity left, QuantityValue right) { return new Permittivity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Permittivity left, Permittivity right) + public static QuantityValue operator /(Permittivity left, Permittivity right) { return left.FaradsPerMeter / right.FaradsPerMeter; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Permi return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Permittivity left, Permittivity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Permittivity left, Permittivity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(Permittivity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Permittivity objPermittivity)) + return false; + return Equals(objPermittivity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Permittivity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(Permittivity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Permittivity other, double tolerance, ComparisonType comparisonType) + public bool Equals(Permittivity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(Permittivity other, double tolerance, ComparisonType comparis /// A hash code for the current Permittivity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(PermittivityUnit unit) + public QuantityValue As(PermittivityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is PermittivityUnit unitAsPermittivityUnit)) + if (!(unit is PermittivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermittivityUnit)} is supported.", nameof(unit)); - return As(unitAsPermittivityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public Permittivity ToUnit(PermittivityUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Permittivity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(PermittivityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public Permittivity ToUnit(PermittivityUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PermittivityUnit unitAsPermittivityUnit)) + if (!(unit is PermittivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermittivityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPermittivityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public Permittivity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(PermittivityUnit unit) + private QuantityValue GetValueAs(PermittivityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs index 3bf7765d64..0ed6169e45 100644 --- a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Permeability_(Earth_sciences) /// [DataContract] - public partial struct PorousMediumPermeability : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct PorousMediumPermeability : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -79,9 +79,9 @@ static PorousMediumPermeability() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public PorousMediumPermeability(double value, PorousMediumPermeabilityUnit unit) + public PorousMediumPermeability(QuantityValue value, PorousMediumPermeabilityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -93,14 +93,14 @@ public PorousMediumPermeability(double value, PorousMediumPermeabilityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public PorousMediumPermeability(double value, UnitSystem unitSystem) + public PorousMediumPermeability(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -141,7 +141,10 @@ public PorousMediumPermeability(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -164,29 +167,29 @@ public PorousMediumPermeability(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Darcys => As(PorousMediumPermeabilityUnit.Darcy); + public QuantityValue Darcys => As(PorousMediumPermeabilityUnit.Darcy); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microdarcys => As(PorousMediumPermeabilityUnit.Microdarcy); + public QuantityValue Microdarcys => As(PorousMediumPermeabilityUnit.Microdarcy); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millidarcys => As(PorousMediumPermeabilityUnit.Millidarcy); + public QuantityValue Millidarcys => As(PorousMediumPermeabilityUnit.Millidarcy); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareCentimeters => As(PorousMediumPermeabilityUnit.SquareCentimeter); + public QuantityValue SquareCentimeters => As(PorousMediumPermeabilityUnit.SquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareMeters => As(PorousMediumPermeabilityUnit.SquareMeter); + public QuantityValue SquareMeters => As(PorousMediumPermeabilityUnit.SquareMeter); #endregion @@ -254,7 +257,7 @@ public static string GetAbbreviation(PorousMediumPermeabilityUnit unit, IFormatP /// If value is NaN or Infinity. public static PorousMediumPermeability FromDarcys(QuantityValue darcys) { - double value = (double) darcys; + QuantityValue value = (QuantityValue) darcys; return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Darcy); } @@ -264,7 +267,7 @@ public static PorousMediumPermeability FromDarcys(QuantityValue darcys) /// If value is NaN or Infinity. public static PorousMediumPermeability FromMicrodarcys(QuantityValue microdarcys) { - double value = (double) microdarcys; + QuantityValue value = (QuantityValue) microdarcys; return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Microdarcy); } @@ -274,7 +277,7 @@ public static PorousMediumPermeability FromMicrodarcys(QuantityValue microdarcys /// If value is NaN or Infinity. public static PorousMediumPermeability FromMillidarcys(QuantityValue millidarcys) { - double value = (double) millidarcys; + QuantityValue value = (QuantityValue) millidarcys; return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Millidarcy); } @@ -284,7 +287,7 @@ public static PorousMediumPermeability FromMillidarcys(QuantityValue millidarcys /// If value is NaN or Infinity. public static PorousMediumPermeability FromSquareCentimeters(QuantityValue squarecentimeters) { - double value = (double) squarecentimeters; + QuantityValue value = (QuantityValue) squarecentimeters; return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.SquareCentimeter); } @@ -294,7 +297,7 @@ public static PorousMediumPermeability FromSquareCentimeters(QuantityValue squar /// If value is NaN or Infinity. public static PorousMediumPermeability FromSquareMeters(QuantityValue squaremeters) { - double value = (double) squaremeters; + QuantityValue value = (QuantityValue) squaremeters; return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.SquareMeter); } @@ -306,7 +309,7 @@ public static PorousMediumPermeability FromSquareMeters(QuantityValue squaremete /// PorousMediumPermeability unit value. public static PorousMediumPermeability From(QuantityValue value, PorousMediumPermeabilityUnit fromUnit) { - return new PorousMediumPermeability((double)value, fromUnit); + return new PorousMediumPermeability((QuantityValue)value, fromUnit); } #endregion @@ -476,25 +479,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Porou } /// Get from multiplying value and . - public static PorousMediumPermeability operator *(double left, PorousMediumPermeability right) + public static PorousMediumPermeability operator *(QuantityValue left, PorousMediumPermeability right) { return new PorousMediumPermeability(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static PorousMediumPermeability operator *(PorousMediumPermeability left, double right) + public static PorousMediumPermeability operator *(PorousMediumPermeability left, QuantityValue right) { return new PorousMediumPermeability(left.Value * right, left.Unit); } /// Get from dividing by value. - public static PorousMediumPermeability operator /(PorousMediumPermeability left, double right) + public static PorousMediumPermeability operator /(PorousMediumPermeability left, QuantityValue right) { return new PorousMediumPermeability(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(PorousMediumPermeability left, PorousMediumPermeability right) + public static QuantityValue operator /(PorousMediumPermeability left, PorousMediumPermeability right) { return left.SquareMeters / right.SquareMeters; } @@ -527,6 +530,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Porou return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(PorousMediumPermeability left, PorousMediumPermeability right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(PorousMediumPermeability left, PorousMediumPermeability right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -539,7 +555,29 @@ public int CompareTo(object obj) /// public int CompareTo(PorousMediumPermeability other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is PorousMediumPermeability objPorousMediumPermeability)) + return false; + return Equals(objPorousMediumPermeability); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(PorousMediumPermeability other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -582,13 +620,13 @@ public int CompareTo(PorousMediumPermeability other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PorousMediumPermeability other, double tolerance, ComparisonType comparisonType) + public bool Equals(PorousMediumPermeability other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -599,7 +637,7 @@ public bool Equals(PorousMediumPermeability other, double tolerance, ComparisonT /// A hash code for the current PorousMediumPermeability. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -610,17 +648,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(PorousMediumPermeabilityUnit unit) + public QuantityValue As(PorousMediumPermeabilityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -635,12 +672,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is PorousMediumPermeabilityUnit unitAsPorousMediumPermeabilityUnit)) + if (!(unit is PorousMediumPermeabilityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PorousMediumPermeabilityUnit)} is supported.", nameof(unit)); - return As(unitAsPorousMediumPermeabilityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -672,7 +709,7 @@ public PorousMediumPermeability ToUnit(PorousMediumPermeabilityUnit unit, UnitCo var converted = conversionFunction(this); return (PorousMediumPermeability)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(PorousMediumPermeabilityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -680,17 +717,17 @@ public PorousMediumPermeability ToUnit(PorousMediumPermeabilityUnit unit, UnitCo } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PorousMediumPermeabilityUnit unitAsPorousMediumPermeabilityUnit)) + if (!(unit is PorousMediumPermeabilityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PorousMediumPermeabilityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPorousMediumPermeabilityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -717,10 +754,10 @@ public PorousMediumPermeability ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(PorousMediumPermeabilityUnit unit) + private QuantityValue GetValueAs(PorousMediumPermeabilityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Power.g.cs b/UnitsNet/GeneratedCode/Quantities/Power.g.cs index 843092f2dc..fd569d371d 100644 --- a/UnitsNet/GeneratedCode/Quantities/Power.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Power.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. /// [DataContract] - public partial struct Power : IQuantity, IDecimalQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Power : IQuantity, IDecimalQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly decimal _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -97,7 +97,7 @@ static Power() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Power(decimal value, PowerUnit unit) + public Power(QuantityValue value, PowerUnit unit) { _value = value; _unit = unit; @@ -111,7 +111,7 @@ public Power(decimal value, PowerUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Power(decimal value, UnitSystem unitSystem) + public Power(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -159,12 +159,13 @@ public Power(decimal value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public decimal Value => _value; + public QuantityValue Value => _value; - double IQuantity.Value => (double) _value; + /// + QuantityValue IQuantity.Value => _value; /// - decimal IDecimalQuantity.Value => _value; + decimal IDecimalQuantity.Value => (decimal)_value; Enum IQuantity.Unit => Unit; @@ -187,134 +188,134 @@ public Power(decimal value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BoilerHorsepower => As(PowerUnit.BoilerHorsepower); + public QuantityValue BoilerHorsepower => As(PowerUnit.BoilerHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); + public QuantityValue BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decawatts => As(PowerUnit.Decawatt); + public QuantityValue Decawatts => As(PowerUnit.Decawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Deciwatts => As(PowerUnit.Deciwatt); + public QuantityValue Deciwatts => As(PowerUnit.Deciwatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); + public QuantityValue ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Femtowatts => As(PowerUnit.Femtowatt); + public QuantityValue Femtowatts => As(PowerUnit.Femtowatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigajoulesPerHour => As(PowerUnit.GigajoulePerHour); + public QuantityValue GigajoulesPerHour => As(PowerUnit.GigajoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gigawatts => As(PowerUnit.Gigawatt); + public QuantityValue Gigawatts => As(PowerUnit.Gigawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); + public QuantityValue HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerHour => As(PowerUnit.JoulePerHour); + public QuantityValue JoulesPerHour => As(PowerUnit.JoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); + public QuantityValue KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerHour => As(PowerUnit.KilojoulePerHour); + public QuantityValue KilojoulesPerHour => As(PowerUnit.KilojoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilowatts => As(PowerUnit.Kilowatt); + public QuantityValue Kilowatts => As(PowerUnit.Kilowatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); + public QuantityValue MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegabritishThermalUnitsPerHour => As(PowerUnit.MegabritishThermalUnitPerHour); + public QuantityValue MegabritishThermalUnitsPerHour => As(PowerUnit.MegabritishThermalUnitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegajoulesPerHour => As(PowerUnit.MegajoulePerHour); + public QuantityValue MegajoulesPerHour => As(PowerUnit.MegajoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megawatts => As(PowerUnit.Megawatt); + public QuantityValue Megawatts => As(PowerUnit.Megawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetricHorsepower => As(PowerUnit.MetricHorsepower); + public QuantityValue MetricHorsepower => As(PowerUnit.MetricHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microwatts => As(PowerUnit.Microwatt); + public QuantityValue Microwatts => As(PowerUnit.Microwatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillijoulesPerHour => As(PowerUnit.MillijoulePerHour); + public QuantityValue MillijoulesPerHour => As(PowerUnit.MillijoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milliwatts => As(PowerUnit.Milliwatt); + public QuantityValue Milliwatts => As(PowerUnit.Milliwatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Nanowatts => As(PowerUnit.Nanowatt); + public QuantityValue Nanowatts => As(PowerUnit.Nanowatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Petawatts => As(PowerUnit.Petawatt); + public QuantityValue Petawatts => As(PowerUnit.Petawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Picowatts => As(PowerUnit.Picowatt); + public QuantityValue Picowatts => As(PowerUnit.Picowatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Terawatts => As(PowerUnit.Terawatt); + public QuantityValue Terawatts => As(PowerUnit.Terawatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Watts => As(PowerUnit.Watt); + public QuantityValue Watts => As(PowerUnit.Watt); #endregion @@ -328,7 +329,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) { // Register in unit converter: BaseUnit -> PowerUnit 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.BritishThermalUnitPerHour, quantity => new Power(quantity.Value / 0.29307107017m, 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)); @@ -337,11 +338,11 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) 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.KilobritishThermalUnitPerHour, quantity => new Power((quantity.Value / 0.29307107017m) / 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.MegabritishThermalUnitPerHour, quantity => new Power((quantity.Value / 0.293071m) / 1e6m, PowerUnit.MegabritishThermalUnitPerHour)); + unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MegabritishThermalUnitPerHour, quantity => new Power((quantity.Value / 0.29307107017m) / 1e6m, PowerUnit.MegabritishThermalUnitPerHour)); 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)); @@ -358,7 +359,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) // Register in unit converter: PowerUnit -> BaseUnit 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.BritishThermalUnitPerHour, PowerUnit.Watt, quantity => new Power(quantity.Value * 0.29307107017m, 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)); @@ -367,11 +368,11 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) 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.KilobritishThermalUnitPerHour, PowerUnit.Watt, quantity => new Power((quantity.Value * 0.29307107017m) * 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.MegabritishThermalUnitPerHour, PowerUnit.Watt, quantity => new Power((quantity.Value * 0.293071m) * 1e6m, PowerUnit.Watt)); + unitConverter.SetConversionFunction(PowerUnit.MegabritishThermalUnitPerHour, PowerUnit.Watt, quantity => new Power((quantity.Value * 0.29307107017m) * 1e6m, 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)); @@ -445,7 +446,7 @@ public static string GetAbbreviation(PowerUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Power FromBoilerHorsepower(QuantityValue boilerhorsepower) { - decimal value = (decimal) boilerhorsepower; + QuantityValue value = (QuantityValue) boilerhorsepower; return new Power(value, PowerUnit.BoilerHorsepower); } @@ -455,7 +456,7 @@ public static Power FromBoilerHorsepower(QuantityValue boilerhorsepower) /// If value is NaN or Infinity. public static Power FromBritishThermalUnitsPerHour(QuantityValue britishthermalunitsperhour) { - decimal value = (decimal) britishthermalunitsperhour; + QuantityValue value = (QuantityValue) britishthermalunitsperhour; return new Power(value, PowerUnit.BritishThermalUnitPerHour); } @@ -465,7 +466,7 @@ public static Power FromBritishThermalUnitsPerHour(QuantityValue britishthermalu /// If value is NaN or Infinity. public static Power FromDecawatts(QuantityValue decawatts) { - decimal value = (decimal) decawatts; + QuantityValue value = (QuantityValue) decawatts; return new Power(value, PowerUnit.Decawatt); } @@ -475,7 +476,7 @@ public static Power FromDecawatts(QuantityValue decawatts) /// If value is NaN or Infinity. public static Power FromDeciwatts(QuantityValue deciwatts) { - decimal value = (decimal) deciwatts; + QuantityValue value = (QuantityValue) deciwatts; return new Power(value, PowerUnit.Deciwatt); } @@ -485,7 +486,7 @@ public static Power FromDeciwatts(QuantityValue deciwatts) /// If value is NaN or Infinity. public static Power FromElectricalHorsepower(QuantityValue electricalhorsepower) { - decimal value = (decimal) electricalhorsepower; + QuantityValue value = (QuantityValue) electricalhorsepower; return new Power(value, PowerUnit.ElectricalHorsepower); } @@ -495,7 +496,7 @@ public static Power FromElectricalHorsepower(QuantityValue electricalhorsepower) /// If value is NaN or Infinity. public static Power FromFemtowatts(QuantityValue femtowatts) { - decimal value = (decimal) femtowatts; + QuantityValue value = (QuantityValue) femtowatts; return new Power(value, PowerUnit.Femtowatt); } @@ -505,7 +506,7 @@ public static Power FromFemtowatts(QuantityValue femtowatts) /// If value is NaN or Infinity. public static Power FromGigajoulesPerHour(QuantityValue gigajoulesperhour) { - decimal value = (decimal) gigajoulesperhour; + QuantityValue value = (QuantityValue) gigajoulesperhour; return new Power(value, PowerUnit.GigajoulePerHour); } @@ -515,7 +516,7 @@ public static Power FromGigajoulesPerHour(QuantityValue gigajoulesperhour) /// If value is NaN or Infinity. public static Power FromGigawatts(QuantityValue gigawatts) { - decimal value = (decimal) gigawatts; + QuantityValue value = (QuantityValue) gigawatts; return new Power(value, PowerUnit.Gigawatt); } @@ -525,7 +526,7 @@ public static Power FromGigawatts(QuantityValue gigawatts) /// If value is NaN or Infinity. public static Power FromHydraulicHorsepower(QuantityValue hydraulichorsepower) { - decimal value = (decimal) hydraulichorsepower; + QuantityValue value = (QuantityValue) hydraulichorsepower; return new Power(value, PowerUnit.HydraulicHorsepower); } @@ -535,7 +536,7 @@ public static Power FromHydraulicHorsepower(QuantityValue hydraulichorsepower) /// If value is NaN or Infinity. public static Power FromJoulesPerHour(QuantityValue joulesperhour) { - decimal value = (decimal) joulesperhour; + QuantityValue value = (QuantityValue) joulesperhour; return new Power(value, PowerUnit.JoulePerHour); } @@ -545,7 +546,7 @@ public static Power FromJoulesPerHour(QuantityValue joulesperhour) /// If value is NaN or Infinity. public static Power FromKilobritishThermalUnitsPerHour(QuantityValue kilobritishthermalunitsperhour) { - decimal value = (decimal) kilobritishthermalunitsperhour; + QuantityValue value = (QuantityValue) kilobritishthermalunitsperhour; return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); } @@ -555,7 +556,7 @@ public static Power FromKilobritishThermalUnitsPerHour(QuantityValue kilobritish /// If value is NaN or Infinity. public static Power FromKilojoulesPerHour(QuantityValue kilojoulesperhour) { - decimal value = (decimal) kilojoulesperhour; + QuantityValue value = (QuantityValue) kilojoulesperhour; return new Power(value, PowerUnit.KilojoulePerHour); } @@ -565,7 +566,7 @@ public static Power FromKilojoulesPerHour(QuantityValue kilojoulesperhour) /// If value is NaN or Infinity. public static Power FromKilowatts(QuantityValue kilowatts) { - decimal value = (decimal) kilowatts; + QuantityValue value = (QuantityValue) kilowatts; return new Power(value, PowerUnit.Kilowatt); } @@ -575,7 +576,7 @@ public static Power FromKilowatts(QuantityValue kilowatts) /// If value is NaN or Infinity. public static Power FromMechanicalHorsepower(QuantityValue mechanicalhorsepower) { - decimal value = (decimal) mechanicalhorsepower; + QuantityValue value = (QuantityValue) mechanicalhorsepower; return new Power(value, PowerUnit.MechanicalHorsepower); } @@ -585,7 +586,7 @@ public static Power FromMechanicalHorsepower(QuantityValue mechanicalhorsepower) /// If value is NaN or Infinity. public static Power FromMegabritishThermalUnitsPerHour(QuantityValue megabritishthermalunitsperhour) { - decimal value = (decimal) megabritishthermalunitsperhour; + QuantityValue value = (QuantityValue) megabritishthermalunitsperhour; return new Power(value, PowerUnit.MegabritishThermalUnitPerHour); } @@ -595,7 +596,7 @@ public static Power FromMegabritishThermalUnitsPerHour(QuantityValue megabritish /// If value is NaN or Infinity. public static Power FromMegajoulesPerHour(QuantityValue megajoulesperhour) { - decimal value = (decimal) megajoulesperhour; + QuantityValue value = (QuantityValue) megajoulesperhour; return new Power(value, PowerUnit.MegajoulePerHour); } @@ -605,7 +606,7 @@ public static Power FromMegajoulesPerHour(QuantityValue megajoulesperhour) /// If value is NaN or Infinity. public static Power FromMegawatts(QuantityValue megawatts) { - decimal value = (decimal) megawatts; + QuantityValue value = (QuantityValue) megawatts; return new Power(value, PowerUnit.Megawatt); } @@ -615,7 +616,7 @@ public static Power FromMegawatts(QuantityValue megawatts) /// If value is NaN or Infinity. public static Power FromMetricHorsepower(QuantityValue metrichorsepower) { - decimal value = (decimal) metrichorsepower; + QuantityValue value = (QuantityValue) metrichorsepower; return new Power(value, PowerUnit.MetricHorsepower); } @@ -625,7 +626,7 @@ public static Power FromMetricHorsepower(QuantityValue metrichorsepower) /// If value is NaN or Infinity. public static Power FromMicrowatts(QuantityValue microwatts) { - decimal value = (decimal) microwatts; + QuantityValue value = (QuantityValue) microwatts; return new Power(value, PowerUnit.Microwatt); } @@ -635,7 +636,7 @@ public static Power FromMicrowatts(QuantityValue microwatts) /// If value is NaN or Infinity. public static Power FromMillijoulesPerHour(QuantityValue millijoulesperhour) { - decimal value = (decimal) millijoulesperhour; + QuantityValue value = (QuantityValue) millijoulesperhour; return new Power(value, PowerUnit.MillijoulePerHour); } @@ -645,7 +646,7 @@ public static Power FromMillijoulesPerHour(QuantityValue millijoulesperhour) /// If value is NaN or Infinity. public static Power FromMilliwatts(QuantityValue milliwatts) { - decimal value = (decimal) milliwatts; + QuantityValue value = (QuantityValue) milliwatts; return new Power(value, PowerUnit.Milliwatt); } @@ -655,7 +656,7 @@ public static Power FromMilliwatts(QuantityValue milliwatts) /// If value is NaN or Infinity. public static Power FromNanowatts(QuantityValue nanowatts) { - decimal value = (decimal) nanowatts; + QuantityValue value = (QuantityValue) nanowatts; return new Power(value, PowerUnit.Nanowatt); } @@ -665,7 +666,7 @@ public static Power FromNanowatts(QuantityValue nanowatts) /// If value is NaN or Infinity. public static Power FromPetawatts(QuantityValue petawatts) { - decimal value = (decimal) petawatts; + QuantityValue value = (QuantityValue) petawatts; return new Power(value, PowerUnit.Petawatt); } @@ -675,7 +676,7 @@ public static Power FromPetawatts(QuantityValue petawatts) /// If value is NaN or Infinity. public static Power FromPicowatts(QuantityValue picowatts) { - decimal value = (decimal) picowatts; + QuantityValue value = (QuantityValue) picowatts; return new Power(value, PowerUnit.Picowatt); } @@ -685,7 +686,7 @@ public static Power FromPicowatts(QuantityValue picowatts) /// If value is NaN or Infinity. public static Power FromTerawatts(QuantityValue terawatts) { - decimal value = (decimal) terawatts; + QuantityValue value = (QuantityValue) terawatts; return new Power(value, PowerUnit.Terawatt); } @@ -695,7 +696,7 @@ public static Power FromTerawatts(QuantityValue terawatts) /// If value is NaN or Infinity. public static Power FromWatts(QuantityValue watts) { - decimal value = (decimal) watts; + QuantityValue value = (QuantityValue) watts; return new Power(value, PowerUnit.Watt); } @@ -707,7 +708,7 @@ public static Power FromWatts(QuantityValue watts) /// Power unit value. public static Power From(QuantityValue value, PowerUnit fromUnit) { - return new Power((decimal)value, fromUnit); + return new Power((QuantityValue)value, fromUnit); } #endregion @@ -877,25 +878,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power } /// Get from multiplying value and . - public static Power operator *(decimal left, Power right) + public static Power operator *(QuantityValue left, Power right) { return new Power(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Power operator *(Power left, decimal right) + public static Power operator *(Power left, QuantityValue right) { return new Power(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Power operator /(Power left, decimal right) + public static Power operator /(Power left, QuantityValue right) { return new Power(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Power left, Power right) + public static QuantityValue operator /(Power left, Power right) { return left.Watts / right.Watts; } @@ -928,6 +929,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Power left, Power right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Power left, Power right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -940,7 +954,29 @@ public int CompareTo(object obj) /// public int CompareTo(Power other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Power objPower)) + return false; + return Equals(objPower); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Power other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -983,13 +1019,13 @@ public int CompareTo(Power other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Power other, double tolerance, ComparisonType comparisonType) + public bool Equals(Power other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1000,7 +1036,7 @@ public bool Equals(Power other, double tolerance, ComparisonType comparisonType) /// A hash code for the current Power. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1011,17 +1047,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(PowerUnit unit) + public QuantityValue As(PowerUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1036,12 +1071,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is PowerUnit unitAsPowerUnit)) + if (!(unit is PowerUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerUnit)} is supported.", nameof(unit)); - return As(unitAsPowerUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1073,7 +1108,7 @@ public Power ToUnit(PowerUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Power)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(PowerUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1081,17 +1116,17 @@ public Power ToUnit(PowerUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PowerUnit unitAsPowerUnit)) + if (!(unit is PowerUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPowerUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1118,10 +1153,10 @@ public Power ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private decimal GetValueAs(PowerUnit unit) + private QuantityValue GetValueAs(PowerUnit unit) { var converted = ToUnit(unit); - return (decimal)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs index a13b01eef5..e35dfe4767 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The amount of power in a volume. /// [DataContract] - public partial struct PowerDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct PowerDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -115,9 +115,9 @@ static PowerDensity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public PowerDensity(double value, PowerDensityUnit unit) + public PowerDensity(QuantityValue value, PowerDensityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -129,14 +129,14 @@ public PowerDensity(double value, PowerDensityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public PowerDensity(double value, UnitSystem unitSystem) + public PowerDensity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -177,7 +177,10 @@ public PowerDensity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -200,224 +203,224 @@ public PowerDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); + public QuantityValue DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); + public QuantityValue DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); + public QuantityValue DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); + public QuantityValue DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); + public QuantityValue DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); + public QuantityValue DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); + public QuantityValue DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); + public QuantityValue DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); + public QuantityValue GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); + public QuantityValue GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); + public QuantityValue GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); + public QuantityValue GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); + public QuantityValue KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); + public QuantityValue KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); + public QuantityValue KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); + public QuantityValue KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); + public QuantityValue MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); + public QuantityValue MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); + public QuantityValue MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); + public QuantityValue MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); + public QuantityValue MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); + public QuantityValue MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); + public QuantityValue MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); + public QuantityValue MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); + public QuantityValue MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); + public QuantityValue MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); + public QuantityValue MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); + public QuantityValue MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); + public QuantityValue NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); + public QuantityValue NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); + public QuantityValue NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); + public QuantityValue NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); + public QuantityValue PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); + public QuantityValue PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); + public QuantityValue PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); + public QuantityValue PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); + public QuantityValue TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); + public QuantityValue TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); + public QuantityValue TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); + public QuantityValue TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); + public QuantityValue WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); + public QuantityValue WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); + public QuantityValue WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerLiter => As(PowerDensityUnit.WattPerLiter); + public QuantityValue WattsPerLiter => As(PowerDensityUnit.WattPerLiter); #endregion @@ -602,7 +605,7 @@ public static string GetAbbreviation(PowerDensityUnit unit, IFormatProvider? pro /// If value is NaN or Infinity. public static PowerDensity FromDecawattsPerCubicFoot(QuantityValue decawattspercubicfoot) { - double value = (double) decawattspercubicfoot; + QuantityValue value = (QuantityValue) decawattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); } @@ -612,7 +615,7 @@ public static PowerDensity FromDecawattsPerCubicFoot(QuantityValue decawattsperc /// If value is NaN or Infinity. public static PowerDensity FromDecawattsPerCubicInch(QuantityValue decawattspercubicinch) { - double value = (double) decawattspercubicinch; + QuantityValue value = (QuantityValue) decawattspercubicinch; return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); } @@ -622,7 +625,7 @@ public static PowerDensity FromDecawattsPerCubicInch(QuantityValue decawattsperc /// If value is NaN or Infinity. public static PowerDensity FromDecawattsPerCubicMeter(QuantityValue decawattspercubicmeter) { - double value = (double) decawattspercubicmeter; + QuantityValue value = (QuantityValue) decawattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); } @@ -632,7 +635,7 @@ public static PowerDensity FromDecawattsPerCubicMeter(QuantityValue decawattsper /// If value is NaN or Infinity. public static PowerDensity FromDecawattsPerLiter(QuantityValue decawattsperliter) { - double value = (double) decawattsperliter; + QuantityValue value = (QuantityValue) decawattsperliter; return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); } @@ -642,7 +645,7 @@ public static PowerDensity FromDecawattsPerLiter(QuantityValue decawattsperliter /// If value is NaN or Infinity. public static PowerDensity FromDeciwattsPerCubicFoot(QuantityValue deciwattspercubicfoot) { - double value = (double) deciwattspercubicfoot; + QuantityValue value = (QuantityValue) deciwattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); } @@ -652,7 +655,7 @@ public static PowerDensity FromDeciwattsPerCubicFoot(QuantityValue deciwattsperc /// If value is NaN or Infinity. public static PowerDensity FromDeciwattsPerCubicInch(QuantityValue deciwattspercubicinch) { - double value = (double) deciwattspercubicinch; + QuantityValue value = (QuantityValue) deciwattspercubicinch; return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); } @@ -662,7 +665,7 @@ public static PowerDensity FromDeciwattsPerCubicInch(QuantityValue deciwattsperc /// If value is NaN or Infinity. public static PowerDensity FromDeciwattsPerCubicMeter(QuantityValue deciwattspercubicmeter) { - double value = (double) deciwattspercubicmeter; + QuantityValue value = (QuantityValue) deciwattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); } @@ -672,7 +675,7 @@ public static PowerDensity FromDeciwattsPerCubicMeter(QuantityValue deciwattsper /// If value is NaN or Infinity. public static PowerDensity FromDeciwattsPerLiter(QuantityValue deciwattsperliter) { - double value = (double) deciwattsperliter; + QuantityValue value = (QuantityValue) deciwattsperliter; return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); } @@ -682,7 +685,7 @@ public static PowerDensity FromDeciwattsPerLiter(QuantityValue deciwattsperliter /// If value is NaN or Infinity. public static PowerDensity FromGigawattsPerCubicFoot(QuantityValue gigawattspercubicfoot) { - double value = (double) gigawattspercubicfoot; + QuantityValue value = (QuantityValue) gigawattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); } @@ -692,7 +695,7 @@ public static PowerDensity FromGigawattsPerCubicFoot(QuantityValue gigawattsperc /// If value is NaN or Infinity. public static PowerDensity FromGigawattsPerCubicInch(QuantityValue gigawattspercubicinch) { - double value = (double) gigawattspercubicinch; + QuantityValue value = (QuantityValue) gigawattspercubicinch; return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); } @@ -702,7 +705,7 @@ public static PowerDensity FromGigawattsPerCubicInch(QuantityValue gigawattsperc /// If value is NaN or Infinity. public static PowerDensity FromGigawattsPerCubicMeter(QuantityValue gigawattspercubicmeter) { - double value = (double) gigawattspercubicmeter; + QuantityValue value = (QuantityValue) gigawattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); } @@ -712,7 +715,7 @@ public static PowerDensity FromGigawattsPerCubicMeter(QuantityValue gigawattsper /// If value is NaN or Infinity. public static PowerDensity FromGigawattsPerLiter(QuantityValue gigawattsperliter) { - double value = (double) gigawattsperliter; + QuantityValue value = (QuantityValue) gigawattsperliter; return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); } @@ -722,7 +725,7 @@ public static PowerDensity FromGigawattsPerLiter(QuantityValue gigawattsperliter /// If value is NaN or Infinity. public static PowerDensity FromKilowattsPerCubicFoot(QuantityValue kilowattspercubicfoot) { - double value = (double) kilowattspercubicfoot; + QuantityValue value = (QuantityValue) kilowattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); } @@ -732,7 +735,7 @@ public static PowerDensity FromKilowattsPerCubicFoot(QuantityValue kilowattsperc /// If value is NaN or Infinity. public static PowerDensity FromKilowattsPerCubicInch(QuantityValue kilowattspercubicinch) { - double value = (double) kilowattspercubicinch; + QuantityValue value = (QuantityValue) kilowattspercubicinch; return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); } @@ -742,7 +745,7 @@ public static PowerDensity FromKilowattsPerCubicInch(QuantityValue kilowattsperc /// If value is NaN or Infinity. public static PowerDensity FromKilowattsPerCubicMeter(QuantityValue kilowattspercubicmeter) { - double value = (double) kilowattspercubicmeter; + QuantityValue value = (QuantityValue) kilowattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); } @@ -752,7 +755,7 @@ public static PowerDensity FromKilowattsPerCubicMeter(QuantityValue kilowattsper /// If value is NaN or Infinity. public static PowerDensity FromKilowattsPerLiter(QuantityValue kilowattsperliter) { - double value = (double) kilowattsperliter; + QuantityValue value = (QuantityValue) kilowattsperliter; return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); } @@ -762,7 +765,7 @@ public static PowerDensity FromKilowattsPerLiter(QuantityValue kilowattsperliter /// If value is NaN or Infinity. public static PowerDensity FromMegawattsPerCubicFoot(QuantityValue megawattspercubicfoot) { - double value = (double) megawattspercubicfoot; + QuantityValue value = (QuantityValue) megawattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); } @@ -772,7 +775,7 @@ public static PowerDensity FromMegawattsPerCubicFoot(QuantityValue megawattsperc /// If value is NaN or Infinity. public static PowerDensity FromMegawattsPerCubicInch(QuantityValue megawattspercubicinch) { - double value = (double) megawattspercubicinch; + QuantityValue value = (QuantityValue) megawattspercubicinch; return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); } @@ -782,7 +785,7 @@ public static PowerDensity FromMegawattsPerCubicInch(QuantityValue megawattsperc /// If value is NaN or Infinity. public static PowerDensity FromMegawattsPerCubicMeter(QuantityValue megawattspercubicmeter) { - double value = (double) megawattspercubicmeter; + QuantityValue value = (QuantityValue) megawattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); } @@ -792,7 +795,7 @@ public static PowerDensity FromMegawattsPerCubicMeter(QuantityValue megawattsper /// If value is NaN or Infinity. public static PowerDensity FromMegawattsPerLiter(QuantityValue megawattsperliter) { - double value = (double) megawattsperliter; + QuantityValue value = (QuantityValue) megawattsperliter; return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); } @@ -802,7 +805,7 @@ public static PowerDensity FromMegawattsPerLiter(QuantityValue megawattsperliter /// If value is NaN or Infinity. public static PowerDensity FromMicrowattsPerCubicFoot(QuantityValue microwattspercubicfoot) { - double value = (double) microwattspercubicfoot; + QuantityValue value = (QuantityValue) microwattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); } @@ -812,7 +815,7 @@ public static PowerDensity FromMicrowattsPerCubicFoot(QuantityValue microwattspe /// If value is NaN or Infinity. public static PowerDensity FromMicrowattsPerCubicInch(QuantityValue microwattspercubicinch) { - double value = (double) microwattspercubicinch; + QuantityValue value = (QuantityValue) microwattspercubicinch; return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); } @@ -822,7 +825,7 @@ public static PowerDensity FromMicrowattsPerCubicInch(QuantityValue microwattspe /// If value is NaN or Infinity. public static PowerDensity FromMicrowattsPerCubicMeter(QuantityValue microwattspercubicmeter) { - double value = (double) microwattspercubicmeter; + QuantityValue value = (QuantityValue) microwattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); } @@ -832,7 +835,7 @@ public static PowerDensity FromMicrowattsPerCubicMeter(QuantityValue microwattsp /// If value is NaN or Infinity. public static PowerDensity FromMicrowattsPerLiter(QuantityValue microwattsperliter) { - double value = (double) microwattsperliter; + QuantityValue value = (QuantityValue) microwattsperliter; return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); } @@ -842,7 +845,7 @@ public static PowerDensity FromMicrowattsPerLiter(QuantityValue microwattsperlit /// If value is NaN or Infinity. public static PowerDensity FromMilliwattsPerCubicFoot(QuantityValue milliwattspercubicfoot) { - double value = (double) milliwattspercubicfoot; + QuantityValue value = (QuantityValue) milliwattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); } @@ -852,7 +855,7 @@ public static PowerDensity FromMilliwattsPerCubicFoot(QuantityValue milliwattspe /// If value is NaN or Infinity. public static PowerDensity FromMilliwattsPerCubicInch(QuantityValue milliwattspercubicinch) { - double value = (double) milliwattspercubicinch; + QuantityValue value = (QuantityValue) milliwattspercubicinch; return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); } @@ -862,7 +865,7 @@ public static PowerDensity FromMilliwattsPerCubicInch(QuantityValue milliwattspe /// If value is NaN or Infinity. public static PowerDensity FromMilliwattsPerCubicMeter(QuantityValue milliwattspercubicmeter) { - double value = (double) milliwattspercubicmeter; + QuantityValue value = (QuantityValue) milliwattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); } @@ -872,7 +875,7 @@ public static PowerDensity FromMilliwattsPerCubicMeter(QuantityValue milliwattsp /// If value is NaN or Infinity. public static PowerDensity FromMilliwattsPerLiter(QuantityValue milliwattsperliter) { - double value = (double) milliwattsperliter; + QuantityValue value = (QuantityValue) milliwattsperliter; return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); } @@ -882,7 +885,7 @@ public static PowerDensity FromMilliwattsPerLiter(QuantityValue milliwattsperlit /// If value is NaN or Infinity. public static PowerDensity FromNanowattsPerCubicFoot(QuantityValue nanowattspercubicfoot) { - double value = (double) nanowattspercubicfoot; + QuantityValue value = (QuantityValue) nanowattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); } @@ -892,7 +895,7 @@ public static PowerDensity FromNanowattsPerCubicFoot(QuantityValue nanowattsperc /// If value is NaN or Infinity. public static PowerDensity FromNanowattsPerCubicInch(QuantityValue nanowattspercubicinch) { - double value = (double) nanowattspercubicinch; + QuantityValue value = (QuantityValue) nanowattspercubicinch; return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); } @@ -902,7 +905,7 @@ public static PowerDensity FromNanowattsPerCubicInch(QuantityValue nanowattsperc /// If value is NaN or Infinity. public static PowerDensity FromNanowattsPerCubicMeter(QuantityValue nanowattspercubicmeter) { - double value = (double) nanowattspercubicmeter; + QuantityValue value = (QuantityValue) nanowattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); } @@ -912,7 +915,7 @@ public static PowerDensity FromNanowattsPerCubicMeter(QuantityValue nanowattsper /// If value is NaN or Infinity. public static PowerDensity FromNanowattsPerLiter(QuantityValue nanowattsperliter) { - double value = (double) nanowattsperliter; + QuantityValue value = (QuantityValue) nanowattsperliter; return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); } @@ -922,7 +925,7 @@ public static PowerDensity FromNanowattsPerLiter(QuantityValue nanowattsperliter /// If value is NaN or Infinity. public static PowerDensity FromPicowattsPerCubicFoot(QuantityValue picowattspercubicfoot) { - double value = (double) picowattspercubicfoot; + QuantityValue value = (QuantityValue) picowattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); } @@ -932,7 +935,7 @@ public static PowerDensity FromPicowattsPerCubicFoot(QuantityValue picowattsperc /// If value is NaN or Infinity. public static PowerDensity FromPicowattsPerCubicInch(QuantityValue picowattspercubicinch) { - double value = (double) picowattspercubicinch; + QuantityValue value = (QuantityValue) picowattspercubicinch; return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); } @@ -942,7 +945,7 @@ public static PowerDensity FromPicowattsPerCubicInch(QuantityValue picowattsperc /// If value is NaN or Infinity. public static PowerDensity FromPicowattsPerCubicMeter(QuantityValue picowattspercubicmeter) { - double value = (double) picowattspercubicmeter; + QuantityValue value = (QuantityValue) picowattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); } @@ -952,7 +955,7 @@ public static PowerDensity FromPicowattsPerCubicMeter(QuantityValue picowattsper /// If value is NaN or Infinity. public static PowerDensity FromPicowattsPerLiter(QuantityValue picowattsperliter) { - double value = (double) picowattsperliter; + QuantityValue value = (QuantityValue) picowattsperliter; return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); } @@ -962,7 +965,7 @@ public static PowerDensity FromPicowattsPerLiter(QuantityValue picowattsperliter /// If value is NaN or Infinity. public static PowerDensity FromTerawattsPerCubicFoot(QuantityValue terawattspercubicfoot) { - double value = (double) terawattspercubicfoot; + QuantityValue value = (QuantityValue) terawattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); } @@ -972,7 +975,7 @@ public static PowerDensity FromTerawattsPerCubicFoot(QuantityValue terawattsperc /// If value is NaN or Infinity. public static PowerDensity FromTerawattsPerCubicInch(QuantityValue terawattspercubicinch) { - double value = (double) terawattspercubicinch; + QuantityValue value = (QuantityValue) terawattspercubicinch; return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); } @@ -982,7 +985,7 @@ public static PowerDensity FromTerawattsPerCubicInch(QuantityValue terawattsperc /// If value is NaN or Infinity. public static PowerDensity FromTerawattsPerCubicMeter(QuantityValue terawattspercubicmeter) { - double value = (double) terawattspercubicmeter; + QuantityValue value = (QuantityValue) terawattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); } @@ -992,7 +995,7 @@ public static PowerDensity FromTerawattsPerCubicMeter(QuantityValue terawattsper /// If value is NaN or Infinity. public static PowerDensity FromTerawattsPerLiter(QuantityValue terawattsperliter) { - double value = (double) terawattsperliter; + QuantityValue value = (QuantityValue) terawattsperliter; return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); } @@ -1002,7 +1005,7 @@ public static PowerDensity FromTerawattsPerLiter(QuantityValue terawattsperliter /// If value is NaN or Infinity. public static PowerDensity FromWattsPerCubicFoot(QuantityValue wattspercubicfoot) { - double value = (double) wattspercubicfoot; + QuantityValue value = (QuantityValue) wattspercubicfoot; return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); } @@ -1012,7 +1015,7 @@ public static PowerDensity FromWattsPerCubicFoot(QuantityValue wattspercubicfoot /// If value is NaN or Infinity. public static PowerDensity FromWattsPerCubicInch(QuantityValue wattspercubicinch) { - double value = (double) wattspercubicinch; + QuantityValue value = (QuantityValue) wattspercubicinch; return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); } @@ -1022,7 +1025,7 @@ public static PowerDensity FromWattsPerCubicInch(QuantityValue wattspercubicinch /// If value is NaN or Infinity. public static PowerDensity FromWattsPerCubicMeter(QuantityValue wattspercubicmeter) { - double value = (double) wattspercubicmeter; + QuantityValue value = (QuantityValue) wattspercubicmeter; return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); } @@ -1032,7 +1035,7 @@ public static PowerDensity FromWattsPerCubicMeter(QuantityValue wattspercubicmet /// If value is NaN or Infinity. public static PowerDensity FromWattsPerLiter(QuantityValue wattsperliter) { - double value = (double) wattsperliter; + QuantityValue value = (QuantityValue) wattsperliter; return new PowerDensity(value, PowerDensityUnit.WattPerLiter); } @@ -1044,7 +1047,7 @@ public static PowerDensity FromWattsPerLiter(QuantityValue wattsperliter) /// PowerDensity unit value. public static PowerDensity From(QuantityValue value, PowerDensityUnit fromUnit) { - return new PowerDensity((double)value, fromUnit); + return new PowerDensity((QuantityValue)value, fromUnit); } #endregion @@ -1214,25 +1217,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power } /// Get from multiplying value and . - public static PowerDensity operator *(double left, PowerDensity right) + public static PowerDensity operator *(QuantityValue left, PowerDensity right) { return new PowerDensity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static PowerDensity operator *(PowerDensity left, double right) + public static PowerDensity operator *(PowerDensity left, QuantityValue right) { return new PowerDensity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static PowerDensity operator /(PowerDensity left, double right) + public static PowerDensity operator /(PowerDensity left, QuantityValue right) { return new PowerDensity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(PowerDensity left, PowerDensity right) + public static QuantityValue operator /(PowerDensity left, PowerDensity right) { return left.WattsPerCubicMeter / right.WattsPerCubicMeter; } @@ -1265,6 +1268,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(PowerDensity left, PowerDensity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(PowerDensity left, PowerDensity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1277,7 +1293,29 @@ public int CompareTo(object obj) /// public int CompareTo(PowerDensity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is PowerDensity objPowerDensity)) + return false; + return Equals(objPowerDensity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(PowerDensity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1320,13 +1358,13 @@ public int CompareTo(PowerDensity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PowerDensity other, double tolerance, ComparisonType comparisonType) + public bool Equals(PowerDensity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1337,7 +1375,7 @@ public bool Equals(PowerDensity other, double tolerance, ComparisonType comparis /// A hash code for the current PowerDensity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1348,17 +1386,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(PowerDensityUnit unit) + public QuantityValue As(PowerDensityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1373,12 +1410,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is PowerDensityUnit unitAsPowerDensityUnit)) + if (!(unit is PowerDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerDensityUnit)} is supported.", nameof(unit)); - return As(unitAsPowerDensityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1410,7 +1447,7 @@ public PowerDensity ToUnit(PowerDensityUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (PowerDensity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(PowerDensityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1418,17 +1455,17 @@ public PowerDensity ToUnit(PowerDensityUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PowerDensityUnit unitAsPowerDensityUnit)) + if (!(unit is PowerDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerDensityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPowerDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1455,10 +1492,10 @@ public PowerDensity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(PowerDensityUnit unit) + private QuantityValue GetValueAs(PowerDensityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs index e2297bd8ec..b76f6f4e1f 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The strength of a signal expressed in decibels (dB) relative to one watt. /// [DataContract] - public partial struct PowerRatio : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct PowerRatio : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -73,9 +73,9 @@ static PowerRatio() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public PowerRatio(double value, PowerRatioUnit unit) + public PowerRatio(QuantityValue value, PowerRatioUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -87,14 +87,14 @@ public PowerRatio(double value, PowerRatioUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public PowerRatio(double value, UnitSystem unitSystem) + public PowerRatio(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -135,7 +135,10 @@ public PowerRatio(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -158,14 +161,14 @@ public PowerRatio(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); + public QuantityValue DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); + public QuantityValue DecibelWatts => As(PowerRatioUnit.DecibelWatt); #endregion @@ -224,7 +227,7 @@ public static string GetAbbreviation(PowerRatioUnit unit, IFormatProvider? provi /// If value is NaN or Infinity. public static PowerRatio FromDecibelMilliwatts(QuantityValue decibelmilliwatts) { - double value = (double) decibelmilliwatts; + QuantityValue value = (QuantityValue) decibelmilliwatts; return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); } @@ -234,7 +237,7 @@ public static PowerRatio FromDecibelMilliwatts(QuantityValue decibelmilliwatts) /// If value is NaN or Infinity. public static PowerRatio FromDecibelWatts(QuantityValue decibelwatts) { - double value = (double) decibelwatts; + QuantityValue value = (QuantityValue) decibelwatts; return new PowerRatio(value, PowerRatioUnit.DecibelWatt); } @@ -246,7 +249,7 @@ public static PowerRatio FromDecibelWatts(QuantityValue decibelwatts) /// PowerRatio unit value. public static PowerRatio From(QuantityValue value, PowerRatioUnit fromUnit) { - return new PowerRatio((double)value, fromUnit); + return new PowerRatio((QuantityValue)value, fromUnit); } #endregion @@ -408,7 +411,7 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power { // Logarithmic addition // Formula: 10 * log10(10^(x/10) + 10^(y/10)) - return new PowerRatio(10 * Math.Log10(Math.Pow(10, left.Value/10) + Math.Pow(10, right.GetValueAs(left.Unit)/10)), left.Unit); + return new PowerRatio(10 * Math.Log10(Math.Pow(10, (double)left.Value/10) + Math.Pow(10, (double)right.GetValueAs(left.Unit)/10)), left.Unit); } /// Get from logarithmic subtraction of two . @@ -416,11 +419,11 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power { // Logarithmic subtraction // Formula: 10 * log10(10^(x/10) - 10^(y/10)) - return new PowerRatio(10 * Math.Log10(Math.Pow(10, left.Value/10) - Math.Pow(10, right.GetValueAs(left.Unit)/10)), left.Unit); + return new PowerRatio(10 * Math.Log10(Math.Pow(10, (double)left.Value/10) - Math.Pow(10, (double)right.GetValueAs(left.Unit)/10)), left.Unit); } /// Get from logarithmic multiplication of value and . - public static PowerRatio operator *(double left, PowerRatio right) + public static PowerRatio operator *(QuantityValue left, PowerRatio right) { // Logarithmic multiplication = addition return new PowerRatio(left + right.Value, right.Unit); @@ -430,14 +433,14 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power public static PowerRatio operator *(PowerRatio left, double right) { // Logarithmic multiplication = addition - return new PowerRatio(left.Value + (double)right, left.Unit); + return new PowerRatio(left.Value + (QuantityValue)right, left.Unit); } /// Get from logarithmic division of by value. public static PowerRatio operator /(PowerRatio left, double right) { // Logarithmic division = subtraction - return new PowerRatio(left.Value - (double)right, left.Unit); + return new PowerRatio(left.Value - (QuantityValue)right, left.Unit); } /// Get ratio value from logarithmic division of by . @@ -475,6 +478,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(PowerRatio left, PowerRatio right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(PowerRatio left, PowerRatio right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -487,7 +503,29 @@ public int CompareTo(object obj) /// public int CompareTo(PowerRatio other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is PowerRatio objPowerRatio)) + return false; + return Equals(objPowerRatio); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(PowerRatio other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -530,13 +568,13 @@ public int CompareTo(PowerRatio other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PowerRatio other, double tolerance, ComparisonType comparisonType) + public bool Equals(PowerRatio other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -547,7 +585,7 @@ public bool Equals(PowerRatio other, double tolerance, ComparisonType comparison /// A hash code for the current PowerRatio. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -558,17 +596,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(PowerRatioUnit unit) + public QuantityValue As(PowerRatioUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -583,12 +620,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is PowerRatioUnit unitAsPowerRatioUnit)) + if (!(unit is PowerRatioUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerRatioUnit)} is supported.", nameof(unit)); - return As(unitAsPowerRatioUnit); + return (QuantityValue)As(typedUnit); } /// @@ -620,7 +657,7 @@ public PowerRatio ToUnit(PowerRatioUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (PowerRatio)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(PowerRatioUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -628,17 +665,17 @@ public PowerRatio ToUnit(PowerRatioUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PowerRatioUnit unitAsPowerRatioUnit)) + if (!(unit is PowerRatioUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerRatioUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPowerRatioUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -665,10 +702,10 @@ public PowerRatio ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(PowerRatioUnit unit) + private QuantityValue GetValueAs(PowerRatioUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index 12ab6f58c5..cd4dcfda52 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa). /// [DataContract] - public partial struct Pressure : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Pressure : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -118,9 +118,9 @@ static Pressure() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Pressure(double value, PressureUnit unit) + public Pressure(QuantityValue value, PressureUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -132,14 +132,14 @@ public Pressure(double value, PressureUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Pressure(double value, UnitSystem unitSystem) + public Pressure(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -180,7 +180,10 @@ public Pressure(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -203,239 +206,239 @@ public Pressure(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Atmospheres => As(PressureUnit.Atmosphere); + public QuantityValue Atmospheres => As(PressureUnit.Atmosphere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Bars => As(PressureUnit.Bar); + public QuantityValue Bars => As(PressureUnit.Bar); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Centibars => As(PressureUnit.Centibar); + public QuantityValue Centibars => As(PressureUnit.Centibar); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decapascals => As(PressureUnit.Decapascal); + public QuantityValue Decapascals => As(PressureUnit.Decapascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decibars => As(PressureUnit.Decibar); + public QuantityValue Decibars => As(PressureUnit.Decibar); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); + public QuantityValue DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FeetOfElevation => As(PressureUnit.FootOfElevation); + public QuantityValue FeetOfElevation => As(PressureUnit.FootOfElevation); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FeetOfHead => As(PressureUnit.FootOfHead); + public QuantityValue FeetOfHead => As(PressureUnit.FootOfHead); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Gigapascals => As(PressureUnit.Gigapascal); + public QuantityValue Gigapascals => As(PressureUnit.Gigapascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Hectopascals => As(PressureUnit.Hectopascal); + public QuantityValue Hectopascals => As(PressureUnit.Hectopascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InchesOfMercury => As(PressureUnit.InchOfMercury); + public QuantityValue InchesOfMercury => As(PressureUnit.InchOfMercury); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InchesOfWaterColumn => As(PressureUnit.InchOfWaterColumn); + public QuantityValue InchesOfWaterColumn => As(PressureUnit.InchOfWaterColumn); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilobars => As(PressureUnit.Kilobar); + public QuantityValue Kilobars => As(PressureUnit.Kilobar); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); + public QuantityValue KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); + public QuantityValue KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); + public QuantityValue KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); + public QuantityValue KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); + public QuantityValue KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); + public QuantityValue KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kilopascals => As(PressureUnit.Kilopascal); + public QuantityValue Kilopascals => As(PressureUnit.Kilopascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); + public QuantityValue KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); + public QuantityValue KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerSquareMil => As(PressureUnit.KilopoundForcePerSquareMil); + public QuantityValue KilopoundsForcePerSquareMil => As(PressureUnit.KilopoundForcePerSquareMil); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megabars => As(PressureUnit.Megabar); + public QuantityValue Megabars => As(PressureUnit.Megabar); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonsPerSquareMeter => As(PressureUnit.MeganewtonPerSquareMeter); + public QuantityValue MeganewtonsPerSquareMeter => As(PressureUnit.MeganewtonPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megapascals => As(PressureUnit.Megapascal); + public QuantityValue Megapascals => As(PressureUnit.Megapascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetersOfElevation => As(PressureUnit.MeterOfElevation); + public QuantityValue MetersOfElevation => As(PressureUnit.MeterOfElevation); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetersOfHead => As(PressureUnit.MeterOfHead); + public QuantityValue MetersOfHead => As(PressureUnit.MeterOfHead); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microbars => As(PressureUnit.Microbar); + public QuantityValue Microbars => As(PressureUnit.Microbar); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Micropascals => As(PressureUnit.Micropascal); + public QuantityValue Micropascals => As(PressureUnit.Micropascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millibars => As(PressureUnit.Millibar); + public QuantityValue Millibars => As(PressureUnit.Millibar); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); + public QuantityValue MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimeterOfWaterColumn => As(PressureUnit.MillimeterOfWaterColumn); + public QuantityValue MillimeterOfWaterColumn => As(PressureUnit.MillimeterOfWaterColumn); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Millipascals => As(PressureUnit.Millipascal); + public QuantityValue Millipascals => As(PressureUnit.Millipascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); + public QuantityValue NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); + public QuantityValue NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); + public QuantityValue NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Pascals => As(PressureUnit.Pascal); + public QuantityValue Pascals => As(PressureUnit.Pascal); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); + public QuantityValue PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); + public QuantityValue PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerSquareMil => As(PressureUnit.PoundForcePerSquareMil); + public QuantityValue PoundsForcePerSquareMil => As(PressureUnit.PoundForcePerSquareMil); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); + public QuantityValue PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); + public QuantityValue TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); + public QuantityValue TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); + public QuantityValue TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); + public QuantityValue TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Torrs => As(PressureUnit.Torr); + public QuantityValue Torrs => As(PressureUnit.Torr); #endregion @@ -454,7 +457,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) 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.FootOfElevation, quantity => new Pressure((1.0 - Math.Pow((double)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)); @@ -474,7 +477,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) 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.MeterOfElevation, quantity => new Pressure((1.0 - Math.Pow((double)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)); @@ -505,7 +508,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) 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.FootOfElevation, PressureUnit.Pascal, quantity => new Pressure(Math.Pow(1.0 - ((double)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)); @@ -525,7 +528,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) 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.MeterOfElevation, PressureUnit.Pascal, quantity => new Pressure(Math.Pow(1.0 - ((double)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)); @@ -660,7 +663,7 @@ public static string GetAbbreviation(PressureUnit unit, IFormatProvider? provide /// If value is NaN or Infinity. public static Pressure FromAtmospheres(QuantityValue atmospheres) { - double value = (double) atmospheres; + QuantityValue value = (QuantityValue) atmospheres; return new Pressure(value, PressureUnit.Atmosphere); } @@ -670,7 +673,7 @@ public static Pressure FromAtmospheres(QuantityValue atmospheres) /// If value is NaN or Infinity. public static Pressure FromBars(QuantityValue bars) { - double value = (double) bars; + QuantityValue value = (QuantityValue) bars; return new Pressure(value, PressureUnit.Bar); } @@ -680,7 +683,7 @@ public static Pressure FromBars(QuantityValue bars) /// If value is NaN or Infinity. public static Pressure FromCentibars(QuantityValue centibars) { - double value = (double) centibars; + QuantityValue value = (QuantityValue) centibars; return new Pressure(value, PressureUnit.Centibar); } @@ -690,7 +693,7 @@ public static Pressure FromCentibars(QuantityValue centibars) /// If value is NaN or Infinity. public static Pressure FromDecapascals(QuantityValue decapascals) { - double value = (double) decapascals; + QuantityValue value = (QuantityValue) decapascals; return new Pressure(value, PressureUnit.Decapascal); } @@ -700,7 +703,7 @@ public static Pressure FromDecapascals(QuantityValue decapascals) /// If value is NaN or Infinity. public static Pressure FromDecibars(QuantityValue decibars) { - double value = (double) decibars; + QuantityValue value = (QuantityValue) decibars; return new Pressure(value, PressureUnit.Decibar); } @@ -710,7 +713,7 @@ public static Pressure FromDecibars(QuantityValue decibars) /// If value is NaN or Infinity. public static Pressure FromDynesPerSquareCentimeter(QuantityValue dynespersquarecentimeter) { - double value = (double) dynespersquarecentimeter; + QuantityValue value = (QuantityValue) dynespersquarecentimeter; return new Pressure(value, PressureUnit.DynePerSquareCentimeter); } @@ -720,7 +723,7 @@ public static Pressure FromDynesPerSquareCentimeter(QuantityValue dynespersquare /// If value is NaN or Infinity. public static Pressure FromFeetOfElevation(QuantityValue feetofelevation) { - double value = (double) feetofelevation; + QuantityValue value = (QuantityValue) feetofelevation; return new Pressure(value, PressureUnit.FootOfElevation); } @@ -730,7 +733,7 @@ public static Pressure FromFeetOfElevation(QuantityValue feetofelevation) /// If value is NaN or Infinity. public static Pressure FromFeetOfHead(QuantityValue feetofhead) { - double value = (double) feetofhead; + QuantityValue value = (QuantityValue) feetofhead; return new Pressure(value, PressureUnit.FootOfHead); } @@ -740,7 +743,7 @@ public static Pressure FromFeetOfHead(QuantityValue feetofhead) /// If value is NaN or Infinity. public static Pressure FromGigapascals(QuantityValue gigapascals) { - double value = (double) gigapascals; + QuantityValue value = (QuantityValue) gigapascals; return new Pressure(value, PressureUnit.Gigapascal); } @@ -750,7 +753,7 @@ public static Pressure FromGigapascals(QuantityValue gigapascals) /// If value is NaN or Infinity. public static Pressure FromHectopascals(QuantityValue hectopascals) { - double value = (double) hectopascals; + QuantityValue value = (QuantityValue) hectopascals; return new Pressure(value, PressureUnit.Hectopascal); } @@ -760,7 +763,7 @@ public static Pressure FromHectopascals(QuantityValue hectopascals) /// If value is NaN or Infinity. public static Pressure FromInchesOfMercury(QuantityValue inchesofmercury) { - double value = (double) inchesofmercury; + QuantityValue value = (QuantityValue) inchesofmercury; return new Pressure(value, PressureUnit.InchOfMercury); } @@ -770,7 +773,7 @@ public static Pressure FromInchesOfMercury(QuantityValue inchesofmercury) /// If value is NaN or Infinity. public static Pressure FromInchesOfWaterColumn(QuantityValue inchesofwatercolumn) { - double value = (double) inchesofwatercolumn; + QuantityValue value = (QuantityValue) inchesofwatercolumn; return new Pressure(value, PressureUnit.InchOfWaterColumn); } @@ -780,7 +783,7 @@ public static Pressure FromInchesOfWaterColumn(QuantityValue inchesofwatercolumn /// If value is NaN or Infinity. public static Pressure FromKilobars(QuantityValue kilobars) { - double value = (double) kilobars; + QuantityValue value = (QuantityValue) kilobars; return new Pressure(value, PressureUnit.Kilobar); } @@ -790,7 +793,7 @@ public static Pressure FromKilobars(QuantityValue kilobars) /// If value is NaN or Infinity. public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue kilogramsforcepersquarecentimeter) { - double value = (double) kilogramsforcepersquarecentimeter; + QuantityValue value = (QuantityValue) kilogramsforcepersquarecentimeter; return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); } @@ -800,7 +803,7 @@ public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue kilog /// If value is NaN or Infinity. public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue kilogramsforcepersquaremeter) { - double value = (double) kilogramsforcepersquaremeter; + QuantityValue value = (QuantityValue) kilogramsforcepersquaremeter; return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); } @@ -810,7 +813,7 @@ public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue kilogramsf /// If value is NaN or Infinity. public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue kilogramsforcepersquaremillimeter) { - double value = (double) kilogramsforcepersquaremillimeter; + QuantityValue value = (QuantityValue) kilogramsforcepersquaremillimeter; return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); } @@ -820,7 +823,7 @@ public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue kilog /// If value is NaN or Infinity. public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue kilonewtonspersquarecentimeter) { - double value = (double) kilonewtonspersquarecentimeter; + QuantityValue value = (QuantityValue) kilonewtonspersquarecentimeter; return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); } @@ -830,7 +833,7 @@ public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue kilonewt /// If value is NaN or Infinity. public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue kilonewtonspersquaremeter) { - double value = (double) kilonewtonspersquaremeter; + QuantityValue value = (QuantityValue) kilonewtonspersquaremeter; return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); } @@ -840,7 +843,7 @@ public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue kilonewtonspe /// If value is NaN or Infinity. public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue kilonewtonspersquaremillimeter) { - double value = (double) kilonewtonspersquaremillimeter; + QuantityValue value = (QuantityValue) kilonewtonspersquaremillimeter; return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); } @@ -850,7 +853,7 @@ public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue kilonewt /// If value is NaN or Infinity. public static Pressure FromKilopascals(QuantityValue kilopascals) { - double value = (double) kilopascals; + QuantityValue value = (QuantityValue) kilopascals; return new Pressure(value, PressureUnit.Kilopascal); } @@ -860,7 +863,7 @@ public static Pressure FromKilopascals(QuantityValue kilopascals) /// If value is NaN or Infinity. public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue kilopoundsforcepersquarefoot) { - double value = (double) kilopoundsforcepersquarefoot; + QuantityValue value = (QuantityValue) kilopoundsforcepersquarefoot; return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); } @@ -870,7 +873,7 @@ public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue kilopounds /// If value is NaN or Infinity. public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue kilopoundsforcepersquareinch) { - double value = (double) kilopoundsforcepersquareinch; + QuantityValue value = (QuantityValue) kilopoundsforcepersquareinch; return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); } @@ -880,7 +883,7 @@ public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue kilopounds /// If value is NaN or Infinity. public static Pressure FromKilopoundsForcePerSquareMil(QuantityValue kilopoundsforcepersquaremil) { - double value = (double) kilopoundsforcepersquaremil; + QuantityValue value = (QuantityValue) kilopoundsforcepersquaremil; return new Pressure(value, PressureUnit.KilopoundForcePerSquareMil); } @@ -890,7 +893,7 @@ public static Pressure FromKilopoundsForcePerSquareMil(QuantityValue kilopoundsf /// If value is NaN or Infinity. public static Pressure FromMegabars(QuantityValue megabars) { - double value = (double) megabars; + QuantityValue value = (QuantityValue) megabars; return new Pressure(value, PressureUnit.Megabar); } @@ -900,7 +903,7 @@ public static Pressure FromMegabars(QuantityValue megabars) /// If value is NaN or Infinity. public static Pressure FromMeganewtonsPerSquareMeter(QuantityValue meganewtonspersquaremeter) { - double value = (double) meganewtonspersquaremeter; + QuantityValue value = (QuantityValue) meganewtonspersquaremeter; return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); } @@ -910,7 +913,7 @@ public static Pressure FromMeganewtonsPerSquareMeter(QuantityValue meganewtonspe /// If value is NaN or Infinity. public static Pressure FromMegapascals(QuantityValue megapascals) { - double value = (double) megapascals; + QuantityValue value = (QuantityValue) megapascals; return new Pressure(value, PressureUnit.Megapascal); } @@ -920,7 +923,7 @@ public static Pressure FromMegapascals(QuantityValue megapascals) /// If value is NaN or Infinity. public static Pressure FromMetersOfElevation(QuantityValue metersofelevation) { - double value = (double) metersofelevation; + QuantityValue value = (QuantityValue) metersofelevation; return new Pressure(value, PressureUnit.MeterOfElevation); } @@ -930,7 +933,7 @@ public static Pressure FromMetersOfElevation(QuantityValue metersofelevation) /// If value is NaN or Infinity. public static Pressure FromMetersOfHead(QuantityValue metersofhead) { - double value = (double) metersofhead; + QuantityValue value = (QuantityValue) metersofhead; return new Pressure(value, PressureUnit.MeterOfHead); } @@ -940,7 +943,7 @@ public static Pressure FromMetersOfHead(QuantityValue metersofhead) /// If value is NaN or Infinity. public static Pressure FromMicrobars(QuantityValue microbars) { - double value = (double) microbars; + QuantityValue value = (QuantityValue) microbars; return new Pressure(value, PressureUnit.Microbar); } @@ -950,7 +953,7 @@ public static Pressure FromMicrobars(QuantityValue microbars) /// If value is NaN or Infinity. public static Pressure FromMicropascals(QuantityValue micropascals) { - double value = (double) micropascals; + QuantityValue value = (QuantityValue) micropascals; return new Pressure(value, PressureUnit.Micropascal); } @@ -960,7 +963,7 @@ public static Pressure FromMicropascals(QuantityValue micropascals) /// If value is NaN or Infinity. public static Pressure FromMillibars(QuantityValue millibars) { - double value = (double) millibars; + QuantityValue value = (QuantityValue) millibars; return new Pressure(value, PressureUnit.Millibar); } @@ -970,7 +973,7 @@ public static Pressure FromMillibars(QuantityValue millibars) /// If value is NaN or Infinity. public static Pressure FromMillimetersOfMercury(QuantityValue millimetersofmercury) { - double value = (double) millimetersofmercury; + QuantityValue value = (QuantityValue) millimetersofmercury; return new Pressure(value, PressureUnit.MillimeterOfMercury); } @@ -980,7 +983,7 @@ public static Pressure FromMillimetersOfMercury(QuantityValue millimetersofmercu /// If value is NaN or Infinity. public static Pressure FromMillimeterOfWaterColumn(QuantityValue millimeterofwatercolumn) { - double value = (double) millimeterofwatercolumn; + QuantityValue value = (QuantityValue) millimeterofwatercolumn; return new Pressure(value, PressureUnit.MillimeterOfWaterColumn); } @@ -990,7 +993,7 @@ public static Pressure FromMillimeterOfWaterColumn(QuantityValue millimeterofwat /// If value is NaN or Infinity. public static Pressure FromMillipascals(QuantityValue millipascals) { - double value = (double) millipascals; + QuantityValue value = (QuantityValue) millipascals; return new Pressure(value, PressureUnit.Millipascal); } @@ -1000,7 +1003,7 @@ public static Pressure FromMillipascals(QuantityValue millipascals) /// If value is NaN or Infinity. public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue newtonspersquarecentimeter) { - double value = (double) newtonspersquarecentimeter; + QuantityValue value = (QuantityValue) newtonspersquarecentimeter; return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); } @@ -1010,7 +1013,7 @@ public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue newtonspersq /// If value is NaN or Infinity. public static Pressure FromNewtonsPerSquareMeter(QuantityValue newtonspersquaremeter) { - double value = (double) newtonspersquaremeter; + QuantityValue value = (QuantityValue) newtonspersquaremeter; return new Pressure(value, PressureUnit.NewtonPerSquareMeter); } @@ -1020,7 +1023,7 @@ public static Pressure FromNewtonsPerSquareMeter(QuantityValue newtonspersquarem /// If value is NaN or Infinity. public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue newtonspersquaremillimeter) { - double value = (double) newtonspersquaremillimeter; + QuantityValue value = (QuantityValue) newtonspersquaremillimeter; return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); } @@ -1030,7 +1033,7 @@ public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue newtonspersq /// If value is NaN or Infinity. public static Pressure FromPascals(QuantityValue pascals) { - double value = (double) pascals; + QuantityValue value = (QuantityValue) pascals; return new Pressure(value, PressureUnit.Pascal); } @@ -1040,7 +1043,7 @@ public static Pressure FromPascals(QuantityValue pascals) /// If value is NaN or Infinity. public static Pressure FromPoundsForcePerSquareFoot(QuantityValue poundsforcepersquarefoot) { - double value = (double) poundsforcepersquarefoot; + QuantityValue value = (QuantityValue) poundsforcepersquarefoot; return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); } @@ -1050,7 +1053,7 @@ public static Pressure FromPoundsForcePerSquareFoot(QuantityValue poundsforceper /// If value is NaN or Infinity. public static Pressure FromPoundsForcePerSquareInch(QuantityValue poundsforcepersquareinch) { - double value = (double) poundsforcepersquareinch; + QuantityValue value = (QuantityValue) poundsforcepersquareinch; return new Pressure(value, PressureUnit.PoundForcePerSquareInch); } @@ -1060,7 +1063,7 @@ public static Pressure FromPoundsForcePerSquareInch(QuantityValue poundsforceper /// If value is NaN or Infinity. public static Pressure FromPoundsForcePerSquareMil(QuantityValue poundsforcepersquaremil) { - double value = (double) poundsforcepersquaremil; + QuantityValue value = (QuantityValue) poundsforcepersquaremil; return new Pressure(value, PressureUnit.PoundForcePerSquareMil); } @@ -1070,7 +1073,7 @@ public static Pressure FromPoundsForcePerSquareMil(QuantityValue poundsforcepers /// If value is NaN or Infinity. public static Pressure FromPoundsPerInchSecondSquared(QuantityValue poundsperinchsecondsquared) { - double value = (double) poundsperinchsecondsquared; + QuantityValue value = (QuantityValue) poundsperinchsecondsquared; return new Pressure(value, PressureUnit.PoundPerInchSecondSquared); } @@ -1080,7 +1083,7 @@ public static Pressure FromPoundsPerInchSecondSquared(QuantityValue poundsperinc /// If value is NaN or Infinity. public static Pressure FromTechnicalAtmospheres(QuantityValue technicalatmospheres) { - double value = (double) technicalatmospheres; + QuantityValue value = (QuantityValue) technicalatmospheres; return new Pressure(value, PressureUnit.TechnicalAtmosphere); } @@ -1090,7 +1093,7 @@ public static Pressure FromTechnicalAtmospheres(QuantityValue technicalatmospher /// If value is NaN or Infinity. public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue tonnesforcepersquarecentimeter) { - double value = (double) tonnesforcepersquarecentimeter; + QuantityValue value = (QuantityValue) tonnesforcepersquarecentimeter; return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); } @@ -1100,7 +1103,7 @@ public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue tonnesfo /// If value is NaN or Infinity. public static Pressure FromTonnesForcePerSquareMeter(QuantityValue tonnesforcepersquaremeter) { - double value = (double) tonnesforcepersquaremeter; + QuantityValue value = (QuantityValue) tonnesforcepersquaremeter; return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); } @@ -1110,7 +1113,7 @@ public static Pressure FromTonnesForcePerSquareMeter(QuantityValue tonnesforcepe /// If value is NaN or Infinity. public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue tonnesforcepersquaremillimeter) { - double value = (double) tonnesforcepersquaremillimeter; + QuantityValue value = (QuantityValue) tonnesforcepersquaremillimeter; return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); } @@ -1120,7 +1123,7 @@ public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue tonnesfo /// If value is NaN or Infinity. public static Pressure FromTorrs(QuantityValue torrs) { - double value = (double) torrs; + QuantityValue value = (QuantityValue) torrs; return new Pressure(value, PressureUnit.Torr); } @@ -1132,7 +1135,7 @@ public static Pressure FromTorrs(QuantityValue torrs) /// Pressure unit value. public static Pressure From(QuantityValue value, PressureUnit fromUnit) { - return new Pressure((double)value, fromUnit); + return new Pressure((QuantityValue)value, fromUnit); } #endregion @@ -1302,25 +1305,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Press } /// Get from multiplying value and . - public static Pressure operator *(double left, Pressure right) + public static Pressure operator *(QuantityValue left, Pressure right) { return new Pressure(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Pressure operator *(Pressure left, double right) + public static Pressure operator *(Pressure left, QuantityValue right) { return new Pressure(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Pressure operator /(Pressure left, double right) + public static Pressure operator /(Pressure left, QuantityValue right) { return new Pressure(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Pressure left, Pressure right) + public static QuantityValue operator /(Pressure left, Pressure right) { return left.Pascals / right.Pascals; } @@ -1353,6 +1356,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Press return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Pressure left, Pressure right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Pressure left, Pressure right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1365,7 +1381,29 @@ public int CompareTo(object obj) /// public int CompareTo(Pressure other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Pressure objPressure)) + return false; + return Equals(objPressure); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Pressure other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1408,13 +1446,13 @@ public int CompareTo(Pressure other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Pressure other, double tolerance, ComparisonType comparisonType) + public bool Equals(Pressure other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1425,7 +1463,7 @@ public bool Equals(Pressure other, double tolerance, ComparisonType comparisonTy /// A hash code for the current Pressure. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1436,17 +1474,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(PressureUnit unit) + public QuantityValue As(PressureUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1461,12 +1498,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is PressureUnit unitAsPressureUnit)) + if (!(unit is PressureUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureUnit)} is supported.", nameof(unit)); - return As(unitAsPressureUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1498,7 +1535,7 @@ public Pressure ToUnit(PressureUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Pressure)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(PressureUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1506,17 +1543,17 @@ public Pressure ToUnit(PressureUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PressureUnit unitAsPressureUnit)) + if (!(unit is PressureUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPressureUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1543,10 +1580,10 @@ public Pressure ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(PressureUnit unit) + private QuantityValue GetValueAs(PressureUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs index 7ee7d7f344..06d14aeaa6 100644 --- a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time). /// [DataContract] - public partial struct PressureChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct PressureChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -85,9 +85,9 @@ static PressureChangeRate() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public PressureChangeRate(double value, PressureChangeRateUnit unit) + public PressureChangeRate(QuantityValue value, PressureChangeRateUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -99,14 +99,14 @@ public PressureChangeRate(double value, PressureChangeRateUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public PressureChangeRate(double value, UnitSystem unitSystem) + public PressureChangeRate(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -147,7 +147,10 @@ public PressureChangeRate(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -170,74 +173,74 @@ public PressureChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); + public QuantityValue AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopascalsPerMinute => As(PressureChangeRateUnit.KilopascalPerMinute); + public QuantityValue KilopascalsPerMinute => As(PressureChangeRateUnit.KilopascalPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); + public QuantityValue KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); + public QuantityValue KilopoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); + public QuantityValue KilopoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapascalsPerMinute => As(PressureChangeRateUnit.MegapascalPerMinute); + public QuantityValue MegapascalsPerMinute => As(PressureChangeRateUnit.MegapascalPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); + public QuantityValue MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); + public QuantityValue MegapoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); + public QuantityValue MegapoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimetersOfMercuryPerSecond => As(PressureChangeRateUnit.MillimeterOfMercuryPerSecond); + public QuantityValue MillimetersOfMercuryPerSecond => As(PressureChangeRateUnit.MillimeterOfMercuryPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PascalsPerMinute => As(PressureChangeRateUnit.PascalPerMinute); + public QuantityValue PascalsPerMinute => As(PressureChangeRateUnit.PascalPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); + public QuantityValue PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); + public QuantityValue PoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); + public QuantityValue PoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); #endregion @@ -346,7 +349,7 @@ public static string GetAbbreviation(PressureChangeRateUnit unit, IFormatProvide /// If value is NaN or Infinity. public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue atmospherespersecond) { - double value = (double) atmospherespersecond; + QuantityValue value = (QuantityValue) atmospherespersecond; return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); } @@ -356,7 +359,7 @@ public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue atmosphe /// If value is NaN or Infinity. public static PressureChangeRate FromKilopascalsPerMinute(QuantityValue kilopascalsperminute) { - double value = (double) kilopascalsperminute; + QuantityValue value = (QuantityValue) kilopascalsperminute; return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerMinute); } @@ -366,7 +369,7 @@ public static PressureChangeRate FromKilopascalsPerMinute(QuantityValue kilopasc /// If value is NaN or Infinity. public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue kilopascalspersecond) { - double value = (double) kilopascalspersecond; + QuantityValue value = (QuantityValue) kilopascalspersecond; return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); } @@ -376,7 +379,7 @@ public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue kilopasc /// If value is NaN or Infinity. public static PressureChangeRate FromKilopoundsForcePerSquareInchPerMinute(QuantityValue kilopoundsforcepersquareinchperminute) { - double value = (double) kilopoundsforcepersquareinchperminute; + QuantityValue value = (QuantityValue) kilopoundsforcepersquareinchperminute; return new PressureChangeRate(value, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); } @@ -386,7 +389,7 @@ public static PressureChangeRate FromKilopoundsForcePerSquareInchPerMinute(Quant /// If value is NaN or Infinity. public static PressureChangeRate FromKilopoundsForcePerSquareInchPerSecond(QuantityValue kilopoundsforcepersquareinchpersecond) { - double value = (double) kilopoundsforcepersquareinchpersecond; + QuantityValue value = (QuantityValue) kilopoundsforcepersquareinchpersecond; return new PressureChangeRate(value, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); } @@ -396,7 +399,7 @@ public static PressureChangeRate FromKilopoundsForcePerSquareInchPerSecond(Quant /// If value is NaN or Infinity. public static PressureChangeRate FromMegapascalsPerMinute(QuantityValue megapascalsperminute) { - double value = (double) megapascalsperminute; + QuantityValue value = (QuantityValue) megapascalsperminute; return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerMinute); } @@ -406,7 +409,7 @@ public static PressureChangeRate FromMegapascalsPerMinute(QuantityValue megapasc /// If value is NaN or Infinity. public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue megapascalspersecond) { - double value = (double) megapascalspersecond; + QuantityValue value = (QuantityValue) megapascalspersecond; return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); } @@ -416,7 +419,7 @@ public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue megapasc /// If value is NaN or Infinity. public static PressureChangeRate FromMegapoundsForcePerSquareInchPerMinute(QuantityValue megapoundsforcepersquareinchperminute) { - double value = (double) megapoundsforcepersquareinchperminute; + QuantityValue value = (QuantityValue) megapoundsforcepersquareinchperminute; return new PressureChangeRate(value, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); } @@ -426,7 +429,7 @@ public static PressureChangeRate FromMegapoundsForcePerSquareInchPerMinute(Quant /// If value is NaN or Infinity. public static PressureChangeRate FromMegapoundsForcePerSquareInchPerSecond(QuantityValue megapoundsforcepersquareinchpersecond) { - double value = (double) megapoundsforcepersquareinchpersecond; + QuantityValue value = (QuantityValue) megapoundsforcepersquareinchpersecond; return new PressureChangeRate(value, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); } @@ -436,7 +439,7 @@ public static PressureChangeRate FromMegapoundsForcePerSquareInchPerSecond(Quant /// If value is NaN or Infinity. public static PressureChangeRate FromMillimetersOfMercuryPerSecond(QuantityValue millimetersofmercurypersecond) { - double value = (double) millimetersofmercurypersecond; + QuantityValue value = (QuantityValue) millimetersofmercurypersecond; return new PressureChangeRate(value, PressureChangeRateUnit.MillimeterOfMercuryPerSecond); } @@ -446,7 +449,7 @@ public static PressureChangeRate FromMillimetersOfMercuryPerSecond(QuantityValue /// If value is NaN or Infinity. public static PressureChangeRate FromPascalsPerMinute(QuantityValue pascalsperminute) { - double value = (double) pascalsperminute; + QuantityValue value = (QuantityValue) pascalsperminute; return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerMinute); } @@ -456,7 +459,7 @@ public static PressureChangeRate FromPascalsPerMinute(QuantityValue pascalspermi /// If value is NaN or Infinity. public static PressureChangeRate FromPascalsPerSecond(QuantityValue pascalspersecond) { - double value = (double) pascalspersecond; + QuantityValue value = (QuantityValue) pascalspersecond; return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerSecond); } @@ -466,7 +469,7 @@ public static PressureChangeRate FromPascalsPerSecond(QuantityValue pascalsperse /// If value is NaN or Infinity. public static PressureChangeRate FromPoundsForcePerSquareInchPerMinute(QuantityValue poundsforcepersquareinchperminute) { - double value = (double) poundsforcepersquareinchperminute; + QuantityValue value = (QuantityValue) poundsforcepersquareinchperminute; return new PressureChangeRate(value, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); } @@ -476,7 +479,7 @@ public static PressureChangeRate FromPoundsForcePerSquareInchPerMinute(QuantityV /// If value is NaN or Infinity. public static PressureChangeRate FromPoundsForcePerSquareInchPerSecond(QuantityValue poundsforcepersquareinchpersecond) { - double value = (double) poundsforcepersquareinchpersecond; + QuantityValue value = (QuantityValue) poundsforcepersquareinchpersecond; return new PressureChangeRate(value, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); } @@ -488,7 +491,7 @@ public static PressureChangeRate FromPoundsForcePerSquareInchPerSecond(QuantityV /// PressureChangeRate unit value. public static PressureChangeRate From(QuantityValue value, PressureChangeRateUnit fromUnit) { - return new PressureChangeRate((double)value, fromUnit); + return new PressureChangeRate((QuantityValue)value, fromUnit); } #endregion @@ -658,25 +661,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Press } /// Get from multiplying value and . - public static PressureChangeRate operator *(double left, PressureChangeRate right) + public static PressureChangeRate operator *(QuantityValue left, PressureChangeRate right) { return new PressureChangeRate(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static PressureChangeRate operator *(PressureChangeRate left, double right) + public static PressureChangeRate operator *(PressureChangeRate left, QuantityValue right) { return new PressureChangeRate(left.Value * right, left.Unit); } /// Get from dividing by value. - public static PressureChangeRate operator /(PressureChangeRate left, double right) + public static PressureChangeRate operator /(PressureChangeRate left, QuantityValue right) { return new PressureChangeRate(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(PressureChangeRate left, PressureChangeRate right) + public static QuantityValue operator /(PressureChangeRate left, PressureChangeRate right) { return left.PascalsPerSecond / right.PascalsPerSecond; } @@ -709,6 +712,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Press return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(PressureChangeRate left, PressureChangeRate right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(PressureChangeRate left, PressureChangeRate right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -721,7 +737,29 @@ public int CompareTo(object obj) /// public int CompareTo(PressureChangeRate other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is PressureChangeRate objPressureChangeRate)) + return false; + return Equals(objPressureChangeRate); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(PressureChangeRate other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -764,13 +802,13 @@ public int CompareTo(PressureChangeRate other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PressureChangeRate other, double tolerance, ComparisonType comparisonType) + public bool Equals(PressureChangeRate other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -781,7 +819,7 @@ public bool Equals(PressureChangeRate other, double tolerance, ComparisonType co /// A hash code for the current PressureChangeRate. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -792,17 +830,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(PressureChangeRateUnit unit) + public QuantityValue As(PressureChangeRateUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -817,12 +854,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is PressureChangeRateUnit unitAsPressureChangeRateUnit)) + if (!(unit is PressureChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsPressureChangeRateUnit); + return (QuantityValue)As(typedUnit); } /// @@ -854,7 +891,7 @@ public PressureChangeRate ToUnit(PressureChangeRateUnit unit, UnitConverter unit var converted = conversionFunction(this); return (PressureChangeRate)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(PressureChangeRateUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -862,17 +899,17 @@ public PressureChangeRate ToUnit(PressureChangeRateUnit unit, UnitConverter unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PressureChangeRateUnit unitAsPressureChangeRateUnit)) + if (!(unit is PressureChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsPressureChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -899,10 +936,10 @@ public PressureChangeRate ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(PressureChangeRateUnit unit) + private QuantityValue GetValueAs(PressureChangeRateUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs index 4477fbdf39..5cd1baf2d0 100644 --- a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as "a to b" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer). /// [DataContract] - public partial struct Ratio : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Ratio : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -77,9 +77,9 @@ static Ratio() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Ratio(double value, RatioUnit unit) + public Ratio(QuantityValue value, RatioUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -91,14 +91,14 @@ public Ratio(double value, RatioUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Ratio(double value, UnitSystem unitSystem) + public Ratio(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -139,7 +139,10 @@ public Ratio(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -162,34 +165,34 @@ public Ratio(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimalFractions => As(RatioUnit.DecimalFraction); + public QuantityValue DecimalFractions => As(RatioUnit.DecimalFraction); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerBillion => As(RatioUnit.PartPerBillion); + public QuantityValue PartsPerBillion => As(RatioUnit.PartPerBillion); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerMillion => As(RatioUnit.PartPerMillion); + public QuantityValue PartsPerMillion => As(RatioUnit.PartPerMillion); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerThousand => As(RatioUnit.PartPerThousand); + public QuantityValue PartsPerThousand => As(RatioUnit.PartPerThousand); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerTrillion => As(RatioUnit.PartPerTrillion); + public QuantityValue PartsPerTrillion => As(RatioUnit.PartPerTrillion); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Percent => As(RatioUnit.Percent); + public QuantityValue Percent => As(RatioUnit.Percent); #endregion @@ -260,7 +263,7 @@ public static string GetAbbreviation(RatioUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Ratio FromDecimalFractions(QuantityValue decimalfractions) { - double value = (double) decimalfractions; + QuantityValue value = (QuantityValue) decimalfractions; return new Ratio(value, RatioUnit.DecimalFraction); } @@ -270,7 +273,7 @@ public static Ratio FromDecimalFractions(QuantityValue decimalfractions) /// If value is NaN or Infinity. public static Ratio FromPartsPerBillion(QuantityValue partsperbillion) { - double value = (double) partsperbillion; + QuantityValue value = (QuantityValue) partsperbillion; return new Ratio(value, RatioUnit.PartPerBillion); } @@ -280,7 +283,7 @@ public static Ratio FromPartsPerBillion(QuantityValue partsperbillion) /// If value is NaN or Infinity. public static Ratio FromPartsPerMillion(QuantityValue partspermillion) { - double value = (double) partspermillion; + QuantityValue value = (QuantityValue) partspermillion; return new Ratio(value, RatioUnit.PartPerMillion); } @@ -290,7 +293,7 @@ public static Ratio FromPartsPerMillion(QuantityValue partspermillion) /// If value is NaN or Infinity. public static Ratio FromPartsPerThousand(QuantityValue partsperthousand) { - double value = (double) partsperthousand; + QuantityValue value = (QuantityValue) partsperthousand; return new Ratio(value, RatioUnit.PartPerThousand); } @@ -300,7 +303,7 @@ public static Ratio FromPartsPerThousand(QuantityValue partsperthousand) /// If value is NaN or Infinity. public static Ratio FromPartsPerTrillion(QuantityValue partspertrillion) { - double value = (double) partspertrillion; + QuantityValue value = (QuantityValue) partspertrillion; return new Ratio(value, RatioUnit.PartPerTrillion); } @@ -310,7 +313,7 @@ public static Ratio FromPartsPerTrillion(QuantityValue partspertrillion) /// If value is NaN or Infinity. public static Ratio FromPercent(QuantityValue percent) { - double value = (double) percent; + QuantityValue value = (QuantityValue) percent; return new Ratio(value, RatioUnit.Percent); } @@ -322,7 +325,7 @@ public static Ratio FromPercent(QuantityValue percent) /// Ratio unit value. public static Ratio From(QuantityValue value, RatioUnit fromUnit) { - return new Ratio((double)value, fromUnit); + return new Ratio((QuantityValue)value, fromUnit); } #endregion @@ -492,25 +495,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ratio } /// Get from multiplying value and . - public static Ratio operator *(double left, Ratio right) + public static Ratio operator *(QuantityValue left, Ratio right) { return new Ratio(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Ratio operator *(Ratio left, double right) + public static Ratio operator *(Ratio left, QuantityValue right) { return new Ratio(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Ratio operator /(Ratio left, double right) + public static Ratio operator /(Ratio left, QuantityValue right) { return new Ratio(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Ratio left, Ratio right) + public static QuantityValue operator /(Ratio left, Ratio right) { return left.DecimalFractions / right.DecimalFractions; } @@ -543,6 +546,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ratio return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Ratio left, Ratio right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Ratio left, Ratio right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -555,7 +571,29 @@ public int CompareTo(object obj) /// public int CompareTo(Ratio other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Ratio objRatio)) + return false; + return Equals(objRatio); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Ratio other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -598,13 +636,13 @@ public int CompareTo(Ratio other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Ratio other, double tolerance, ComparisonType comparisonType) + public bool Equals(Ratio other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -615,7 +653,7 @@ public bool Equals(Ratio other, double tolerance, ComparisonType comparisonType) /// A hash code for the current Ratio. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -626,17 +664,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(RatioUnit unit) + public QuantityValue As(RatioUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -651,12 +688,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is RatioUnit unitAsRatioUnit)) + if (!(unit is RatioUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioUnit)} is supported.", nameof(unit)); - return As(unitAsRatioUnit); + return (QuantityValue)As(typedUnit); } /// @@ -688,7 +725,7 @@ public Ratio ToUnit(RatioUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Ratio)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(RatioUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -696,17 +733,17 @@ public Ratio ToUnit(RatioUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RatioUnit unitAsRatioUnit)) + if (!(unit is RatioUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRatioUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -733,10 +770,10 @@ public Ratio ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(RatioUnit unit) + private QuantityValue GetValueAs(RatioUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs index 9a19832e06..55d191ea6c 100644 --- a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The change in ratio per unit of time. /// [DataContract] - public partial struct RatioChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct RatioChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -73,9 +73,9 @@ static RatioChangeRate() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public RatioChangeRate(double value, RatioChangeRateUnit unit) + public RatioChangeRate(QuantityValue value, RatioChangeRateUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -87,14 +87,14 @@ public RatioChangeRate(double value, RatioChangeRateUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public RatioChangeRate(double value, UnitSystem unitSystem) + public RatioChangeRate(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -135,7 +135,10 @@ public RatioChangeRate(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -158,14 +161,14 @@ public RatioChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimalFractionsPerSecond => As(RatioChangeRateUnit.DecimalFractionPerSecond); + public QuantityValue DecimalFractionsPerSecond => As(RatioChangeRateUnit.DecimalFractionPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PercentsPerSecond => As(RatioChangeRateUnit.PercentPerSecond); + public QuantityValue PercentsPerSecond => As(RatioChangeRateUnit.PercentPerSecond); #endregion @@ -224,7 +227,7 @@ public static string GetAbbreviation(RatioChangeRateUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static RatioChangeRate FromDecimalFractionsPerSecond(QuantityValue decimalfractionspersecond) { - double value = (double) decimalfractionspersecond; + QuantityValue value = (QuantityValue) decimalfractionspersecond; return new RatioChangeRate(value, RatioChangeRateUnit.DecimalFractionPerSecond); } @@ -234,7 +237,7 @@ public static RatioChangeRate FromDecimalFractionsPerSecond(QuantityValue decima /// If value is NaN or Infinity. public static RatioChangeRate FromPercentsPerSecond(QuantityValue percentspersecond) { - double value = (double) percentspersecond; + QuantityValue value = (QuantityValue) percentspersecond; return new RatioChangeRate(value, RatioChangeRateUnit.PercentPerSecond); } @@ -246,7 +249,7 @@ public static RatioChangeRate FromPercentsPerSecond(QuantityValue percentspersec /// RatioChangeRate unit value. public static RatioChangeRate From(QuantityValue value, RatioChangeRateUnit fromUnit) { - return new RatioChangeRate((double)value, fromUnit); + return new RatioChangeRate((QuantityValue)value, fromUnit); } #endregion @@ -416,25 +419,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ratio } /// Get from multiplying value and . - public static RatioChangeRate operator *(double left, RatioChangeRate right) + public static RatioChangeRate operator *(QuantityValue left, RatioChangeRate right) { return new RatioChangeRate(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static RatioChangeRate operator *(RatioChangeRate left, double right) + public static RatioChangeRate operator *(RatioChangeRate left, QuantityValue right) { return new RatioChangeRate(left.Value * right, left.Unit); } /// Get from dividing by value. - public static RatioChangeRate operator /(RatioChangeRate left, double right) + public static RatioChangeRate operator /(RatioChangeRate left, QuantityValue right) { return new RatioChangeRate(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(RatioChangeRate left, RatioChangeRate right) + public static QuantityValue operator /(RatioChangeRate left, RatioChangeRate right) { return left.DecimalFractionsPerSecond / right.DecimalFractionsPerSecond; } @@ -467,6 +470,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ratio return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(RatioChangeRate left, RatioChangeRate right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(RatioChangeRate left, RatioChangeRate right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -479,7 +495,29 @@ public int CompareTo(object obj) /// public int CompareTo(RatioChangeRate other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is RatioChangeRate objRatioChangeRate)) + return false; + return Equals(objRatioChangeRate); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(RatioChangeRate other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -522,13 +560,13 @@ public int CompareTo(RatioChangeRate other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RatioChangeRate other, double tolerance, ComparisonType comparisonType) + public bool Equals(RatioChangeRate other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -539,7 +577,7 @@ public bool Equals(RatioChangeRate other, double tolerance, ComparisonType compa /// A hash code for the current RatioChangeRate. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -550,17 +588,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(RatioChangeRateUnit unit) + public QuantityValue As(RatioChangeRateUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -575,12 +612,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is RatioChangeRateUnit unitAsRatioChangeRateUnit)) + if (!(unit is RatioChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsRatioChangeRateUnit); + return (QuantityValue)As(typedUnit); } /// @@ -612,7 +649,7 @@ public RatioChangeRate ToUnit(RatioChangeRateUnit unit, UnitConverter unitConver var converted = conversionFunction(this); return (RatioChangeRate)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(RatioChangeRateUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -620,17 +657,17 @@ public RatioChangeRate ToUnit(RatioChangeRateUnit unit, UnitConverter unitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RatioChangeRateUnit unitAsRatioChangeRateUnit)) + if (!(unit is RatioChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRatioChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -657,10 +694,10 @@ public RatioChangeRate ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(RatioChangeRateUnit unit) + private QuantityValue GetValueAs(RatioChangeRateUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs index b46c2e5303..bcb82d37ff 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. /// [DataContract] - public partial struct ReactiveEnergy : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ReactiveEnergy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -74,9 +74,9 @@ static ReactiveEnergy() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ReactiveEnergy(double value, ReactiveEnergyUnit unit) + public ReactiveEnergy(QuantityValue value, ReactiveEnergyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -88,14 +88,14 @@ public ReactiveEnergy(double value, ReactiveEnergyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ReactiveEnergy(double value, UnitSystem unitSystem) + public ReactiveEnergy(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -136,7 +136,10 @@ public ReactiveEnergy(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -159,19 +162,19 @@ public ReactiveEnergy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); + public QuantityValue KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); + public QuantityValue MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); + public QuantityValue VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); #endregion @@ -233,7 +236,7 @@ public static string GetAbbreviation(ReactiveEnergyUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilovoltamperereactivehours) { - double value = (double) kilovoltamperereactivehours; + QuantityValue value = (QuantityValue) kilovoltamperereactivehours; return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); } @@ -243,7 +246,7 @@ public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilov /// If value is NaN or Infinity. public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megavoltamperereactivehours) { - double value = (double) megavoltamperereactivehours; + QuantityValue value = (QuantityValue) megavoltamperereactivehours; return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); } @@ -253,7 +256,7 @@ public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megav /// If value is NaN or Infinity. public static ReactiveEnergy FromVoltampereReactiveHours(QuantityValue voltamperereactivehours) { - double value = (double) voltamperereactivehours; + QuantityValue value = (QuantityValue) voltamperereactivehours; return new ReactiveEnergy(value, ReactiveEnergyUnit.VoltampereReactiveHour); } @@ -265,7 +268,7 @@ public static ReactiveEnergy FromVoltampereReactiveHours(QuantityValue voltamper /// ReactiveEnergy unit value. public static ReactiveEnergy From(QuantityValue value, ReactiveEnergyUnit fromUnit) { - return new ReactiveEnergy((double)value, fromUnit); + return new ReactiveEnergy((QuantityValue)value, fromUnit); } #endregion @@ -435,25 +438,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out React } /// Get from multiplying value and . - public static ReactiveEnergy operator *(double left, ReactiveEnergy right) + public static ReactiveEnergy operator *(QuantityValue left, ReactiveEnergy right) { return new ReactiveEnergy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ReactiveEnergy operator *(ReactiveEnergy left, double right) + public static ReactiveEnergy operator *(ReactiveEnergy left, QuantityValue right) { return new ReactiveEnergy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ReactiveEnergy operator /(ReactiveEnergy left, double right) + public static ReactiveEnergy operator /(ReactiveEnergy left, QuantityValue right) { return new ReactiveEnergy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ReactiveEnergy left, ReactiveEnergy right) + public static QuantityValue operator /(ReactiveEnergy left, ReactiveEnergy right) { return left.VoltampereReactiveHours / right.VoltampereReactiveHours; } @@ -486,6 +489,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out React return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ReactiveEnergy left, ReactiveEnergy right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ReactiveEnergy left, ReactiveEnergy right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -498,7 +514,29 @@ public int CompareTo(object obj) /// public int CompareTo(ReactiveEnergy other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ReactiveEnergy objReactiveEnergy)) + return false; + return Equals(objReactiveEnergy); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ReactiveEnergy other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -541,13 +579,13 @@ public int CompareTo(ReactiveEnergy other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ReactiveEnergy other, double tolerance, ComparisonType comparisonType) + public bool Equals(ReactiveEnergy other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -558,7 +596,7 @@ public bool Equals(ReactiveEnergy other, double tolerance, ComparisonType compar /// A hash code for the current ReactiveEnergy. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -569,17 +607,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ReactiveEnergyUnit unit) + public QuantityValue As(ReactiveEnergyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -594,12 +631,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ReactiveEnergyUnit unitAsReactiveEnergyUnit)) + if (!(unit is ReactiveEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactiveEnergyUnit)} is supported.", nameof(unit)); - return As(unitAsReactiveEnergyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -631,7 +668,7 @@ public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (ReactiveEnergy)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ReactiveEnergyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -639,17 +676,17 @@ public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ReactiveEnergyUnit unitAsReactiveEnergyUnit)) + if (!(unit is ReactiveEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactiveEnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsReactiveEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -676,10 +713,10 @@ public ReactiveEnergy ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ReactiveEnergyUnit unit) + private QuantityValue GetValueAs(ReactiveEnergyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs index 12ba60dcba..0a4d9cb603 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase. /// [DataContract] - public partial struct ReactivePower : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ReactivePower : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static ReactivePower() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ReactivePower(double value, ReactivePowerUnit unit) + public ReactivePower(QuantityValue value, ReactivePowerUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public ReactivePower(double value, ReactivePowerUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ReactivePower(double value, UnitSystem unitSystem) + public ReactivePower(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public ReactivePower(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,24 +163,24 @@ public ReactivePower(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigavoltamperesReactive => As(ReactivePowerUnit.GigavoltampereReactive); + public QuantityValue GigavoltamperesReactive => As(ReactivePowerUnit.GigavoltampereReactive); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilovoltamperesReactive => As(ReactivePowerUnit.KilovoltampereReactive); + public QuantityValue KilovoltamperesReactive => As(ReactivePowerUnit.KilovoltampereReactive); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegavoltamperesReactive => As(ReactivePowerUnit.MegavoltampereReactive); + public QuantityValue MegavoltamperesReactive => As(ReactivePowerUnit.MegavoltampereReactive); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double VoltamperesReactive => As(ReactivePowerUnit.VoltampereReactive); + public QuantityValue VoltamperesReactive => As(ReactivePowerUnit.VoltampereReactive); #endregion @@ -242,7 +245,7 @@ public static string GetAbbreviation(ReactivePowerUnit unit, IFormatProvider? pr /// If value is NaN or Infinity. public static ReactivePower FromGigavoltamperesReactive(QuantityValue gigavoltamperesreactive) { - double value = (double) gigavoltamperesreactive; + QuantityValue value = (QuantityValue) gigavoltamperesreactive; return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); } @@ -252,7 +255,7 @@ public static ReactivePower FromGigavoltamperesReactive(QuantityValue gigavoltam /// If value is NaN or Infinity. public static ReactivePower FromKilovoltamperesReactive(QuantityValue kilovoltamperesreactive) { - double value = (double) kilovoltamperesreactive; + QuantityValue value = (QuantityValue) kilovoltamperesreactive; return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); } @@ -262,7 +265,7 @@ public static ReactivePower FromKilovoltamperesReactive(QuantityValue kilovoltam /// If value is NaN or Infinity. public static ReactivePower FromMegavoltamperesReactive(QuantityValue megavoltamperesreactive) { - double value = (double) megavoltamperesreactive; + QuantityValue value = (QuantityValue) megavoltamperesreactive; return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); } @@ -272,7 +275,7 @@ public static ReactivePower FromMegavoltamperesReactive(QuantityValue megavoltam /// If value is NaN or Infinity. public static ReactivePower FromVoltamperesReactive(QuantityValue voltamperesreactive) { - double value = (double) voltamperesreactive; + QuantityValue value = (QuantityValue) voltamperesreactive; return new ReactivePower(value, ReactivePowerUnit.VoltampereReactive); } @@ -284,7 +287,7 @@ public static ReactivePower FromVoltamperesReactive(QuantityValue voltamperesrea /// ReactivePower unit value. public static ReactivePower From(QuantityValue value, ReactivePowerUnit fromUnit) { - return new ReactivePower((double)value, fromUnit); + return new ReactivePower((QuantityValue)value, fromUnit); } #endregion @@ -454,25 +457,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out React } /// Get from multiplying value and . - public static ReactivePower operator *(double left, ReactivePower right) + public static ReactivePower operator *(QuantityValue left, ReactivePower right) { return new ReactivePower(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ReactivePower operator *(ReactivePower left, double right) + public static ReactivePower operator *(ReactivePower left, QuantityValue right) { return new ReactivePower(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ReactivePower operator /(ReactivePower left, double right) + public static ReactivePower operator /(ReactivePower left, QuantityValue right) { return new ReactivePower(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ReactivePower left, ReactivePower right) + public static QuantityValue operator /(ReactivePower left, ReactivePower right) { return left.VoltamperesReactive / right.VoltamperesReactive; } @@ -505,6 +508,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out React return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ReactivePower left, ReactivePower right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ReactivePower left, ReactivePower right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -517,7 +533,29 @@ public int CompareTo(object obj) /// public int CompareTo(ReactivePower other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ReactivePower objReactivePower)) + return false; + return Equals(objReactivePower); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ReactivePower other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -560,13 +598,13 @@ public int CompareTo(ReactivePower other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ReactivePower other, double tolerance, ComparisonType comparisonType) + public bool Equals(ReactivePower other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -577,7 +615,7 @@ public bool Equals(ReactivePower other, double tolerance, ComparisonType compari /// A hash code for the current ReactivePower. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -588,17 +626,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ReactivePowerUnit unit) + public QuantityValue As(ReactivePowerUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -613,12 +650,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ReactivePowerUnit unitAsReactivePowerUnit)) + if (!(unit is ReactivePowerUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactivePowerUnit)} is supported.", nameof(unit)); - return As(unitAsReactivePowerUnit); + return (QuantityValue)As(typedUnit); } /// @@ -650,7 +687,7 @@ public ReactivePower ToUnit(ReactivePowerUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (ReactivePower)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ReactivePowerUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -658,17 +695,17 @@ public ReactivePower ToUnit(ReactivePowerUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ReactivePowerUnit unitAsReactivePowerUnit)) + if (!(unit is ReactivePowerUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactivePowerUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsReactivePowerUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -695,10 +732,10 @@ public ReactivePower ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ReactivePowerUnit unit) + private QuantityValue GetValueAs(ReactivePowerUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs index fa18c54017..f0756bf8c4 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Inverse-square_law /// [DataContract] - public partial struct ReciprocalArea : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ReciprocalArea : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -85,9 +85,9 @@ static ReciprocalArea() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ReciprocalArea(double value, ReciprocalAreaUnit unit) + public ReciprocalArea(QuantityValue value, ReciprocalAreaUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -99,14 +99,14 @@ public ReciprocalArea(double value, ReciprocalAreaUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ReciprocalArea(double value, UnitSystem unitSystem) + public ReciprocalArea(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -147,7 +147,10 @@ public ReciprocalArea(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -170,59 +173,59 @@ public ReciprocalArea(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareCentimeters => As(ReciprocalAreaUnit.InverseSquareCentimeter); + public QuantityValue InverseSquareCentimeters => As(ReciprocalAreaUnit.InverseSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareDecimeters => As(ReciprocalAreaUnit.InverseSquareDecimeter); + public QuantityValue InverseSquareDecimeters => As(ReciprocalAreaUnit.InverseSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareFeet => As(ReciprocalAreaUnit.InverseSquareFoot); + public QuantityValue InverseSquareFeet => As(ReciprocalAreaUnit.InverseSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareInches => As(ReciprocalAreaUnit.InverseSquareInch); + public QuantityValue InverseSquareInches => As(ReciprocalAreaUnit.InverseSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareKilometers => As(ReciprocalAreaUnit.InverseSquareKilometer); + public QuantityValue InverseSquareKilometers => As(ReciprocalAreaUnit.InverseSquareKilometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareMeters => As(ReciprocalAreaUnit.InverseSquareMeter); + public QuantityValue InverseSquareMeters => As(ReciprocalAreaUnit.InverseSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareMicrometers => As(ReciprocalAreaUnit.InverseSquareMicrometer); + public QuantityValue InverseSquareMicrometers => As(ReciprocalAreaUnit.InverseSquareMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareMiles => As(ReciprocalAreaUnit.InverseSquareMile); + public QuantityValue InverseSquareMiles => As(ReciprocalAreaUnit.InverseSquareMile); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareMillimeters => As(ReciprocalAreaUnit.InverseSquareMillimeter); + public QuantityValue InverseSquareMillimeters => As(ReciprocalAreaUnit.InverseSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseSquareYards => As(ReciprocalAreaUnit.InverseSquareYard); + public QuantityValue InverseSquareYards => As(ReciprocalAreaUnit.InverseSquareYard); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseUsSurveySquareFeet => As(ReciprocalAreaUnit.InverseUsSurveySquareFoot); + public QuantityValue InverseUsSurveySquareFeet => As(ReciprocalAreaUnit.InverseUsSurveySquareFoot); #endregion @@ -308,7 +311,7 @@ public static string GetAbbreviation(ReciprocalAreaUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareCentimeters(QuantityValue inversesquarecentimeters) { - double value = (double) inversesquarecentimeters; + QuantityValue value = (QuantityValue) inversesquarecentimeters; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareCentimeter); } @@ -318,7 +321,7 @@ public static ReciprocalArea FromInverseSquareCentimeters(QuantityValue inverses /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareDecimeters(QuantityValue inversesquaredecimeters) { - double value = (double) inversesquaredecimeters; + QuantityValue value = (QuantityValue) inversesquaredecimeters; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareDecimeter); } @@ -328,7 +331,7 @@ public static ReciprocalArea FromInverseSquareDecimeters(QuantityValue inversesq /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareFeet(QuantityValue inversesquarefeet) { - double value = (double) inversesquarefeet; + QuantityValue value = (QuantityValue) inversesquarefeet; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareFoot); } @@ -338,7 +341,7 @@ public static ReciprocalArea FromInverseSquareFeet(QuantityValue inversesquarefe /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareInches(QuantityValue inversesquareinches) { - double value = (double) inversesquareinches; + QuantityValue value = (QuantityValue) inversesquareinches; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareInch); } @@ -348,7 +351,7 @@ public static ReciprocalArea FromInverseSquareInches(QuantityValue inversesquare /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareKilometers(QuantityValue inversesquarekilometers) { - double value = (double) inversesquarekilometers; + QuantityValue value = (QuantityValue) inversesquarekilometers; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareKilometer); } @@ -358,7 +361,7 @@ public static ReciprocalArea FromInverseSquareKilometers(QuantityValue inversesq /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareMeters(QuantityValue inversesquaremeters) { - double value = (double) inversesquaremeters; + QuantityValue value = (QuantityValue) inversesquaremeters; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMeter); } @@ -368,7 +371,7 @@ public static ReciprocalArea FromInverseSquareMeters(QuantityValue inversesquare /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareMicrometers(QuantityValue inversesquaremicrometers) { - double value = (double) inversesquaremicrometers; + QuantityValue value = (QuantityValue) inversesquaremicrometers; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMicrometer); } @@ -378,7 +381,7 @@ public static ReciprocalArea FromInverseSquareMicrometers(QuantityValue inverses /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareMiles(QuantityValue inversesquaremiles) { - double value = (double) inversesquaremiles; + QuantityValue value = (QuantityValue) inversesquaremiles; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMile); } @@ -388,7 +391,7 @@ public static ReciprocalArea FromInverseSquareMiles(QuantityValue inversesquarem /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareMillimeters(QuantityValue inversesquaremillimeters) { - double value = (double) inversesquaremillimeters; + QuantityValue value = (QuantityValue) inversesquaremillimeters; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMillimeter); } @@ -398,7 +401,7 @@ public static ReciprocalArea FromInverseSquareMillimeters(QuantityValue inverses /// If value is NaN or Infinity. public static ReciprocalArea FromInverseSquareYards(QuantityValue inversesquareyards) { - double value = (double) inversesquareyards; + QuantityValue value = (QuantityValue) inversesquareyards; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareYard); } @@ -408,7 +411,7 @@ public static ReciprocalArea FromInverseSquareYards(QuantityValue inversesquarey /// If value is NaN or Infinity. public static ReciprocalArea FromInverseUsSurveySquareFeet(QuantityValue inverseussurveysquarefeet) { - double value = (double) inverseussurveysquarefeet; + QuantityValue value = (QuantityValue) inverseussurveysquarefeet; return new ReciprocalArea(value, ReciprocalAreaUnit.InverseUsSurveySquareFoot); } @@ -420,7 +423,7 @@ public static ReciprocalArea FromInverseUsSurveySquareFeet(QuantityValue inverse /// ReciprocalArea unit value. public static ReciprocalArea From(QuantityValue value, ReciprocalAreaUnit fromUnit) { - return new ReciprocalArea((double)value, fromUnit); + return new ReciprocalArea((QuantityValue)value, fromUnit); } #endregion @@ -590,25 +593,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Recip } /// Get from multiplying value and . - public static ReciprocalArea operator *(double left, ReciprocalArea right) + public static ReciprocalArea operator *(QuantityValue left, ReciprocalArea right) { return new ReciprocalArea(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ReciprocalArea operator *(ReciprocalArea left, double right) + public static ReciprocalArea operator *(ReciprocalArea left, QuantityValue right) { return new ReciprocalArea(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ReciprocalArea operator /(ReciprocalArea left, double right) + public static ReciprocalArea operator /(ReciprocalArea left, QuantityValue right) { return new ReciprocalArea(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ReciprocalArea left, ReciprocalArea right) + public static QuantityValue operator /(ReciprocalArea left, ReciprocalArea right) { return left.InverseSquareMeters / right.InverseSquareMeters; } @@ -641,6 +644,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Recip return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ReciprocalArea left, ReciprocalArea right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ReciprocalArea left, ReciprocalArea right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -653,7 +669,29 @@ public int CompareTo(object obj) /// public int CompareTo(ReciprocalArea other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ReciprocalArea objReciprocalArea)) + return false; + return Equals(objReciprocalArea); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ReciprocalArea other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -696,13 +734,13 @@ public int CompareTo(ReciprocalArea other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ReciprocalArea other, double tolerance, ComparisonType comparisonType) + public bool Equals(ReciprocalArea other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -713,7 +751,7 @@ public bool Equals(ReciprocalArea other, double tolerance, ComparisonType compar /// A hash code for the current ReciprocalArea. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -724,17 +762,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ReciprocalAreaUnit unit) + public QuantityValue As(ReciprocalAreaUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -749,12 +786,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ReciprocalAreaUnit unitAsReciprocalAreaUnit)) + if (!(unit is ReciprocalAreaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalAreaUnit)} is supported.", nameof(unit)); - return As(unitAsReciprocalAreaUnit); + return (QuantityValue)As(typedUnit); } /// @@ -786,7 +823,7 @@ public ReciprocalArea ToUnit(ReciprocalAreaUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (ReciprocalArea)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ReciprocalAreaUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -794,17 +831,17 @@ public ReciprocalArea ToUnit(ReciprocalAreaUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ReciprocalAreaUnit unitAsReciprocalAreaUnit)) + if (!(unit is ReciprocalAreaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalAreaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsReciprocalAreaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -831,10 +868,10 @@ public ReciprocalArea ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ReciprocalAreaUnit unit) + private QuantityValue GetValueAs(ReciprocalAreaUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs index db5125af45..80d8b7d8e3 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Reciprocal_length /// [DataContract] - public partial struct ReciprocalLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ReciprocalLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -84,9 +84,9 @@ static ReciprocalLength() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ReciprocalLength(double value, ReciprocalLengthUnit unit) + public ReciprocalLength(QuantityValue value, ReciprocalLengthUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -98,14 +98,14 @@ public ReciprocalLength(double value, ReciprocalLengthUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ReciprocalLength(double value, UnitSystem unitSystem) + public ReciprocalLength(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -146,7 +146,10 @@ public ReciprocalLength(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -169,54 +172,54 @@ public ReciprocalLength(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseCentimeters => As(ReciprocalLengthUnit.InverseCentimeter); + public QuantityValue InverseCentimeters => As(ReciprocalLengthUnit.InverseCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseFeet => As(ReciprocalLengthUnit.InverseFoot); + public QuantityValue InverseFeet => As(ReciprocalLengthUnit.InverseFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseInches => As(ReciprocalLengthUnit.InverseInch); + public QuantityValue InverseInches => As(ReciprocalLengthUnit.InverseInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseMeters => As(ReciprocalLengthUnit.InverseMeter); + public QuantityValue InverseMeters => As(ReciprocalLengthUnit.InverseMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseMicroinches => As(ReciprocalLengthUnit.InverseMicroinch); + public QuantityValue InverseMicroinches => As(ReciprocalLengthUnit.InverseMicroinch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseMils => As(ReciprocalLengthUnit.InverseMil); + public QuantityValue InverseMils => As(ReciprocalLengthUnit.InverseMil); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseMiles => As(ReciprocalLengthUnit.InverseMile); + public QuantityValue InverseMiles => As(ReciprocalLengthUnit.InverseMile); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseMillimeters => As(ReciprocalLengthUnit.InverseMillimeter); + public QuantityValue InverseMillimeters => As(ReciprocalLengthUnit.InverseMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseUsSurveyFeet => As(ReciprocalLengthUnit.InverseUsSurveyFoot); + public QuantityValue InverseUsSurveyFeet => As(ReciprocalLengthUnit.InverseUsSurveyFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InverseYards => As(ReciprocalLengthUnit.InverseYard); + public QuantityValue InverseYards => As(ReciprocalLengthUnit.InverseYard); #endregion @@ -299,7 +302,7 @@ public static string GetAbbreviation(ReciprocalLengthUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static ReciprocalLength FromInverseCentimeters(QuantityValue inversecentimeters) { - double value = (double) inversecentimeters; + QuantityValue value = (QuantityValue) inversecentimeters; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseCentimeter); } @@ -309,7 +312,7 @@ public static ReciprocalLength FromInverseCentimeters(QuantityValue inversecenti /// If value is NaN or Infinity. public static ReciprocalLength FromInverseFeet(QuantityValue inversefeet) { - double value = (double) inversefeet; + QuantityValue value = (QuantityValue) inversefeet; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseFoot); } @@ -319,7 +322,7 @@ public static ReciprocalLength FromInverseFeet(QuantityValue inversefeet) /// If value is NaN or Infinity. public static ReciprocalLength FromInverseInches(QuantityValue inverseinches) { - double value = (double) inverseinches; + QuantityValue value = (QuantityValue) inverseinches; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseInch); } @@ -329,7 +332,7 @@ public static ReciprocalLength FromInverseInches(QuantityValue inverseinches) /// If value is NaN or Infinity. public static ReciprocalLength FromInverseMeters(QuantityValue inversemeters) { - double value = (double) inversemeters; + QuantityValue value = (QuantityValue) inversemeters; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMeter); } @@ -339,7 +342,7 @@ public static ReciprocalLength FromInverseMeters(QuantityValue inversemeters) /// If value is NaN or Infinity. public static ReciprocalLength FromInverseMicroinches(QuantityValue inversemicroinches) { - double value = (double) inversemicroinches; + QuantityValue value = (QuantityValue) inversemicroinches; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMicroinch); } @@ -349,7 +352,7 @@ public static ReciprocalLength FromInverseMicroinches(QuantityValue inversemicro /// If value is NaN or Infinity. public static ReciprocalLength FromInverseMils(QuantityValue inversemils) { - double value = (double) inversemils; + QuantityValue value = (QuantityValue) inversemils; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMil); } @@ -359,7 +362,7 @@ public static ReciprocalLength FromInverseMils(QuantityValue inversemils) /// If value is NaN or Infinity. public static ReciprocalLength FromInverseMiles(QuantityValue inversemiles) { - double value = (double) inversemiles; + QuantityValue value = (QuantityValue) inversemiles; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMile); } @@ -369,7 +372,7 @@ public static ReciprocalLength FromInverseMiles(QuantityValue inversemiles) /// If value is NaN or Infinity. public static ReciprocalLength FromInverseMillimeters(QuantityValue inversemillimeters) { - double value = (double) inversemillimeters; + QuantityValue value = (QuantityValue) inversemillimeters; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMillimeter); } @@ -379,7 +382,7 @@ public static ReciprocalLength FromInverseMillimeters(QuantityValue inversemilli /// If value is NaN or Infinity. public static ReciprocalLength FromInverseUsSurveyFeet(QuantityValue inverseussurveyfeet) { - double value = (double) inverseussurveyfeet; + QuantityValue value = (QuantityValue) inverseussurveyfeet; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseUsSurveyFoot); } @@ -389,7 +392,7 @@ public static ReciprocalLength FromInverseUsSurveyFeet(QuantityValue inverseussu /// If value is NaN or Infinity. public static ReciprocalLength FromInverseYards(QuantityValue inverseyards) { - double value = (double) inverseyards; + QuantityValue value = (QuantityValue) inverseyards; return new ReciprocalLength(value, ReciprocalLengthUnit.InverseYard); } @@ -401,7 +404,7 @@ public static ReciprocalLength FromInverseYards(QuantityValue inverseyards) /// ReciprocalLength unit value. public static ReciprocalLength From(QuantityValue value, ReciprocalLengthUnit fromUnit) { - return new ReciprocalLength((double)value, fromUnit); + return new ReciprocalLength((QuantityValue)value, fromUnit); } #endregion @@ -571,25 +574,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Recip } /// Get from multiplying value and . - public static ReciprocalLength operator *(double left, ReciprocalLength right) + public static ReciprocalLength operator *(QuantityValue left, ReciprocalLength right) { return new ReciprocalLength(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ReciprocalLength operator *(ReciprocalLength left, double right) + public static ReciprocalLength operator *(ReciprocalLength left, QuantityValue right) { return new ReciprocalLength(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ReciprocalLength operator /(ReciprocalLength left, double right) + public static ReciprocalLength operator /(ReciprocalLength left, QuantityValue right) { return new ReciprocalLength(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ReciprocalLength left, ReciprocalLength right) + public static QuantityValue operator /(ReciprocalLength left, ReciprocalLength right) { return left.InverseMeters / right.InverseMeters; } @@ -622,6 +625,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Recip return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ReciprocalLength left, ReciprocalLength right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ReciprocalLength left, ReciprocalLength right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -634,7 +650,29 @@ public int CompareTo(object obj) /// public int CompareTo(ReciprocalLength other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ReciprocalLength objReciprocalLength)) + return false; + return Equals(objReciprocalLength); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ReciprocalLength other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -677,13 +715,13 @@ public int CompareTo(ReciprocalLength other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ReciprocalLength other, double tolerance, ComparisonType comparisonType) + public bool Equals(ReciprocalLength other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -694,7 +732,7 @@ public bool Equals(ReciprocalLength other, double tolerance, ComparisonType comp /// A hash code for the current ReciprocalLength. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -705,17 +743,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ReciprocalLengthUnit unit) + public QuantityValue As(ReciprocalLengthUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -730,12 +767,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ReciprocalLengthUnit unitAsReciprocalLengthUnit)) + if (!(unit is ReciprocalLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalLengthUnit)} is supported.", nameof(unit)); - return As(unitAsReciprocalLengthUnit); + return (QuantityValue)As(typedUnit); } /// @@ -767,7 +804,7 @@ public ReciprocalLength ToUnit(ReciprocalLengthUnit unit, UnitConverter unitConv var converted = conversionFunction(this); return (ReciprocalLength)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ReciprocalLengthUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -775,17 +812,17 @@ public ReciprocalLength ToUnit(ReciprocalLengthUnit unit, UnitConverter unitConv } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ReciprocalLengthUnit unitAsReciprocalLengthUnit)) + if (!(unit is ReciprocalLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsReciprocalLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -812,10 +849,10 @@ public ReciprocalLength ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ReciprocalLengthUnit unit) + private QuantityValue GetValueAs(ReciprocalLengthUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs index b91d29a949..42045a858b 100644 --- a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Relative humidity is a ratio of the actual water vapor present in the air to the maximum water vapor in the air at the given temperature. /// [DataContract] - public partial struct RelativeHumidity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct RelativeHumidity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -72,9 +72,9 @@ static RelativeHumidity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public RelativeHumidity(double value, RelativeHumidityUnit unit) + public RelativeHumidity(QuantityValue value, RelativeHumidityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -86,14 +86,14 @@ public RelativeHumidity(double value, RelativeHumidityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public RelativeHumidity(double value, UnitSystem unitSystem) + public RelativeHumidity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -134,7 +134,10 @@ public RelativeHumidity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -157,9 +160,9 @@ public RelativeHumidity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Percent => As(RelativeHumidityUnit.Percent); + public QuantityValue Percent => As(RelativeHumidityUnit.Percent); #endregion @@ -215,7 +218,7 @@ public static string GetAbbreviation(RelativeHumidityUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static RelativeHumidity FromPercent(QuantityValue percent) { - double value = (double) percent; + QuantityValue value = (QuantityValue) percent; return new RelativeHumidity(value, RelativeHumidityUnit.Percent); } @@ -227,7 +230,7 @@ public static RelativeHumidity FromPercent(QuantityValue percent) /// RelativeHumidity unit value. public static RelativeHumidity From(QuantityValue value, RelativeHumidityUnit fromUnit) { - return new RelativeHumidity((double)value, fromUnit); + return new RelativeHumidity((QuantityValue)value, fromUnit); } #endregion @@ -397,25 +400,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Relat } /// Get from multiplying value and . - public static RelativeHumidity operator *(double left, RelativeHumidity right) + public static RelativeHumidity operator *(QuantityValue left, RelativeHumidity right) { return new RelativeHumidity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static RelativeHumidity operator *(RelativeHumidity left, double right) + public static RelativeHumidity operator *(RelativeHumidity left, QuantityValue right) { return new RelativeHumidity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static RelativeHumidity operator /(RelativeHumidity left, double right) + public static RelativeHumidity operator /(RelativeHumidity left, QuantityValue right) { return new RelativeHumidity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(RelativeHumidity left, RelativeHumidity right) + public static QuantityValue operator /(RelativeHumidity left, RelativeHumidity right) { return left.Percent / right.Percent; } @@ -448,6 +451,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Relat return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(RelativeHumidity left, RelativeHumidity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(RelativeHumidity left, RelativeHumidity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -460,7 +476,29 @@ public int CompareTo(object obj) /// public int CompareTo(RelativeHumidity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is RelativeHumidity objRelativeHumidity)) + return false; + return Equals(objRelativeHumidity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(RelativeHumidity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -503,13 +541,13 @@ public int CompareTo(RelativeHumidity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RelativeHumidity other, double tolerance, ComparisonType comparisonType) + public bool Equals(RelativeHumidity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -520,7 +558,7 @@ public bool Equals(RelativeHumidity other, double tolerance, ComparisonType comp /// A hash code for the current RelativeHumidity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -531,17 +569,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(RelativeHumidityUnit unit) + public QuantityValue As(RelativeHumidityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -556,12 +593,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is RelativeHumidityUnit unitAsRelativeHumidityUnit)) + if (!(unit is RelativeHumidityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RelativeHumidityUnit)} is supported.", nameof(unit)); - return As(unitAsRelativeHumidityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -593,7 +630,7 @@ public RelativeHumidity ToUnit(RelativeHumidityUnit unit, UnitConverter unitConv var converted = conversionFunction(this); return (RelativeHumidity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(RelativeHumidityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -601,17 +638,17 @@ public RelativeHumidity ToUnit(RelativeHumidityUnit unit, UnitConverter unitConv } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RelativeHumidityUnit unitAsRelativeHumidityUnit)) + if (!(unit is RelativeHumidityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RelativeHumidityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRelativeHumidityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -638,10 +675,10 @@ public RelativeHumidity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(RelativeHumidityUnit unit) + private QuantityValue GetValueAs(RelativeHumidityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs index 82e5e89d70..4f2c933aca 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Angular acceleration is the rate of change of rotational speed. /// [DataContract] - public partial struct RotationalAcceleration : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct RotationalAcceleration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static RotationalAcceleration() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public RotationalAcceleration(double value, RotationalAccelerationUnit unit) + public RotationalAcceleration(QuantityValue value, RotationalAccelerationUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public RotationalAcceleration(double value, RotationalAccelerationUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public RotationalAcceleration(double value, UnitSystem unitSystem) + public RotationalAcceleration(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,24 +163,24 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); + public QuantityValue DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); + public QuantityValue RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); + public QuantityValue RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double RevolutionsPerSecondSquared => As(RotationalAccelerationUnit.RevolutionPerSecondSquared); + public QuantityValue RevolutionsPerSecondSquared => As(RotationalAccelerationUnit.RevolutionPerSecondSquared); #endregion @@ -242,7 +245,7 @@ public static string GetAbbreviation(RotationalAccelerationUnit unit, IFormatPro /// If value is NaN or Infinity. public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue degreespersecondsquared) { - double value = (double) degreespersecondsquared; + QuantityValue value = (QuantityValue) degreespersecondsquared; return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); } @@ -252,7 +255,7 @@ public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue d /// If value is NaN or Infinity. public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue radianspersecondsquared) { - double value = (double) radianspersecondsquared; + QuantityValue value = (QuantityValue) radianspersecondsquared; return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); } @@ -262,7 +265,7 @@ public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue r /// If value is NaN or Infinity. public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(QuantityValue revolutionsperminutepersecond) { - double value = (double) revolutionsperminutepersecond; + QuantityValue value = (QuantityValue) revolutionsperminutepersecond; return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); } @@ -272,7 +275,7 @@ public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(QuantityV /// If value is NaN or Infinity. public static RotationalAcceleration FromRevolutionsPerSecondSquared(QuantityValue revolutionspersecondsquared) { - double value = (double) revolutionspersecondsquared; + QuantityValue value = (QuantityValue) revolutionspersecondsquared; return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerSecondSquared); } @@ -284,7 +287,7 @@ public static RotationalAcceleration FromRevolutionsPerSecondSquared(QuantityVal /// RotationalAcceleration unit value. public static RotationalAcceleration From(QuantityValue value, RotationalAccelerationUnit fromUnit) { - return new RotationalAcceleration((double)value, fromUnit); + return new RotationalAcceleration((QuantityValue)value, fromUnit); } #endregion @@ -454,25 +457,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat } /// Get from multiplying value and . - public static RotationalAcceleration operator *(double left, RotationalAcceleration right) + public static RotationalAcceleration operator *(QuantityValue left, RotationalAcceleration right) { return new RotationalAcceleration(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static RotationalAcceleration operator *(RotationalAcceleration left, double right) + public static RotationalAcceleration operator *(RotationalAcceleration left, QuantityValue right) { return new RotationalAcceleration(left.Value * right, left.Unit); } /// Get from dividing by value. - public static RotationalAcceleration operator /(RotationalAcceleration left, double right) + public static RotationalAcceleration operator /(RotationalAcceleration left, QuantityValue right) { return new RotationalAcceleration(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(RotationalAcceleration left, RotationalAcceleration right) + public static QuantityValue operator /(RotationalAcceleration left, RotationalAcceleration right) { return left.RadiansPerSecondSquared / right.RadiansPerSecondSquared; } @@ -505,6 +508,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(RotationalAcceleration left, RotationalAcceleration right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(RotationalAcceleration left, RotationalAcceleration right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -517,7 +533,29 @@ public int CompareTo(object obj) /// public int CompareTo(RotationalAcceleration other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is RotationalAcceleration objRotationalAcceleration)) + return false; + return Equals(objRotationalAcceleration); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(RotationalAcceleration other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -560,13 +598,13 @@ public int CompareTo(RotationalAcceleration other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalAcceleration other, double tolerance, ComparisonType comparisonType) + public bool Equals(RotationalAcceleration other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -577,7 +615,7 @@ public bool Equals(RotationalAcceleration other, double tolerance, ComparisonTyp /// A hash code for the current RotationalAcceleration. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -588,17 +626,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(RotationalAccelerationUnit unit) + public QuantityValue As(RotationalAccelerationUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -613,12 +650,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is RotationalAccelerationUnit unitAsRotationalAccelerationUnit)) + if (!(unit is RotationalAccelerationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalAccelerationUnit)} is supported.", nameof(unit)); - return As(unitAsRotationalAccelerationUnit); + return (QuantityValue)As(typedUnit); } /// @@ -650,7 +687,7 @@ public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit, UnitConver var converted = conversionFunction(this); return (RotationalAcceleration)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(RotationalAccelerationUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -658,17 +695,17 @@ public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit, UnitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RotationalAccelerationUnit unitAsRotationalAccelerationUnit)) + if (!(unit is RotationalAccelerationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalAccelerationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRotationalAccelerationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -695,10 +732,10 @@ public RotationalAcceleration ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(RotationalAccelerationUnit unit) + private QuantityValue GetValueAs(RotationalAccelerationUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs index 85e4e1cff9..fe07f1048a 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter "omega"). /// [DataContract] - public partial struct RotationalSpeed : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct RotationalSpeed : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -84,9 +84,9 @@ static RotationalSpeed() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public RotationalSpeed(double value, RotationalSpeedUnit unit) + public RotationalSpeed(QuantityValue value, RotationalSpeedUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -98,14 +98,14 @@ public RotationalSpeed(double value, RotationalSpeedUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public RotationalSpeed(double value, UnitSystem unitSystem) + public RotationalSpeed(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -146,7 +146,10 @@ public RotationalSpeed(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -169,69 +172,69 @@ public RotationalSpeed(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); + public QuantityValue CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); + public QuantityValue DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); + public QuantityValue DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); + public QuantityValue DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); + public QuantityValue MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); + public QuantityValue MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); + public QuantityValue MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); + public QuantityValue MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); + public QuantityValue NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); + public QuantityValue NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); + public QuantityValue RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); + public QuantityValue RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); + public QuantityValue RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); #endregion @@ -335,7 +338,7 @@ public static string GetAbbreviation(RotationalSpeedUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue centiradianspersecond) { - double value = (double) centiradianspersecond; + QuantityValue value = (QuantityValue) centiradianspersecond; return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); } @@ -345,7 +348,7 @@ public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue centiradia /// If value is NaN or Infinity. public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue deciradianspersecond) { - double value = (double) deciradianspersecond; + QuantityValue value = (QuantityValue) deciradianspersecond; return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); } @@ -355,7 +358,7 @@ public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue deciradians /// If value is NaN or Infinity. public static RotationalSpeed FromDegreesPerMinute(QuantityValue degreesperminute) { - double value = (double) degreesperminute; + QuantityValue value = (QuantityValue) degreesperminute; return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); } @@ -365,7 +368,7 @@ public static RotationalSpeed FromDegreesPerMinute(QuantityValue degreesperminut /// If value is NaN or Infinity. public static RotationalSpeed FromDegreesPerSecond(QuantityValue degreespersecond) { - double value = (double) degreespersecond; + QuantityValue value = (QuantityValue) degreespersecond; return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); } @@ -375,7 +378,7 @@ public static RotationalSpeed FromDegreesPerSecond(QuantityValue degreespersecon /// If value is NaN or Infinity. public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue microdegreespersecond) { - double value = (double) microdegreespersecond; + QuantityValue value = (QuantityValue) microdegreespersecond; return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); } @@ -385,7 +388,7 @@ public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue microdegre /// If value is NaN or Infinity. public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue microradianspersecond) { - double value = (double) microradianspersecond; + QuantityValue value = (QuantityValue) microradianspersecond; return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); } @@ -395,7 +398,7 @@ public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue microradia /// If value is NaN or Infinity. public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue millidegreespersecond) { - double value = (double) millidegreespersecond; + QuantityValue value = (QuantityValue) millidegreespersecond; return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); } @@ -405,7 +408,7 @@ public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue millidegre /// If value is NaN or Infinity. public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue milliradianspersecond) { - double value = (double) milliradianspersecond; + QuantityValue value = (QuantityValue) milliradianspersecond; return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); } @@ -415,7 +418,7 @@ public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue milliradia /// If value is NaN or Infinity. public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue nanodegreespersecond) { - double value = (double) nanodegreespersecond; + QuantityValue value = (QuantityValue) nanodegreespersecond; return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); } @@ -425,7 +428,7 @@ public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue nanodegrees /// If value is NaN or Infinity. public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue nanoradianspersecond) { - double value = (double) nanoradianspersecond; + QuantityValue value = (QuantityValue) nanoradianspersecond; return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); } @@ -435,7 +438,7 @@ public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue nanoradians /// If value is NaN or Infinity. public static RotationalSpeed FromRadiansPerSecond(QuantityValue radianspersecond) { - double value = (double) radianspersecond; + QuantityValue value = (QuantityValue) radianspersecond; return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); } @@ -445,7 +448,7 @@ public static RotationalSpeed FromRadiansPerSecond(QuantityValue radianspersecon /// If value is NaN or Infinity. public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue revolutionsperminute) { - double value = (double) revolutionsperminute; + QuantityValue value = (QuantityValue) revolutionsperminute; return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); } @@ -455,7 +458,7 @@ public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue revolutions /// If value is NaN or Infinity. public static RotationalSpeed FromRevolutionsPerSecond(QuantityValue revolutionspersecond) { - double value = (double) revolutionspersecond; + QuantityValue value = (QuantityValue) revolutionspersecond; return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerSecond); } @@ -467,7 +470,7 @@ public static RotationalSpeed FromRevolutionsPerSecond(QuantityValue revolutions /// RotationalSpeed unit value. public static RotationalSpeed From(QuantityValue value, RotationalSpeedUnit fromUnit) { - return new RotationalSpeed((double)value, fromUnit); + return new RotationalSpeed((QuantityValue)value, fromUnit); } #endregion @@ -637,25 +640,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat } /// Get from multiplying value and . - public static RotationalSpeed operator *(double left, RotationalSpeed right) + public static RotationalSpeed operator *(QuantityValue left, RotationalSpeed right) { return new RotationalSpeed(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static RotationalSpeed operator *(RotationalSpeed left, double right) + public static RotationalSpeed operator *(RotationalSpeed left, QuantityValue right) { return new RotationalSpeed(left.Value * right, left.Unit); } /// Get from dividing by value. - public static RotationalSpeed operator /(RotationalSpeed left, double right) + public static RotationalSpeed operator /(RotationalSpeed left, QuantityValue right) { return new RotationalSpeed(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(RotationalSpeed left, RotationalSpeed right) + public static QuantityValue operator /(RotationalSpeed left, RotationalSpeed right) { return left.RadiansPerSecond / right.RadiansPerSecond; } @@ -688,6 +691,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(RotationalSpeed left, RotationalSpeed right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(RotationalSpeed left, RotationalSpeed right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -700,7 +716,29 @@ public int CompareTo(object obj) /// public int CompareTo(RotationalSpeed other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is RotationalSpeed objRotationalSpeed)) + return false; + return Equals(objRotationalSpeed); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(RotationalSpeed other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -743,13 +781,13 @@ public int CompareTo(RotationalSpeed other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalSpeed other, double tolerance, ComparisonType comparisonType) + public bool Equals(RotationalSpeed other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -760,7 +798,7 @@ public bool Equals(RotationalSpeed other, double tolerance, ComparisonType compa /// A hash code for the current RotationalSpeed. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -771,17 +809,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(RotationalSpeedUnit unit) + public QuantityValue As(RotationalSpeedUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -796,12 +833,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is RotationalSpeedUnit unitAsRotationalSpeedUnit)) + if (!(unit is RotationalSpeedUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalSpeedUnit)} is supported.", nameof(unit)); - return As(unitAsRotationalSpeedUnit); + return (QuantityValue)As(typedUnit); } /// @@ -833,7 +870,7 @@ public RotationalSpeed ToUnit(RotationalSpeedUnit unit, UnitConverter unitConver var converted = conversionFunction(this); return (RotationalSpeed)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(RotationalSpeedUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -841,17 +878,17 @@ public RotationalSpeed ToUnit(RotationalSpeedUnit unit, UnitConverter unitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RotationalSpeedUnit unitAsRotationalSpeedUnit)) + if (!(unit is RotationalSpeedUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalSpeedUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRotationalSpeedUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -878,10 +915,10 @@ public RotationalSpeed ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(RotationalSpeedUnit unit) + private QuantityValue GetValueAs(RotationalSpeedUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs index dd3526719d..566185aa51 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// [DataContract] - public partial struct RotationalStiffness : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct RotationalStiffness : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -104,9 +104,9 @@ static RotationalStiffness() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public RotationalStiffness(double value, RotationalStiffnessUnit unit) + public RotationalStiffness(QuantityValue value, RotationalStiffnessUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -118,14 +118,14 @@ public RotationalStiffness(double value, RotationalStiffnessUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public RotationalStiffness(double value, UnitSystem unitSystem) + public RotationalStiffness(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -166,7 +166,10 @@ public RotationalStiffness(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -189,169 +192,169 @@ public RotationalStiffness(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentinewtonMetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMeterPerDegree); + public QuantityValue CentinewtonMetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); + public QuantityValue CentinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); + public QuantityValue CentinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecanewtonMetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMeterPerDegree); + public QuantityValue DecanewtonMetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecanewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); + public QuantityValue DecanewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecanewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); + public QuantityValue DecanewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecinewtonMetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMeterPerDegree); + public QuantityValue DecinewtonMetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); + public QuantityValue DecinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); + public QuantityValue DecinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonMetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMeterPerDegree); + public QuantityValue KilonewtonMetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonMetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); + public QuantityValue KilonewtonMetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); + public QuantityValue KilonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); + public QuantityValue KilonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundForceFeetPerDegrees => As(RotationalStiffnessUnit.KilopoundForceFootPerDegrees); + public QuantityValue KilopoundForceFeetPerDegrees => As(RotationalStiffnessUnit.KilopoundForceFootPerDegrees); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonMetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMeterPerDegree); + public QuantityValue MeganewtonMetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonMetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); + public QuantityValue MeganewtonMetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); + public QuantityValue MeganewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); + public QuantityValue MeganewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicronewtonMetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMeterPerDegree); + public QuantityValue MicronewtonMetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicronewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); + public QuantityValue MicronewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicronewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); + public QuantityValue MicronewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillinewtonMetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMeterPerDegree); + public QuantityValue MillinewtonMetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); + public QuantityValue MillinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); + public QuantityValue MillinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanonewtonMetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMeterPerDegree); + public QuantityValue NanonewtonMetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); + public QuantityValue NanonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); + public QuantityValue NanonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonMetersPerDegree => As(RotationalStiffnessUnit.NewtonMeterPerDegree); + public QuantityValue NewtonMetersPerDegree => As(RotationalStiffnessUnit.NewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonMetersPerRadian => As(RotationalStiffnessUnit.NewtonMeterPerRadian); + public QuantityValue NewtonMetersPerRadian => As(RotationalStiffnessUnit.NewtonMeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NewtonMillimeterPerDegree); + public QuantityValue NewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NewtonMillimeterPerRadian); + public QuantityValue NewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundForceFeetPerRadian => As(RotationalStiffnessUnit.PoundForceFeetPerRadian); + public QuantityValue PoundForceFeetPerRadian => As(RotationalStiffnessUnit.PoundForceFeetPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundForceFeetPerDegrees => As(RotationalStiffnessUnit.PoundForceFootPerDegrees); + public QuantityValue PoundForceFeetPerDegrees => As(RotationalStiffnessUnit.PoundForceFootPerDegrees); #endregion @@ -503,7 +506,7 @@ public static string GetAbbreviation(RotationalStiffnessUnit unit, IFormatProvid /// If value is NaN or Infinity. public static RotationalStiffness FromCentinewtonMetersPerDegree(QuantityValue centinewtonmetersperdegree) { - double value = (double) centinewtonmetersperdegree; + QuantityValue value = (QuantityValue) centinewtonmetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMeterPerDegree); } @@ -513,7 +516,7 @@ public static RotationalStiffness FromCentinewtonMetersPerDegree(QuantityValue c /// If value is NaN or Infinity. public static RotationalStiffness FromCentinewtonMillimetersPerDegree(QuantityValue centinewtonmillimetersperdegree) { - double value = (double) centinewtonmillimetersperdegree; + QuantityValue value = (QuantityValue) centinewtonmillimetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); } @@ -523,7 +526,7 @@ public static RotationalStiffness FromCentinewtonMillimetersPerDegree(QuantityVa /// If value is NaN or Infinity. public static RotationalStiffness FromCentinewtonMillimetersPerRadian(QuantityValue centinewtonmillimetersperradian) { - double value = (double) centinewtonmillimetersperradian; + QuantityValue value = (QuantityValue) centinewtonmillimetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); } @@ -533,7 +536,7 @@ public static RotationalStiffness FromCentinewtonMillimetersPerRadian(QuantityVa /// If value is NaN or Infinity. public static RotationalStiffness FromDecanewtonMetersPerDegree(QuantityValue decanewtonmetersperdegree) { - double value = (double) decanewtonmetersperdegree; + QuantityValue value = (QuantityValue) decanewtonmetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMeterPerDegree); } @@ -543,7 +546,7 @@ public static RotationalStiffness FromDecanewtonMetersPerDegree(QuantityValue de /// If value is NaN or Infinity. public static RotationalStiffness FromDecanewtonMillimetersPerDegree(QuantityValue decanewtonmillimetersperdegree) { - double value = (double) decanewtonmillimetersperdegree; + QuantityValue value = (QuantityValue) decanewtonmillimetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); } @@ -553,7 +556,7 @@ public static RotationalStiffness FromDecanewtonMillimetersPerDegree(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromDecanewtonMillimetersPerRadian(QuantityValue decanewtonmillimetersperradian) { - double value = (double) decanewtonmillimetersperradian; + QuantityValue value = (QuantityValue) decanewtonmillimetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); } @@ -563,7 +566,7 @@ public static RotationalStiffness FromDecanewtonMillimetersPerRadian(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromDecinewtonMetersPerDegree(QuantityValue decinewtonmetersperdegree) { - double value = (double) decinewtonmetersperdegree; + QuantityValue value = (QuantityValue) decinewtonmetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMeterPerDegree); } @@ -573,7 +576,7 @@ public static RotationalStiffness FromDecinewtonMetersPerDegree(QuantityValue de /// If value is NaN or Infinity. public static RotationalStiffness FromDecinewtonMillimetersPerDegree(QuantityValue decinewtonmillimetersperdegree) { - double value = (double) decinewtonmillimetersperdegree; + QuantityValue value = (QuantityValue) decinewtonmillimetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); } @@ -583,7 +586,7 @@ public static RotationalStiffness FromDecinewtonMillimetersPerDegree(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromDecinewtonMillimetersPerRadian(QuantityValue decinewtonmillimetersperradian) { - double value = (double) decinewtonmillimetersperradian; + QuantityValue value = (QuantityValue) decinewtonmillimetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); } @@ -593,7 +596,7 @@ public static RotationalStiffness FromDecinewtonMillimetersPerRadian(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromKilonewtonMetersPerDegree(QuantityValue kilonewtonmetersperdegree) { - double value = (double) kilonewtonmetersperdegree; + QuantityValue value = (QuantityValue) kilonewtonmetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerDegree); } @@ -603,7 +606,7 @@ public static RotationalStiffness FromKilonewtonMetersPerDegree(QuantityValue ki /// If value is NaN or Infinity. public static RotationalStiffness FromKilonewtonMetersPerRadian(QuantityValue kilonewtonmetersperradian) { - double value = (double) kilonewtonmetersperradian; + QuantityValue value = (QuantityValue) kilonewtonmetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); } @@ -613,7 +616,7 @@ public static RotationalStiffness FromKilonewtonMetersPerRadian(QuantityValue ki /// If value is NaN or Infinity. public static RotationalStiffness FromKilonewtonMillimetersPerDegree(QuantityValue kilonewtonmillimetersperdegree) { - double value = (double) kilonewtonmillimetersperdegree; + QuantityValue value = (QuantityValue) kilonewtonmillimetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); } @@ -623,7 +626,7 @@ public static RotationalStiffness FromKilonewtonMillimetersPerDegree(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromKilonewtonMillimetersPerRadian(QuantityValue kilonewtonmillimetersperradian) { - double value = (double) kilonewtonmillimetersperradian; + QuantityValue value = (QuantityValue) kilonewtonmillimetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); } @@ -633,7 +636,7 @@ public static RotationalStiffness FromKilonewtonMillimetersPerRadian(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromKilopoundForceFeetPerDegrees(QuantityValue kilopoundforcefeetperdegrees) { - double value = (double) kilopoundforcefeetperdegrees; + QuantityValue value = (QuantityValue) kilopoundforcefeetperdegrees; return new RotationalStiffness(value, RotationalStiffnessUnit.KilopoundForceFootPerDegrees); } @@ -643,7 +646,7 @@ public static RotationalStiffness FromKilopoundForceFeetPerDegrees(QuantityValue /// If value is NaN or Infinity. public static RotationalStiffness FromMeganewtonMetersPerDegree(QuantityValue meganewtonmetersperdegree) { - double value = (double) meganewtonmetersperdegree; + QuantityValue value = (QuantityValue) meganewtonmetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerDegree); } @@ -653,7 +656,7 @@ public static RotationalStiffness FromMeganewtonMetersPerDegree(QuantityValue me /// If value is NaN or Infinity. public static RotationalStiffness FromMeganewtonMetersPerRadian(QuantityValue meganewtonmetersperradian) { - double value = (double) meganewtonmetersperradian; + QuantityValue value = (QuantityValue) meganewtonmetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); } @@ -663,7 +666,7 @@ public static RotationalStiffness FromMeganewtonMetersPerRadian(QuantityValue me /// If value is NaN or Infinity. public static RotationalStiffness FromMeganewtonMillimetersPerDegree(QuantityValue meganewtonmillimetersperdegree) { - double value = (double) meganewtonmillimetersperdegree; + QuantityValue value = (QuantityValue) meganewtonmillimetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); } @@ -673,7 +676,7 @@ public static RotationalStiffness FromMeganewtonMillimetersPerDegree(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromMeganewtonMillimetersPerRadian(QuantityValue meganewtonmillimetersperradian) { - double value = (double) meganewtonmillimetersperradian; + QuantityValue value = (QuantityValue) meganewtonmillimetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); } @@ -683,7 +686,7 @@ public static RotationalStiffness FromMeganewtonMillimetersPerRadian(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromMicronewtonMetersPerDegree(QuantityValue micronewtonmetersperdegree) { - double value = (double) micronewtonmetersperdegree; + QuantityValue value = (QuantityValue) micronewtonmetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMeterPerDegree); } @@ -693,7 +696,7 @@ public static RotationalStiffness FromMicronewtonMetersPerDegree(QuantityValue m /// If value is NaN or Infinity. public static RotationalStiffness FromMicronewtonMillimetersPerDegree(QuantityValue micronewtonmillimetersperdegree) { - double value = (double) micronewtonmillimetersperdegree; + QuantityValue value = (QuantityValue) micronewtonmillimetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); } @@ -703,7 +706,7 @@ public static RotationalStiffness FromMicronewtonMillimetersPerDegree(QuantityVa /// If value is NaN or Infinity. public static RotationalStiffness FromMicronewtonMillimetersPerRadian(QuantityValue micronewtonmillimetersperradian) { - double value = (double) micronewtonmillimetersperradian; + QuantityValue value = (QuantityValue) micronewtonmillimetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); } @@ -713,7 +716,7 @@ public static RotationalStiffness FromMicronewtonMillimetersPerRadian(QuantityVa /// If value is NaN or Infinity. public static RotationalStiffness FromMillinewtonMetersPerDegree(QuantityValue millinewtonmetersperdegree) { - double value = (double) millinewtonmetersperdegree; + QuantityValue value = (QuantityValue) millinewtonmetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMeterPerDegree); } @@ -723,7 +726,7 @@ public static RotationalStiffness FromMillinewtonMetersPerDegree(QuantityValue m /// If value is NaN or Infinity. public static RotationalStiffness FromMillinewtonMillimetersPerDegree(QuantityValue millinewtonmillimetersperdegree) { - double value = (double) millinewtonmillimetersperdegree; + QuantityValue value = (QuantityValue) millinewtonmillimetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); } @@ -733,7 +736,7 @@ public static RotationalStiffness FromMillinewtonMillimetersPerDegree(QuantityVa /// If value is NaN or Infinity. public static RotationalStiffness FromMillinewtonMillimetersPerRadian(QuantityValue millinewtonmillimetersperradian) { - double value = (double) millinewtonmillimetersperradian; + QuantityValue value = (QuantityValue) millinewtonmillimetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); } @@ -743,7 +746,7 @@ public static RotationalStiffness FromMillinewtonMillimetersPerRadian(QuantityVa /// If value is NaN or Infinity. public static RotationalStiffness FromNanonewtonMetersPerDegree(QuantityValue nanonewtonmetersperdegree) { - double value = (double) nanonewtonmetersperdegree; + QuantityValue value = (QuantityValue) nanonewtonmetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMeterPerDegree); } @@ -753,7 +756,7 @@ public static RotationalStiffness FromNanonewtonMetersPerDegree(QuantityValue na /// If value is NaN or Infinity. public static RotationalStiffness FromNanonewtonMillimetersPerDegree(QuantityValue nanonewtonmillimetersperdegree) { - double value = (double) nanonewtonmillimetersperdegree; + QuantityValue value = (QuantityValue) nanonewtonmillimetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); } @@ -763,7 +766,7 @@ public static RotationalStiffness FromNanonewtonMillimetersPerDegree(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromNanonewtonMillimetersPerRadian(QuantityValue nanonewtonmillimetersperradian) { - double value = (double) nanonewtonmillimetersperradian; + QuantityValue value = (QuantityValue) nanonewtonmillimetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); } @@ -773,7 +776,7 @@ public static RotationalStiffness FromNanonewtonMillimetersPerRadian(QuantityVal /// If value is NaN or Infinity. public static RotationalStiffness FromNewtonMetersPerDegree(QuantityValue newtonmetersperdegree) { - double value = (double) newtonmetersperdegree; + QuantityValue value = (QuantityValue) newtonmetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerDegree); } @@ -783,7 +786,7 @@ public static RotationalStiffness FromNewtonMetersPerDegree(QuantityValue newton /// If value is NaN or Infinity. public static RotationalStiffness FromNewtonMetersPerRadian(QuantityValue newtonmetersperradian) { - double value = (double) newtonmetersperradian; + QuantityValue value = (QuantityValue) newtonmetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerRadian); } @@ -793,7 +796,7 @@ public static RotationalStiffness FromNewtonMetersPerRadian(QuantityValue newton /// If value is NaN or Infinity. public static RotationalStiffness FromNewtonMillimetersPerDegree(QuantityValue newtonmillimetersperdegree) { - double value = (double) newtonmillimetersperdegree; + QuantityValue value = (QuantityValue) newtonmillimetersperdegree; return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMillimeterPerDegree); } @@ -803,7 +806,7 @@ public static RotationalStiffness FromNewtonMillimetersPerDegree(QuantityValue n /// If value is NaN or Infinity. public static RotationalStiffness FromNewtonMillimetersPerRadian(QuantityValue newtonmillimetersperradian) { - double value = (double) newtonmillimetersperradian; + QuantityValue value = (QuantityValue) newtonmillimetersperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMillimeterPerRadian); } @@ -813,7 +816,7 @@ public static RotationalStiffness FromNewtonMillimetersPerRadian(QuantityValue n /// If value is NaN or Infinity. public static RotationalStiffness FromPoundForceFeetPerRadian(QuantityValue poundforcefeetperradian) { - double value = (double) poundforcefeetperradian; + QuantityValue value = (QuantityValue) poundforcefeetperradian; return new RotationalStiffness(value, RotationalStiffnessUnit.PoundForceFeetPerRadian); } @@ -823,7 +826,7 @@ public static RotationalStiffness FromPoundForceFeetPerRadian(QuantityValue poun /// If value is NaN or Infinity. public static RotationalStiffness FromPoundForceFeetPerDegrees(QuantityValue poundforcefeetperdegrees) { - double value = (double) poundforcefeetperdegrees; + QuantityValue value = (QuantityValue) poundforcefeetperdegrees; return new RotationalStiffness(value, RotationalStiffnessUnit.PoundForceFootPerDegrees); } @@ -835,7 +838,7 @@ public static RotationalStiffness FromPoundForceFeetPerDegrees(QuantityValue pou /// RotationalStiffness unit value. public static RotationalStiffness From(QuantityValue value, RotationalStiffnessUnit fromUnit) { - return new RotationalStiffness((double)value, fromUnit); + return new RotationalStiffness((QuantityValue)value, fromUnit); } #endregion @@ -1005,25 +1008,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat } /// Get from multiplying value and . - public static RotationalStiffness operator *(double left, RotationalStiffness right) + public static RotationalStiffness operator *(QuantityValue left, RotationalStiffness right) { return new RotationalStiffness(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static RotationalStiffness operator *(RotationalStiffness left, double right) + public static RotationalStiffness operator *(RotationalStiffness left, QuantityValue right) { return new RotationalStiffness(left.Value * right, left.Unit); } /// Get from dividing by value. - public static RotationalStiffness operator /(RotationalStiffness left, double right) + public static RotationalStiffness operator /(RotationalStiffness left, QuantityValue right) { return new RotationalStiffness(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(RotationalStiffness left, RotationalStiffness right) + public static QuantityValue operator /(RotationalStiffness left, RotationalStiffness right) { return left.NewtonMetersPerRadian / right.NewtonMetersPerRadian; } @@ -1056,6 +1059,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(RotationalStiffness left, RotationalStiffness right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(RotationalStiffness left, RotationalStiffness right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1068,7 +1084,29 @@ public int CompareTo(object obj) /// public int CompareTo(RotationalStiffness other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is RotationalStiffness objRotationalStiffness)) + return false; + return Equals(objRotationalStiffness); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(RotationalStiffness other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1111,13 +1149,13 @@ public int CompareTo(RotationalStiffness other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalStiffness other, double tolerance, ComparisonType comparisonType) + public bool Equals(RotationalStiffness other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1128,7 +1166,7 @@ public bool Equals(RotationalStiffness other, double tolerance, ComparisonType c /// A hash code for the current RotationalStiffness. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1139,17 +1177,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(RotationalStiffnessUnit unit) + public QuantityValue As(RotationalStiffnessUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1164,12 +1201,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is RotationalStiffnessUnit unitAsRotationalStiffnessUnit)) + if (!(unit is RotationalStiffnessUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessUnit)} is supported.", nameof(unit)); - return As(unitAsRotationalStiffnessUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1201,7 +1238,7 @@ public RotationalStiffness ToUnit(RotationalStiffnessUnit unit, UnitConverter un var converted = conversionFunction(this); return (RotationalStiffness)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(RotationalStiffnessUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1209,17 +1246,17 @@ public RotationalStiffness ToUnit(RotationalStiffnessUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RotationalStiffnessUnit unitAsRotationalStiffnessUnit)) + if (!(unit is RotationalStiffnessUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRotationalStiffnessUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1246,10 +1283,10 @@ public RotationalStiffness ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(RotationalStiffnessUnit unit) + private QuantityValue GetValueAs(RotationalStiffnessUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs index 603b45d53a..891a7f8e9d 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// [DataContract] - public partial struct RotationalStiffnessPerLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct RotationalStiffnessPerLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -76,9 +76,9 @@ static RotationalStiffnessPerLength() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public RotationalStiffnessPerLength(double value, RotationalStiffnessPerLengthUnit unit) + public RotationalStiffnessPerLength(QuantityValue value, RotationalStiffnessPerLengthUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -90,14 +90,14 @@ public RotationalStiffnessPerLength(double value, RotationalStiffnessPerLengthUn /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) + public RotationalStiffnessPerLength(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -138,7 +138,10 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -161,29 +164,29 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + public QuantityValue KilonewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); + public QuantityValue KilopoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + public QuantityValue MeganewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); + public QuantityValue NewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); + public QuantityValue PoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); #endregion @@ -251,7 +254,7 @@ public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, IFor /// If value is NaN or Infinity. public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(QuantityValue kilonewtonmetersperradianpermeter) { - double value = (double) kilonewtonmetersperradianpermeter; + QuantityValue value = (QuantityValue) kilonewtonmetersperradianpermeter; return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); } @@ -261,7 +264,7 @@ public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter /// If value is NaN or Infinity. public static RotationalStiffnessPerLength FromKilopoundForceFeetPerDegreesPerFeet(QuantityValue kilopoundforcefeetperdegreesperfeet) { - double value = (double) kilopoundforcefeetperdegreesperfeet; + QuantityValue value = (QuantityValue) kilopoundforcefeetperdegreesperfeet; return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); } @@ -271,7 +274,7 @@ public static RotationalStiffnessPerLength FromKilopoundForceFeetPerDegreesPerFe /// If value is NaN or Infinity. public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(QuantityValue meganewtonmetersperradianpermeter) { - double value = (double) meganewtonmetersperradianpermeter; + QuantityValue value = (QuantityValue) meganewtonmetersperradianpermeter; return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); } @@ -281,7 +284,7 @@ public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter /// If value is NaN or Infinity. public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(QuantityValue newtonmetersperradianpermeter) { - double value = (double) newtonmetersperradianpermeter; + QuantityValue value = (QuantityValue) newtonmetersperradianpermeter; return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); } @@ -291,7 +294,7 @@ public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(Qua /// If value is NaN or Infinity. public static RotationalStiffnessPerLength FromPoundForceFeetPerDegreesPerFeet(QuantityValue poundforcefeetperdegreesperfeet) { - double value = (double) poundforcefeetperdegreesperfeet; + QuantityValue value = (QuantityValue) poundforcefeetperdegreesperfeet; return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); } @@ -303,7 +306,7 @@ public static RotationalStiffnessPerLength FromPoundForceFeetPerDegreesPerFeet(Q /// RotationalStiffnessPerLength unit value. public static RotationalStiffnessPerLength From(QuantityValue value, RotationalStiffnessPerLengthUnit fromUnit) { - return new RotationalStiffnessPerLength((double)value, fromUnit); + return new RotationalStiffnessPerLength((QuantityValue)value, fromUnit); } #endregion @@ -473,25 +476,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat } /// Get from multiplying value and . - public static RotationalStiffnessPerLength operator *(double left, RotationalStiffnessPerLength right) + public static RotationalStiffnessPerLength operator *(QuantityValue left, RotationalStiffnessPerLength right) { return new RotationalStiffnessPerLength(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static RotationalStiffnessPerLength operator *(RotationalStiffnessPerLength left, double right) + public static RotationalStiffnessPerLength operator *(RotationalStiffnessPerLength left, QuantityValue right) { return new RotationalStiffnessPerLength(left.Value * right, left.Unit); } /// Get from dividing by value. - public static RotationalStiffnessPerLength operator /(RotationalStiffnessPerLength left, double right) + public static RotationalStiffnessPerLength operator /(RotationalStiffnessPerLength left, QuantityValue right) { return new RotationalStiffnessPerLength(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + public static QuantityValue operator /(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { return left.NewtonMetersPerRadianPerMeter / right.NewtonMetersPerRadianPerMeter; } @@ -524,6 +527,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -536,7 +552,29 @@ public int CompareTo(object obj) /// public int CompareTo(RotationalStiffnessPerLength other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is RotationalStiffnessPerLength objRotationalStiffnessPerLength)) + return false; + return Equals(objRotationalStiffnessPerLength); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(RotationalStiffnessPerLength other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -579,13 +617,13 @@ public int CompareTo(RotationalStiffnessPerLength other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalStiffnessPerLength other, double tolerance, ComparisonType comparisonType) + public bool Equals(RotationalStiffnessPerLength other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -596,7 +634,7 @@ public bool Equals(RotationalStiffnessPerLength other, double tolerance, Compari /// A hash code for the current RotationalStiffnessPerLength. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -607,17 +645,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(RotationalStiffnessPerLengthUnit unit) + public QuantityValue As(RotationalStiffnessPerLengthUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -632,12 +669,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is RotationalStiffnessPerLengthUnit unitAsRotationalStiffnessPerLengthUnit)) + if (!(unit is RotationalStiffnessPerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessPerLengthUnit)} is supported.", nameof(unit)); - return As(unitAsRotationalStiffnessPerLengthUnit); + return (QuantityValue)As(typedUnit); } /// @@ -669,7 +706,7 @@ public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit var converted = conversionFunction(this); return (RotationalStiffnessPerLength)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(RotationalStiffnessPerLengthUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -677,17 +714,17 @@ public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RotationalStiffnessPerLengthUnit unitAsRotationalStiffnessPerLengthUnit)) + if (!(unit is RotationalStiffnessPerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessPerLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsRotationalStiffnessPerLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -714,10 +751,10 @@ public RotationalStiffnessPerLength ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(RotationalStiffnessPerLengthUnit unit) + private QuantityValue GetValueAs(RotationalStiffnessPerLengthUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs index 4b70a95229..f6d4428b4a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// A way of representing a number of items. /// [DataContract] - public partial struct Scalar : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Scalar : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -72,9 +72,9 @@ static Scalar() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Scalar(double value, ScalarUnit unit) + public Scalar(QuantityValue value, ScalarUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -86,14 +86,14 @@ public Scalar(double value, ScalarUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Scalar(double value, UnitSystem unitSystem) + public Scalar(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -134,7 +134,10 @@ public Scalar(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -157,9 +160,9 @@ public Scalar(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Amount => As(ScalarUnit.Amount); + public QuantityValue Amount => As(ScalarUnit.Amount); #endregion @@ -215,7 +218,7 @@ public static string GetAbbreviation(ScalarUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Scalar FromAmount(QuantityValue amount) { - double value = (double) amount; + QuantityValue value = (QuantityValue) amount; return new Scalar(value, ScalarUnit.Amount); } @@ -227,7 +230,7 @@ public static Scalar FromAmount(QuantityValue amount) /// Scalar unit value. public static Scalar From(QuantityValue value, ScalarUnit fromUnit) { - return new Scalar((double)value, fromUnit); + return new Scalar((QuantityValue)value, fromUnit); } #endregion @@ -397,25 +400,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Scala } /// Get from multiplying value and . - public static Scalar operator *(double left, Scalar right) + public static Scalar operator *(QuantityValue left, Scalar right) { return new Scalar(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Scalar operator *(Scalar left, double right) + public static Scalar operator *(Scalar left, QuantityValue right) { return new Scalar(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Scalar operator /(Scalar left, double right) + public static Scalar operator /(Scalar left, QuantityValue right) { return new Scalar(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Scalar left, Scalar right) + public static QuantityValue operator /(Scalar left, Scalar right) { return left.Amount / right.Amount; } @@ -448,6 +451,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Scala return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Scalar left, Scalar right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Scalar left, Scalar right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -460,7 +476,29 @@ public int CompareTo(object obj) /// public int CompareTo(Scalar other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Scalar objScalar)) + return false; + return Equals(objScalar); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Scalar other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -503,13 +541,13 @@ public int CompareTo(Scalar other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Scalar other, double tolerance, ComparisonType comparisonType) + public bool Equals(Scalar other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -520,7 +558,7 @@ public bool Equals(Scalar other, double tolerance, ComparisonType comparisonType /// A hash code for the current Scalar. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -531,17 +569,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ScalarUnit unit) + public QuantityValue As(ScalarUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -556,12 +593,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ScalarUnit unitAsScalarUnit)) + if (!(unit is ScalarUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); - return As(unitAsScalarUnit); + return (QuantityValue)As(typedUnit); } /// @@ -593,7 +630,7 @@ public Scalar ToUnit(ScalarUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Scalar)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ScalarUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -601,17 +638,17 @@ public Scalar ToUnit(ScalarUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ScalarUnit unitAsScalarUnit)) + if (!(unit is ScalarUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsScalarUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -638,10 +675,10 @@ public Scalar ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ScalarUnit unit) + private QuantityValue GetValueAs(ScalarUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs index 9a4b65cb3d..dd664f80ca 100644 --- a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Solid_angle /// [DataContract] - public partial struct SolidAngle : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct SolidAngle : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static SolidAngle() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public SolidAngle(double value, SolidAngleUnit unit) + public SolidAngle(QuantityValue value, SolidAngleUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public SolidAngle(double value, SolidAngleUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public SolidAngle(double value, UnitSystem unitSystem) + public SolidAngle(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public SolidAngle(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public SolidAngle(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Steradians => As(SolidAngleUnit.Steradian); + public QuantityValue Steradians => As(SolidAngleUnit.Steradian); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(SolidAngleUnit unit, IFormatProvider? provi /// If value is NaN or Infinity. public static SolidAngle FromSteradians(QuantityValue steradians) { - double value = (double) steradians; + QuantityValue value = (QuantityValue) steradians; return new SolidAngle(value, SolidAngleUnit.Steradian); } @@ -230,7 +233,7 @@ public static SolidAngle FromSteradians(QuantityValue steradians) /// SolidAngle unit value. public static SolidAngle From(QuantityValue value, SolidAngleUnit fromUnit) { - return new SolidAngle((double)value, fromUnit); + return new SolidAngle((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Solid } /// Get from multiplying value and . - public static SolidAngle operator *(double left, SolidAngle right) + public static SolidAngle operator *(QuantityValue left, SolidAngle right) { return new SolidAngle(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static SolidAngle operator *(SolidAngle left, double right) + public static SolidAngle operator *(SolidAngle left, QuantityValue right) { return new SolidAngle(left.Value * right, left.Unit); } /// Get from dividing by value. - public static SolidAngle operator /(SolidAngle left, double right) + public static SolidAngle operator /(SolidAngle left, QuantityValue right) { return new SolidAngle(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(SolidAngle left, SolidAngle right) + public static QuantityValue operator /(SolidAngle left, SolidAngle right) { return left.Steradians / right.Steradians; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Solid return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(SolidAngle left, SolidAngle right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(SolidAngle left, SolidAngle right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(SolidAngle other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is SolidAngle objSolidAngle)) + return false; + return Equals(objSolidAngle); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(SolidAngle other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(SolidAngle other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SolidAngle other, double tolerance, ComparisonType comparisonType) + public bool Equals(SolidAngle other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(SolidAngle other, double tolerance, ComparisonType comparison /// A hash code for the current SolidAngle. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(SolidAngleUnit unit) + public QuantityValue As(SolidAngleUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is SolidAngleUnit unitAsSolidAngleUnit)) + if (!(unit is SolidAngleUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SolidAngleUnit)} is supported.", nameof(unit)); - return As(unitAsSolidAngleUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public SolidAngle ToUnit(SolidAngleUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (SolidAngle)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(SolidAngleUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public SolidAngle ToUnit(SolidAngleUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SolidAngleUnit unitAsSolidAngleUnit)) + if (!(unit is SolidAngleUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SolidAngleUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSolidAngleUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public SolidAngle ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(SolidAngleUnit unit) + private QuantityValue GetValueAs(SolidAngleUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs index 454fa20918..e5f236b1cc 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Specific_energy /// [DataContract] - public partial struct SpecificEnergy : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct SpecificEnergy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -103,9 +103,9 @@ static SpecificEnergy() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public SpecificEnergy(double value, SpecificEnergyUnit unit) + public SpecificEnergy(QuantityValue value, SpecificEnergyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -117,14 +117,14 @@ public SpecificEnergy(double value, SpecificEnergyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public SpecificEnergy(double value, UnitSystem unitSystem) + public SpecificEnergy(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -165,7 +165,10 @@ public SpecificEnergy(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -188,149 +191,149 @@ public SpecificEnergy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BtuPerPound => As(SpecificEnergyUnit.BtuPerPound); + public QuantityValue BtuPerPound => As(SpecificEnergyUnit.BtuPerPound); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); + public QuantityValue CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattDaysPerKilogram => As(SpecificEnergyUnit.GigawattDayPerKilogram); + public QuantityValue GigawattDaysPerKilogram => As(SpecificEnergyUnit.GigawattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattDaysPerShortTon => As(SpecificEnergyUnit.GigawattDayPerShortTon); + public QuantityValue GigawattDaysPerShortTon => As(SpecificEnergyUnit.GigawattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattDaysPerTonne => As(SpecificEnergyUnit.GigawattDayPerTonne); + public QuantityValue GigawattDaysPerTonne => As(SpecificEnergyUnit.GigawattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattHoursPerKilogram => As(SpecificEnergyUnit.GigawattHourPerKilogram); + public QuantityValue GigawattHoursPerKilogram => As(SpecificEnergyUnit.GigawattHourPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GigawattHoursPerPound => As(SpecificEnergyUnit.GigawattHourPerPound); + public QuantityValue GigawattHoursPerPound => As(SpecificEnergyUnit.GigawattHourPerPound); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); + public QuantityValue JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); + public QuantityValue KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); + public QuantityValue KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattDaysPerKilogram => As(SpecificEnergyUnit.KilowattDayPerKilogram); + public QuantityValue KilowattDaysPerKilogram => As(SpecificEnergyUnit.KilowattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattDaysPerShortTon => As(SpecificEnergyUnit.KilowattDayPerShortTon); + public QuantityValue KilowattDaysPerShortTon => As(SpecificEnergyUnit.KilowattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattDaysPerTonne => As(SpecificEnergyUnit.KilowattDayPerTonne); + public QuantityValue KilowattDaysPerTonne => As(SpecificEnergyUnit.KilowattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); + public QuantityValue KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilowattHoursPerPound => As(SpecificEnergyUnit.KilowattHourPerPound); + public QuantityValue KilowattHoursPerPound => As(SpecificEnergyUnit.KilowattHourPerPound); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); + public QuantityValue MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattDaysPerKilogram => As(SpecificEnergyUnit.MegawattDayPerKilogram); + public QuantityValue MegawattDaysPerKilogram => As(SpecificEnergyUnit.MegawattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattDaysPerShortTon => As(SpecificEnergyUnit.MegawattDayPerShortTon); + public QuantityValue MegawattDaysPerShortTon => As(SpecificEnergyUnit.MegawattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattDaysPerTonne => As(SpecificEnergyUnit.MegawattDayPerTonne); + public QuantityValue MegawattDaysPerTonne => As(SpecificEnergyUnit.MegawattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); + public QuantityValue MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegawattHoursPerPound => As(SpecificEnergyUnit.MegawattHourPerPound); + public QuantityValue MegawattHoursPerPound => As(SpecificEnergyUnit.MegawattHourPerPound); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerawattDaysPerKilogram => As(SpecificEnergyUnit.TerawattDayPerKilogram); + public QuantityValue TerawattDaysPerKilogram => As(SpecificEnergyUnit.TerawattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerawattDaysPerShortTon => As(SpecificEnergyUnit.TerawattDayPerShortTon); + public QuantityValue TerawattDaysPerShortTon => As(SpecificEnergyUnit.TerawattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TerawattDaysPerTonne => As(SpecificEnergyUnit.TerawattDayPerTonne); + public QuantityValue TerawattDaysPerTonne => As(SpecificEnergyUnit.TerawattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattDaysPerKilogram => As(SpecificEnergyUnit.WattDayPerKilogram); + public QuantityValue WattDaysPerKilogram => As(SpecificEnergyUnit.WattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattDaysPerShortTon => As(SpecificEnergyUnit.WattDayPerShortTon); + public QuantityValue WattDaysPerShortTon => As(SpecificEnergyUnit.WattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattDaysPerTonne => As(SpecificEnergyUnit.WattDayPerTonne); + public QuantityValue WattDaysPerTonne => As(SpecificEnergyUnit.WattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); + public QuantityValue WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattHoursPerPound => As(SpecificEnergyUnit.WattHourPerPound); + public QuantityValue WattHoursPerPound => As(SpecificEnergyUnit.WattHourPerPound); #endregion @@ -470,7 +473,7 @@ public static string GetAbbreviation(SpecificEnergyUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static SpecificEnergy FromBtuPerPound(QuantityValue btuperpound) { - double value = (double) btuperpound; + QuantityValue value = (QuantityValue) btuperpound; return new SpecificEnergy(value, SpecificEnergyUnit.BtuPerPound); } @@ -480,7 +483,7 @@ public static SpecificEnergy FromBtuPerPound(QuantityValue btuperpound) /// If value is NaN or Infinity. public static SpecificEnergy FromCaloriesPerGram(QuantityValue caloriespergram) { - double value = (double) caloriespergram; + QuantityValue value = (QuantityValue) caloriespergram; return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); } @@ -490,7 +493,7 @@ public static SpecificEnergy FromCaloriesPerGram(QuantityValue caloriespergram) /// If value is NaN or Infinity. public static SpecificEnergy FromGigawattDaysPerKilogram(QuantityValue gigawattdaysperkilogram) { - double value = (double) gigawattdaysperkilogram; + QuantityValue value = (QuantityValue) gigawattdaysperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerKilogram); } @@ -500,7 +503,7 @@ public static SpecificEnergy FromGigawattDaysPerKilogram(QuantityValue gigawattd /// If value is NaN or Infinity. public static SpecificEnergy FromGigawattDaysPerShortTon(QuantityValue gigawattdayspershortton) { - double value = (double) gigawattdayspershortton; + QuantityValue value = (QuantityValue) gigawattdayspershortton; return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerShortTon); } @@ -510,7 +513,7 @@ public static SpecificEnergy FromGigawattDaysPerShortTon(QuantityValue gigawattd /// If value is NaN or Infinity. public static SpecificEnergy FromGigawattDaysPerTonne(QuantityValue gigawattdayspertonne) { - double value = (double) gigawattdayspertonne; + QuantityValue value = (QuantityValue) gigawattdayspertonne; return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerTonne); } @@ -520,7 +523,7 @@ public static SpecificEnergy FromGigawattDaysPerTonne(QuantityValue gigawattdays /// If value is NaN or Infinity. public static SpecificEnergy FromGigawattHoursPerKilogram(QuantityValue gigawatthoursperkilogram) { - double value = (double) gigawatthoursperkilogram; + QuantityValue value = (QuantityValue) gigawatthoursperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.GigawattHourPerKilogram); } @@ -530,7 +533,7 @@ public static SpecificEnergy FromGigawattHoursPerKilogram(QuantityValue gigawatt /// If value is NaN or Infinity. public static SpecificEnergy FromGigawattHoursPerPound(QuantityValue gigawatthoursperpound) { - double value = (double) gigawatthoursperpound; + QuantityValue value = (QuantityValue) gigawatthoursperpound; return new SpecificEnergy(value, SpecificEnergyUnit.GigawattHourPerPound); } @@ -540,7 +543,7 @@ public static SpecificEnergy FromGigawattHoursPerPound(QuantityValue gigawatthou /// If value is NaN or Infinity. public static SpecificEnergy FromJoulesPerKilogram(QuantityValue joulesperkilogram) { - double value = (double) joulesperkilogram; + QuantityValue value = (QuantityValue) joulesperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); } @@ -550,7 +553,7 @@ public static SpecificEnergy FromJoulesPerKilogram(QuantityValue joulesperkilogr /// If value is NaN or Infinity. public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue kilocaloriespergram) { - double value = (double) kilocaloriespergram; + QuantityValue value = (QuantityValue) kilocaloriespergram; return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); } @@ -560,7 +563,7 @@ public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue kilocaloriesp /// If value is NaN or Infinity. public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue kilojoulesperkilogram) { - double value = (double) kilojoulesperkilogram; + QuantityValue value = (QuantityValue) kilojoulesperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); } @@ -570,7 +573,7 @@ public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue kilojoulesp /// If value is NaN or Infinity. public static SpecificEnergy FromKilowattDaysPerKilogram(QuantityValue kilowattdaysperkilogram) { - double value = (double) kilowattdaysperkilogram; + QuantityValue value = (QuantityValue) kilowattdaysperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerKilogram); } @@ -580,7 +583,7 @@ public static SpecificEnergy FromKilowattDaysPerKilogram(QuantityValue kilowattd /// If value is NaN or Infinity. public static SpecificEnergy FromKilowattDaysPerShortTon(QuantityValue kilowattdayspershortton) { - double value = (double) kilowattdayspershortton; + QuantityValue value = (QuantityValue) kilowattdayspershortton; return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerShortTon); } @@ -590,7 +593,7 @@ public static SpecificEnergy FromKilowattDaysPerShortTon(QuantityValue kilowattd /// If value is NaN or Infinity. public static SpecificEnergy FromKilowattDaysPerTonne(QuantityValue kilowattdayspertonne) { - double value = (double) kilowattdayspertonne; + QuantityValue value = (QuantityValue) kilowattdayspertonne; return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerTonne); } @@ -600,7 +603,7 @@ public static SpecificEnergy FromKilowattDaysPerTonne(QuantityValue kilowattdays /// If value is NaN or Infinity. public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue kilowatthoursperkilogram) { - double value = (double) kilowatthoursperkilogram; + QuantityValue value = (QuantityValue) kilowatthoursperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); } @@ -610,7 +613,7 @@ public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue kilowatt /// If value is NaN or Infinity. public static SpecificEnergy FromKilowattHoursPerPound(QuantityValue kilowatthoursperpound) { - double value = (double) kilowatthoursperpound; + QuantityValue value = (QuantityValue) kilowatthoursperpound; return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerPound); } @@ -620,7 +623,7 @@ public static SpecificEnergy FromKilowattHoursPerPound(QuantityValue kilowatthou /// If value is NaN or Infinity. public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue megajoulesperkilogram) { - double value = (double) megajoulesperkilogram; + QuantityValue value = (QuantityValue) megajoulesperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); } @@ -630,7 +633,7 @@ public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue megajoulesp /// If value is NaN or Infinity. public static SpecificEnergy FromMegawattDaysPerKilogram(QuantityValue megawattdaysperkilogram) { - double value = (double) megawattdaysperkilogram; + QuantityValue value = (QuantityValue) megawattdaysperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerKilogram); } @@ -640,7 +643,7 @@ public static SpecificEnergy FromMegawattDaysPerKilogram(QuantityValue megawattd /// If value is NaN or Infinity. public static SpecificEnergy FromMegawattDaysPerShortTon(QuantityValue megawattdayspershortton) { - double value = (double) megawattdayspershortton; + QuantityValue value = (QuantityValue) megawattdayspershortton; return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerShortTon); } @@ -650,7 +653,7 @@ public static SpecificEnergy FromMegawattDaysPerShortTon(QuantityValue megawattd /// If value is NaN or Infinity. public static SpecificEnergy FromMegawattDaysPerTonne(QuantityValue megawattdayspertonne) { - double value = (double) megawattdayspertonne; + QuantityValue value = (QuantityValue) megawattdayspertonne; return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerTonne); } @@ -660,7 +663,7 @@ public static SpecificEnergy FromMegawattDaysPerTonne(QuantityValue megawattdays /// If value is NaN or Infinity. public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue megawatthoursperkilogram) { - double value = (double) megawatthoursperkilogram; + QuantityValue value = (QuantityValue) megawatthoursperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); } @@ -670,7 +673,7 @@ public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue megawatt /// If value is NaN or Infinity. public static SpecificEnergy FromMegawattHoursPerPound(QuantityValue megawatthoursperpound) { - double value = (double) megawatthoursperpound; + QuantityValue value = (QuantityValue) megawatthoursperpound; return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerPound); } @@ -680,7 +683,7 @@ public static SpecificEnergy FromMegawattHoursPerPound(QuantityValue megawatthou /// If value is NaN or Infinity. public static SpecificEnergy FromTerawattDaysPerKilogram(QuantityValue terawattdaysperkilogram) { - double value = (double) terawattdaysperkilogram; + QuantityValue value = (QuantityValue) terawattdaysperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerKilogram); } @@ -690,7 +693,7 @@ public static SpecificEnergy FromTerawattDaysPerKilogram(QuantityValue terawattd /// If value is NaN or Infinity. public static SpecificEnergy FromTerawattDaysPerShortTon(QuantityValue terawattdayspershortton) { - double value = (double) terawattdayspershortton; + QuantityValue value = (QuantityValue) terawattdayspershortton; return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerShortTon); } @@ -700,7 +703,7 @@ public static SpecificEnergy FromTerawattDaysPerShortTon(QuantityValue terawattd /// If value is NaN or Infinity. public static SpecificEnergy FromTerawattDaysPerTonne(QuantityValue terawattdayspertonne) { - double value = (double) terawattdayspertonne; + QuantityValue value = (QuantityValue) terawattdayspertonne; return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerTonne); } @@ -710,7 +713,7 @@ public static SpecificEnergy FromTerawattDaysPerTonne(QuantityValue terawattdays /// If value is NaN or Infinity. public static SpecificEnergy FromWattDaysPerKilogram(QuantityValue wattdaysperkilogram) { - double value = (double) wattdaysperkilogram; + QuantityValue value = (QuantityValue) wattdaysperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerKilogram); } @@ -720,7 +723,7 @@ public static SpecificEnergy FromWattDaysPerKilogram(QuantityValue wattdaysperki /// If value is NaN or Infinity. public static SpecificEnergy FromWattDaysPerShortTon(QuantityValue wattdayspershortton) { - double value = (double) wattdayspershortton; + QuantityValue value = (QuantityValue) wattdayspershortton; return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerShortTon); } @@ -730,7 +733,7 @@ public static SpecificEnergy FromWattDaysPerShortTon(QuantityValue wattdayspersh /// If value is NaN or Infinity. public static SpecificEnergy FromWattDaysPerTonne(QuantityValue wattdayspertonne) { - double value = (double) wattdayspertonne; + QuantityValue value = (QuantityValue) wattdayspertonne; return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerTonne); } @@ -740,7 +743,7 @@ public static SpecificEnergy FromWattDaysPerTonne(QuantityValue wattdayspertonne /// If value is NaN or Infinity. public static SpecificEnergy FromWattHoursPerKilogram(QuantityValue watthoursperkilogram) { - double value = (double) watthoursperkilogram; + QuantityValue value = (QuantityValue) watthoursperkilogram; return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerKilogram); } @@ -750,7 +753,7 @@ public static SpecificEnergy FromWattHoursPerKilogram(QuantityValue watthoursper /// If value is NaN or Infinity. public static SpecificEnergy FromWattHoursPerPound(QuantityValue watthoursperpound) { - double value = (double) watthoursperpound; + QuantityValue value = (QuantityValue) watthoursperpound; return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerPound); } @@ -762,7 +765,7 @@ public static SpecificEnergy FromWattHoursPerPound(QuantityValue watthoursperpou /// SpecificEnergy unit value. public static SpecificEnergy From(QuantityValue value, SpecificEnergyUnit fromUnit) { - return new SpecificEnergy((double)value, fromUnit); + return new SpecificEnergy((QuantityValue)value, fromUnit); } #endregion @@ -932,25 +935,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci } /// Get from multiplying value and . - public static SpecificEnergy operator *(double left, SpecificEnergy right) + public static SpecificEnergy operator *(QuantityValue left, SpecificEnergy right) { return new SpecificEnergy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static SpecificEnergy operator *(SpecificEnergy left, double right) + public static SpecificEnergy operator *(SpecificEnergy left, QuantityValue right) { return new SpecificEnergy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static SpecificEnergy operator /(SpecificEnergy left, double right) + public static SpecificEnergy operator /(SpecificEnergy left, QuantityValue right) { return new SpecificEnergy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(SpecificEnergy left, SpecificEnergy right) + public static QuantityValue operator /(SpecificEnergy left, SpecificEnergy right) { return left.JoulesPerKilogram / right.JoulesPerKilogram; } @@ -983,6 +986,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(SpecificEnergy left, SpecificEnergy right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(SpecificEnergy left, SpecificEnergy right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -995,7 +1011,29 @@ public int CompareTo(object obj) /// public int CompareTo(SpecificEnergy other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is SpecificEnergy objSpecificEnergy)) + return false; + return Equals(objSpecificEnergy); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(SpecificEnergy other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1038,13 +1076,13 @@ public int CompareTo(SpecificEnergy other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificEnergy other, double tolerance, ComparisonType comparisonType) + public bool Equals(SpecificEnergy other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1055,7 +1093,7 @@ public bool Equals(SpecificEnergy other, double tolerance, ComparisonType compar /// A hash code for the current SpecificEnergy. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1066,17 +1104,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(SpecificEnergyUnit unit) + public QuantityValue As(SpecificEnergyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1091,12 +1128,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is SpecificEnergyUnit unitAsSpecificEnergyUnit)) + if (!(unit is SpecificEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEnergyUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificEnergyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1128,7 +1165,7 @@ public SpecificEnergy ToUnit(SpecificEnergyUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (SpecificEnergy)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(SpecificEnergyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1136,17 +1173,17 @@ public SpecificEnergy ToUnit(SpecificEnergyUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificEnergyUnit unitAsSpecificEnergyUnit)) + if (!(unit is SpecificEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEnergyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1173,10 +1210,10 @@ public SpecificEnergy ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(SpecificEnergyUnit unit) + private QuantityValue GetValueAs(SpecificEnergyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs index 26c1ea1e6f..7e4bdf3c92 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass. /// [DataContract] - public partial struct SpecificEntropy : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct SpecificEntropy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -80,9 +80,9 @@ static SpecificEntropy() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public SpecificEntropy(double value, SpecificEntropyUnit unit) + public SpecificEntropy(QuantityValue value, SpecificEntropyUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -94,14 +94,14 @@ public SpecificEntropy(double value, SpecificEntropyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public SpecificEntropy(double value, UnitSystem unitSystem) + public SpecificEntropy(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -142,7 +142,10 @@ public SpecificEntropy(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -165,49 +168,49 @@ public SpecificEntropy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BtusPerPoundFahrenheit => As(SpecificEntropyUnit.BtuPerPoundFahrenheit); + public QuantityValue BtusPerPoundFahrenheit => As(SpecificEntropyUnit.BtuPerPoundFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); + public QuantityValue CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); + public QuantityValue JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); + public QuantityValue JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); + public QuantityValue KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + public QuantityValue KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); + public QuantityValue KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + public QuantityValue MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); + public QuantityValue MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); #endregion @@ -287,7 +290,7 @@ public static string GetAbbreviation(SpecificEntropyUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static SpecificEntropy FromBtusPerPoundFahrenheit(QuantityValue btusperpoundfahrenheit) { - double value = (double) btusperpoundfahrenheit; + QuantityValue value = (QuantityValue) btusperpoundfahrenheit; return new SpecificEntropy(value, SpecificEntropyUnit.BtuPerPoundFahrenheit); } @@ -297,7 +300,7 @@ public static SpecificEntropy FromBtusPerPoundFahrenheit(QuantityValue btusperpo /// If value is NaN or Infinity. public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue caloriespergramkelvin) { - double value = (double) caloriespergramkelvin; + QuantityValue value = (QuantityValue) caloriespergramkelvin; return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); } @@ -307,7 +310,7 @@ public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue caloriespe /// If value is NaN or Infinity. public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue joulesperkilogramdegreecelsius) { - double value = (double) joulesperkilogramdegreecelsius; + QuantityValue value = (QuantityValue) joulesperkilogramdegreecelsius; return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); } @@ -317,7 +320,7 @@ public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue j /// If value is NaN or Infinity. public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue joulesperkilogramkelvin) { - double value = (double) joulesperkilogramkelvin; + QuantityValue value = (QuantityValue) joulesperkilogramkelvin; return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); } @@ -327,7 +330,7 @@ public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue joulespe /// If value is NaN or Infinity. public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue kilocaloriespergramkelvin) { - double value = (double) kilocaloriespergramkelvin; + QuantityValue value = (QuantityValue) kilocaloriespergramkelvin; return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); } @@ -337,7 +340,7 @@ public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue kiloca /// If value is NaN or Infinity. public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityValue kilojoulesperkilogramdegreecelsius) { - double value = (double) kilojoulesperkilogramdegreecelsius; + QuantityValue value = (QuantityValue) kilojoulesperkilogramdegreecelsius; return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); } @@ -347,7 +350,7 @@ public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityVal /// If value is NaN or Infinity. public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue kilojoulesperkilogramkelvin) { - double value = (double) kilojoulesperkilogramkelvin; + QuantityValue value = (QuantityValue) kilojoulesperkilogramkelvin; return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); } @@ -357,7 +360,7 @@ public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue kilo /// If value is NaN or Infinity. public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityValue megajoulesperkilogramdegreecelsius) { - double value = (double) megajoulesperkilogramdegreecelsius; + QuantityValue value = (QuantityValue) megajoulesperkilogramdegreecelsius; return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); } @@ -367,7 +370,7 @@ public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityVal /// If value is NaN or Infinity. public static SpecificEntropy FromMegajoulesPerKilogramKelvin(QuantityValue megajoulesperkilogramkelvin) { - double value = (double) megajoulesperkilogramkelvin; + QuantityValue value = (QuantityValue) megajoulesperkilogramkelvin; return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramKelvin); } @@ -379,7 +382,7 @@ public static SpecificEntropy FromMegajoulesPerKilogramKelvin(QuantityValue mega /// SpecificEntropy unit value. public static SpecificEntropy From(QuantityValue value, SpecificEntropyUnit fromUnit) { - return new SpecificEntropy((double)value, fromUnit); + return new SpecificEntropy((QuantityValue)value, fromUnit); } #endregion @@ -549,25 +552,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci } /// Get from multiplying value and . - public static SpecificEntropy operator *(double left, SpecificEntropy right) + public static SpecificEntropy operator *(QuantityValue left, SpecificEntropy right) { return new SpecificEntropy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static SpecificEntropy operator *(SpecificEntropy left, double right) + public static SpecificEntropy operator *(SpecificEntropy left, QuantityValue right) { return new SpecificEntropy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static SpecificEntropy operator /(SpecificEntropy left, double right) + public static SpecificEntropy operator /(SpecificEntropy left, QuantityValue right) { return new SpecificEntropy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(SpecificEntropy left, SpecificEntropy right) + public static QuantityValue operator /(SpecificEntropy left, SpecificEntropy right) { return left.JoulesPerKilogramKelvin / right.JoulesPerKilogramKelvin; } @@ -600,6 +603,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(SpecificEntropy left, SpecificEntropy right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(SpecificEntropy left, SpecificEntropy right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -612,7 +628,29 @@ public int CompareTo(object obj) /// public int CompareTo(SpecificEntropy other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is SpecificEntropy objSpecificEntropy)) + return false; + return Equals(objSpecificEntropy); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(SpecificEntropy other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -655,13 +693,13 @@ public int CompareTo(SpecificEntropy other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificEntropy other, double tolerance, ComparisonType comparisonType) + public bool Equals(SpecificEntropy other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -672,7 +710,7 @@ public bool Equals(SpecificEntropy other, double tolerance, ComparisonType compa /// A hash code for the current SpecificEntropy. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -683,17 +721,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(SpecificEntropyUnit unit) + public QuantityValue As(SpecificEntropyUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -708,12 +745,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is SpecificEntropyUnit unitAsSpecificEntropyUnit)) + if (!(unit is SpecificEntropyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEntropyUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificEntropyUnit); + return (QuantityValue)As(typedUnit); } /// @@ -745,7 +782,7 @@ public SpecificEntropy ToUnit(SpecificEntropyUnit unit, UnitConverter unitConver var converted = conversionFunction(this); return (SpecificEntropy)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(SpecificEntropyUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -753,17 +790,17 @@ public SpecificEntropy ToUnit(SpecificEntropyUnit unit, UnitConverter unitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificEntropyUnit unitAsSpecificEntropyUnit)) + if (!(unit is SpecificEntropyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEntropyUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificEntropyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -790,10 +827,10 @@ public SpecificEntropy ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(SpecificEntropyUnit unit) + private QuantityValue GetValueAs(SpecificEntropyUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs index e295f67c8e..96cd5c2aee 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Thrust-specific_fuel_consumption /// [DataContract] - public partial struct SpecificFuelConsumption : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct SpecificFuelConsumption : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -78,9 +78,9 @@ static SpecificFuelConsumption() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public SpecificFuelConsumption(double value, SpecificFuelConsumptionUnit unit) + public SpecificFuelConsumption(QuantityValue value, SpecificFuelConsumptionUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -92,14 +92,14 @@ public SpecificFuelConsumption(double value, SpecificFuelConsumptionUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public SpecificFuelConsumption(double value, UnitSystem unitSystem) + public SpecificFuelConsumption(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -140,7 +140,10 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -163,24 +166,24 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramsPerKiloNewtonSecond => As(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond); + public QuantityValue GramsPerKiloNewtonSecond => As(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerKilogramForceHour => As(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); + public QuantityValue KilogramsPerKilogramForceHour => As(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsPerKiloNewtonSecond => As(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond); + public QuantityValue KilogramsPerKiloNewtonSecond => As(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsMassPerPoundForceHour => As(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); + public QuantityValue PoundsMassPerPoundForceHour => As(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); #endregion @@ -245,7 +248,7 @@ public static string GetAbbreviation(SpecificFuelConsumptionUnit unit, IFormatPr /// If value is NaN or Infinity. public static SpecificFuelConsumption FromGramsPerKiloNewtonSecond(QuantityValue gramsperkilonewtonsecond) { - double value = (double) gramsperkilonewtonsecond; + QuantityValue value = (QuantityValue) gramsperkilonewtonsecond; return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond); } @@ -255,7 +258,7 @@ public static SpecificFuelConsumption FromGramsPerKiloNewtonSecond(QuantityValue /// If value is NaN or Infinity. public static SpecificFuelConsumption FromKilogramsPerKilogramForceHour(QuantityValue kilogramsperkilogramforcehour) { - double value = (double) kilogramsperkilogramforcehour; + QuantityValue value = (QuantityValue) kilogramsperkilogramforcehour; return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); } @@ -265,7 +268,7 @@ public static SpecificFuelConsumption FromKilogramsPerKilogramForceHour(Quantity /// If value is NaN or Infinity. public static SpecificFuelConsumption FromKilogramsPerKiloNewtonSecond(QuantityValue kilogramsperkilonewtonsecond) { - double value = (double) kilogramsperkilonewtonsecond; + QuantityValue value = (QuantityValue) kilogramsperkilonewtonsecond; return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond); } @@ -275,7 +278,7 @@ public static SpecificFuelConsumption FromKilogramsPerKiloNewtonSecond(QuantityV /// If value is NaN or Infinity. public static SpecificFuelConsumption FromPoundsMassPerPoundForceHour(QuantityValue poundsmassperpoundforcehour) { - double value = (double) poundsmassperpoundforcehour; + QuantityValue value = (QuantityValue) poundsmassperpoundforcehour; return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); } @@ -287,7 +290,7 @@ public static SpecificFuelConsumption FromPoundsMassPerPoundForceHour(QuantityVa /// SpecificFuelConsumption unit value. public static SpecificFuelConsumption From(QuantityValue value, SpecificFuelConsumptionUnit fromUnit) { - return new SpecificFuelConsumption((double)value, fromUnit); + return new SpecificFuelConsumption((QuantityValue)value, fromUnit); } #endregion @@ -457,25 +460,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci } /// Get from multiplying value and . - public static SpecificFuelConsumption operator *(double left, SpecificFuelConsumption right) + public static SpecificFuelConsumption operator *(QuantityValue left, SpecificFuelConsumption right) { return new SpecificFuelConsumption(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static SpecificFuelConsumption operator *(SpecificFuelConsumption left, double right) + public static SpecificFuelConsumption operator *(SpecificFuelConsumption left, QuantityValue right) { return new SpecificFuelConsumption(left.Value * right, left.Unit); } /// Get from dividing by value. - public static SpecificFuelConsumption operator /(SpecificFuelConsumption left, double right) + public static SpecificFuelConsumption operator /(SpecificFuelConsumption left, QuantityValue right) { return new SpecificFuelConsumption(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(SpecificFuelConsumption left, SpecificFuelConsumption right) + public static QuantityValue operator /(SpecificFuelConsumption left, SpecificFuelConsumption right) { return left.GramsPerKiloNewtonSecond / right.GramsPerKiloNewtonSecond; } @@ -508,6 +511,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -520,7 +536,29 @@ public int CompareTo(object obj) /// public int CompareTo(SpecificFuelConsumption other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is SpecificFuelConsumption objSpecificFuelConsumption)) + return false; + return Equals(objSpecificFuelConsumption); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(SpecificFuelConsumption other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -563,13 +601,13 @@ public int CompareTo(SpecificFuelConsumption other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificFuelConsumption other, double tolerance, ComparisonType comparisonType) + public bool Equals(SpecificFuelConsumption other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -580,7 +618,7 @@ public bool Equals(SpecificFuelConsumption other, double tolerance, ComparisonTy /// A hash code for the current SpecificFuelConsumption. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -591,17 +629,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(SpecificFuelConsumptionUnit unit) + public QuantityValue As(SpecificFuelConsumptionUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -616,12 +653,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is SpecificFuelConsumptionUnit unitAsSpecificFuelConsumptionUnit)) + if (!(unit is SpecificFuelConsumptionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificFuelConsumptionUnit); + return (QuantityValue)As(typedUnit); } /// @@ -653,7 +690,7 @@ public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit, UnitConv var converted = conversionFunction(this); return (SpecificFuelConsumption)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(SpecificFuelConsumptionUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -661,17 +698,17 @@ public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit, UnitConv } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificFuelConsumptionUnit unitAsSpecificFuelConsumptionUnit)) + if (!(unit is SpecificFuelConsumptionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificFuelConsumptionUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -698,10 +735,10 @@ public SpecificFuelConsumption ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(SpecificFuelConsumptionUnit unit) + private QuantityValue GetValueAs(SpecificFuelConsumptionUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs index f15fc45a52..4a7f1dbd7a 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well. /// [DataContract] - public partial struct SpecificVolume : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct SpecificVolume : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -74,9 +74,9 @@ static SpecificVolume() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public SpecificVolume(double value, SpecificVolumeUnit unit) + public SpecificVolume(QuantityValue value, SpecificVolumeUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -88,14 +88,14 @@ public SpecificVolume(double value, SpecificVolumeUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public SpecificVolume(double value, UnitSystem unitSystem) + public SpecificVolume(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -136,7 +136,10 @@ public SpecificVolume(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -159,19 +162,19 @@ public SpecificVolume(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); + public QuantityValue CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); + public QuantityValue CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillicubicMetersPerKilogram => As(SpecificVolumeUnit.MillicubicMeterPerKilogram); + public QuantityValue MillicubicMetersPerKilogram => As(SpecificVolumeUnit.MillicubicMeterPerKilogram); #endregion @@ -233,7 +236,7 @@ public static string GetAbbreviation(SpecificVolumeUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static SpecificVolume FromCubicFeetPerPound(QuantityValue cubicfeetperpound) { - double value = (double) cubicfeetperpound; + QuantityValue value = (QuantityValue) cubicfeetperpound; return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); } @@ -243,7 +246,7 @@ public static SpecificVolume FromCubicFeetPerPound(QuantityValue cubicfeetperpou /// If value is NaN or Infinity. public static SpecificVolume FromCubicMetersPerKilogram(QuantityValue cubicmetersperkilogram) { - double value = (double) cubicmetersperkilogram; + QuantityValue value = (QuantityValue) cubicmetersperkilogram; return new SpecificVolume(value, SpecificVolumeUnit.CubicMeterPerKilogram); } @@ -253,7 +256,7 @@ public static SpecificVolume FromCubicMetersPerKilogram(QuantityValue cubicmeter /// If value is NaN or Infinity. public static SpecificVolume FromMillicubicMetersPerKilogram(QuantityValue millicubicmetersperkilogram) { - double value = (double) millicubicmetersperkilogram; + QuantityValue value = (QuantityValue) millicubicmetersperkilogram; return new SpecificVolume(value, SpecificVolumeUnit.MillicubicMeterPerKilogram); } @@ -265,7 +268,7 @@ public static SpecificVolume FromMillicubicMetersPerKilogram(QuantityValue milli /// SpecificVolume unit value. public static SpecificVolume From(QuantityValue value, SpecificVolumeUnit fromUnit) { - return new SpecificVolume((double)value, fromUnit); + return new SpecificVolume((QuantityValue)value, fromUnit); } #endregion @@ -435,25 +438,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci } /// Get from multiplying value and . - public static SpecificVolume operator *(double left, SpecificVolume right) + public static SpecificVolume operator *(QuantityValue left, SpecificVolume right) { return new SpecificVolume(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static SpecificVolume operator *(SpecificVolume left, double right) + public static SpecificVolume operator *(SpecificVolume left, QuantityValue right) { return new SpecificVolume(left.Value * right, left.Unit); } /// Get from dividing by value. - public static SpecificVolume operator /(SpecificVolume left, double right) + public static SpecificVolume operator /(SpecificVolume left, QuantityValue right) { return new SpecificVolume(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(SpecificVolume left, SpecificVolume right) + public static QuantityValue operator /(SpecificVolume left, SpecificVolume right) { return left.CubicMetersPerKilogram / right.CubicMetersPerKilogram; } @@ -486,6 +489,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(SpecificVolume left, SpecificVolume right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(SpecificVolume left, SpecificVolume right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -498,7 +514,29 @@ public int CompareTo(object obj) /// public int CompareTo(SpecificVolume other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is SpecificVolume objSpecificVolume)) + return false; + return Equals(objSpecificVolume); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(SpecificVolume other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -541,13 +579,13 @@ public int CompareTo(SpecificVolume other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificVolume other, double tolerance, ComparisonType comparisonType) + public bool Equals(SpecificVolume other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -558,7 +596,7 @@ public bool Equals(SpecificVolume other, double tolerance, ComparisonType compar /// A hash code for the current SpecificVolume. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -569,17 +607,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(SpecificVolumeUnit unit) + public QuantityValue As(SpecificVolumeUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -594,12 +631,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is SpecificVolumeUnit unitAsSpecificVolumeUnit)) + if (!(unit is SpecificVolumeUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificVolumeUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificVolumeUnit); + return (QuantityValue)As(typedUnit); } /// @@ -631,7 +668,7 @@ public SpecificVolume ToUnit(SpecificVolumeUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (SpecificVolume)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(SpecificVolumeUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -639,17 +676,17 @@ public SpecificVolume ToUnit(SpecificVolumeUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificVolumeUnit unitAsSpecificVolumeUnit)) + if (!(unit is SpecificVolumeUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificVolumeUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificVolumeUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -676,10 +713,10 @@ public SpecificVolume ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(SpecificVolumeUnit unit) + private QuantityValue GetValueAs(SpecificVolumeUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs index 1698dbf5e8..e00a8d857d 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Specificweight /// [DataContract] - public partial struct SpecificWeight : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct SpecificWeight : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -91,9 +91,9 @@ static SpecificWeight() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public SpecificWeight(double value, SpecificWeightUnit unit) + public SpecificWeight(QuantityValue value, SpecificWeightUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -105,14 +105,14 @@ public SpecificWeight(double value, SpecificWeightUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public SpecificWeight(double value, UnitSystem unitSystem) + public SpecificWeight(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -153,7 +153,10 @@ public SpecificWeight(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -176,89 +179,89 @@ public SpecificWeight(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); + public QuantityValue KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); + public QuantityValue KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); + public QuantityValue KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); + public QuantityValue KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); + public QuantityValue KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); + public QuantityValue KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); + public QuantityValue KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); + public QuantityValue KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonsPerCubicMeter => As(SpecificWeightUnit.MeganewtonPerCubicMeter); + public QuantityValue MeganewtonsPerCubicMeter => As(SpecificWeightUnit.MeganewtonPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); + public QuantityValue NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); + public QuantityValue NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); + public QuantityValue NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); + public QuantityValue PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); + public QuantityValue PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); + public QuantityValue TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); + public QuantityValue TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); + public QuantityValue TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); #endregion @@ -362,7 +365,7 @@ public static string GetAbbreviation(SpecificWeightUnit unit, IFormatProvider? p /// If value is NaN or Infinity. public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue kilogramsforcepercubiccentimeter) { - double value = (double) kilogramsforcepercubiccentimeter; + QuantityValue value = (QuantityValue) kilogramsforcepercubiccentimeter; return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); } @@ -372,7 +375,7 @@ public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue /// If value is NaN or Infinity. public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue kilogramsforcepercubicmeter) { - double value = (double) kilogramsforcepercubicmeter; + QuantityValue value = (QuantityValue) kilogramsforcepercubicmeter; return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); } @@ -382,7 +385,7 @@ public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue kilog /// If value is NaN or Infinity. public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue kilogramsforcepercubicmillimeter) { - double value = (double) kilogramsforcepercubicmillimeter; + QuantityValue value = (QuantityValue) kilogramsforcepercubicmillimeter; return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); } @@ -392,7 +395,7 @@ public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue /// If value is NaN or Infinity. public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue kilonewtonspercubiccentimeter) { - double value = (double) kilonewtonspercubiccentimeter; + QuantityValue value = (QuantityValue) kilonewtonspercubiccentimeter; return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); } @@ -402,7 +405,7 @@ public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue kil /// If value is NaN or Infinity. public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue kilonewtonspercubicmeter) { - double value = (double) kilonewtonspercubicmeter; + QuantityValue value = (QuantityValue) kilonewtonspercubicmeter; return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); } @@ -412,7 +415,7 @@ public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue kilonewt /// If value is NaN or Infinity. public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue kilonewtonspercubicmillimeter) { - double value = (double) kilonewtonspercubicmillimeter; + QuantityValue value = (QuantityValue) kilonewtonspercubicmillimeter; return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); } @@ -422,7 +425,7 @@ public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue kil /// If value is NaN or Infinity. public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue kilopoundsforcepercubicfoot) { - double value = (double) kilopoundsforcepercubicfoot; + QuantityValue value = (QuantityValue) kilopoundsforcepercubicfoot; return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); } @@ -432,7 +435,7 @@ public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue kilop /// If value is NaN or Infinity. public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue kilopoundsforcepercubicinch) { - double value = (double) kilopoundsforcepercubicinch; + QuantityValue value = (QuantityValue) kilopoundsforcepercubicinch; return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); } @@ -442,7 +445,7 @@ public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue kilop /// If value is NaN or Infinity. public static SpecificWeight FromMeganewtonsPerCubicMeter(QuantityValue meganewtonspercubicmeter) { - double value = (double) meganewtonspercubicmeter; + QuantityValue value = (QuantityValue) meganewtonspercubicmeter; return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); } @@ -452,7 +455,7 @@ public static SpecificWeight FromMeganewtonsPerCubicMeter(QuantityValue meganewt /// If value is NaN or Infinity. public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue newtonspercubiccentimeter) { - double value = (double) newtonspercubiccentimeter; + QuantityValue value = (QuantityValue) newtonspercubiccentimeter; return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); } @@ -462,7 +465,7 @@ public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue newtons /// If value is NaN or Infinity. public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue newtonspercubicmeter) { - double value = (double) newtonspercubicmeter; + QuantityValue value = (QuantityValue) newtonspercubicmeter; return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); } @@ -472,7 +475,7 @@ public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue newtonspercu /// If value is NaN or Infinity. public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue newtonspercubicmillimeter) { - double value = (double) newtonspercubicmillimeter; + QuantityValue value = (QuantityValue) newtonspercubicmillimeter; return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); } @@ -482,7 +485,7 @@ public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue newtons /// If value is NaN or Infinity. public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue poundsforcepercubicfoot) { - double value = (double) poundsforcepercubicfoot; + QuantityValue value = (QuantityValue) poundsforcepercubicfoot; return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); } @@ -492,7 +495,7 @@ public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue poundsfor /// If value is NaN or Infinity. public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue poundsforcepercubicinch) { - double value = (double) poundsforcepercubicinch; + QuantityValue value = (QuantityValue) poundsforcepercubicinch; return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); } @@ -502,7 +505,7 @@ public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue poundsfor /// If value is NaN or Infinity. public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue tonnesforcepercubiccentimeter) { - double value = (double) tonnesforcepercubiccentimeter; + QuantityValue value = (QuantityValue) tonnesforcepercubiccentimeter; return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); } @@ -512,7 +515,7 @@ public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue ton /// If value is NaN or Infinity. public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue tonnesforcepercubicmeter) { - double value = (double) tonnesforcepercubicmeter; + QuantityValue value = (QuantityValue) tonnesforcepercubicmeter; return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); } @@ -522,7 +525,7 @@ public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue tonnesfo /// If value is NaN or Infinity. public static SpecificWeight FromTonnesForcePerCubicMillimeter(QuantityValue tonnesforcepercubicmillimeter) { - double value = (double) tonnesforcepercubicmillimeter; + QuantityValue value = (QuantityValue) tonnesforcepercubicmillimeter; return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMillimeter); } @@ -534,7 +537,7 @@ public static SpecificWeight FromTonnesForcePerCubicMillimeter(QuantityValue ton /// SpecificWeight unit value. public static SpecificWeight From(QuantityValue value, SpecificWeightUnit fromUnit) { - return new SpecificWeight((double)value, fromUnit); + return new SpecificWeight((QuantityValue)value, fromUnit); } #endregion @@ -704,25 +707,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci } /// Get from multiplying value and . - public static SpecificWeight operator *(double left, SpecificWeight right) + public static SpecificWeight operator *(QuantityValue left, SpecificWeight right) { return new SpecificWeight(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static SpecificWeight operator *(SpecificWeight left, double right) + public static SpecificWeight operator *(SpecificWeight left, QuantityValue right) { return new SpecificWeight(left.Value * right, left.Unit); } /// Get from dividing by value. - public static SpecificWeight operator /(SpecificWeight left, double right) + public static SpecificWeight operator /(SpecificWeight left, QuantityValue right) { return new SpecificWeight(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(SpecificWeight left, SpecificWeight right) + public static QuantityValue operator /(SpecificWeight left, SpecificWeight right) { return left.NewtonsPerCubicMeter / right.NewtonsPerCubicMeter; } @@ -755,6 +758,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(SpecificWeight left, SpecificWeight right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(SpecificWeight left, SpecificWeight right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -767,7 +783,29 @@ public int CompareTo(object obj) /// public int CompareTo(SpecificWeight other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is SpecificWeight objSpecificWeight)) + return false; + return Equals(objSpecificWeight); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(SpecificWeight other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -810,13 +848,13 @@ public int CompareTo(SpecificWeight other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificWeight other, double tolerance, ComparisonType comparisonType) + public bool Equals(SpecificWeight other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -827,7 +865,7 @@ public bool Equals(SpecificWeight other, double tolerance, ComparisonType compar /// A hash code for the current SpecificWeight. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -838,17 +876,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(SpecificWeightUnit unit) + public QuantityValue As(SpecificWeightUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -863,12 +900,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is SpecificWeightUnit unitAsSpecificWeightUnit)) + if (!(unit is SpecificWeightUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificWeightUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificWeightUnit); + return (QuantityValue)As(typedUnit); } /// @@ -900,7 +937,7 @@ public SpecificWeight ToUnit(SpecificWeightUnit unit, UnitConverter unitConverte var converted = conversionFunction(this); return (SpecificWeight)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(SpecificWeightUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -908,17 +945,17 @@ public SpecificWeight ToUnit(SpecificWeightUnit unit, UnitConverter unitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificWeightUnit unitAsSpecificWeightUnit)) + if (!(unit is SpecificWeightUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificWeightUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpecificWeightUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -945,10 +982,10 @@ public SpecificWeight ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(SpecificWeightUnit unit) + private QuantityValue GetValueAs(SpecificWeightUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs index f064d928b9..e28ac87c05 100644 --- a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero. /// [DataContract] - public partial struct Speed : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Speed : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -103,9 +103,9 @@ static Speed() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Speed(double value, SpeedUnit unit) + public Speed(QuantityValue value, SpeedUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -117,14 +117,14 @@ public Speed(double value, SpeedUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Speed(double value, UnitSystem unitSystem) + public Speed(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -165,7 +165,10 @@ public Speed(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -188,164 +191,164 @@ public Speed(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); + public QuantityValue CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentimetersPerMinutes => As(SpeedUnit.CentimeterPerMinute); + public QuantityValue CentimetersPerMinutes => As(SpeedUnit.CentimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); + public QuantityValue CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimetersPerMinutes => As(SpeedUnit.DecimeterPerMinute); + public QuantityValue DecimetersPerMinutes => As(SpeedUnit.DecimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); + public QuantityValue DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FeetPerHour => As(SpeedUnit.FootPerHour); + public QuantityValue FeetPerHour => As(SpeedUnit.FootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FeetPerMinute => As(SpeedUnit.FootPerMinute); + public QuantityValue FeetPerMinute => As(SpeedUnit.FootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FeetPerSecond => As(SpeedUnit.FootPerSecond); + public QuantityValue FeetPerSecond => As(SpeedUnit.FootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InchesPerHour => As(SpeedUnit.InchPerHour); + public QuantityValue InchesPerHour => As(SpeedUnit.InchPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InchesPerMinute => As(SpeedUnit.InchPerMinute); + public QuantityValue InchesPerMinute => As(SpeedUnit.InchPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InchesPerSecond => As(SpeedUnit.InchPerSecond); + public QuantityValue InchesPerSecond => As(SpeedUnit.InchPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilometersPerHour => As(SpeedUnit.KilometerPerHour); + public QuantityValue KilometersPerHour => As(SpeedUnit.KilometerPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilometersPerMinutes => As(SpeedUnit.KilometerPerMinute); + public QuantityValue KilometersPerMinutes => As(SpeedUnit.KilometerPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); + public QuantityValue KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Knots => As(SpeedUnit.Knot); + public QuantityValue Knots => As(SpeedUnit.Knot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetersPerHour => As(SpeedUnit.MeterPerHour); + public QuantityValue MetersPerHour => As(SpeedUnit.MeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetersPerMinutes => As(SpeedUnit.MeterPerMinute); + public QuantityValue MetersPerMinutes => As(SpeedUnit.MeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetersPerSecond => As(SpeedUnit.MeterPerSecond); + public QuantityValue MetersPerSecond => As(SpeedUnit.MeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrometersPerMinutes => As(SpeedUnit.MicrometerPerMinute); + public QuantityValue MicrometersPerMinutes => As(SpeedUnit.MicrometerPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); + public QuantityValue MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MilesPerHour => As(SpeedUnit.MilePerHour); + public QuantityValue MilesPerHour => As(SpeedUnit.MilePerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); + public QuantityValue MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimetersPerMinutes => As(SpeedUnit.MillimeterPerMinute); + public QuantityValue MillimetersPerMinutes => As(SpeedUnit.MillimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); + public QuantityValue MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanometersPerMinutes => As(SpeedUnit.NanometerPerMinute); + public QuantityValue NanometersPerMinutes => As(SpeedUnit.NanometerPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); + public QuantityValue NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); + public QuantityValue UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); + public QuantityValue UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); + public QuantityValue UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double YardsPerHour => As(SpeedUnit.YardPerHour); + public QuantityValue YardsPerHour => As(SpeedUnit.YardPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double YardsPerMinute => As(SpeedUnit.YardPerMinute); + public QuantityValue YardsPerMinute => As(SpeedUnit.YardPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double YardsPerSecond => As(SpeedUnit.YardPerSecond); + public QuantityValue YardsPerSecond => As(SpeedUnit.YardPerSecond); #endregion @@ -517,7 +520,7 @@ public static string GetAbbreviation(SpeedUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Speed FromCentimetersPerHour(QuantityValue centimetersperhour) { - double value = (double) centimetersperhour; + QuantityValue value = (QuantityValue) centimetersperhour; return new Speed(value, SpeedUnit.CentimeterPerHour); } @@ -527,7 +530,7 @@ public static Speed FromCentimetersPerHour(QuantityValue centimetersperhour) /// If value is NaN or Infinity. public static Speed FromCentimetersPerMinutes(QuantityValue centimetersperminutes) { - double value = (double) centimetersperminutes; + QuantityValue value = (QuantityValue) centimetersperminutes; return new Speed(value, SpeedUnit.CentimeterPerMinute); } @@ -537,7 +540,7 @@ public static Speed FromCentimetersPerMinutes(QuantityValue centimetersperminute /// If value is NaN or Infinity. public static Speed FromCentimetersPerSecond(QuantityValue centimeterspersecond) { - double value = (double) centimeterspersecond; + QuantityValue value = (QuantityValue) centimeterspersecond; return new Speed(value, SpeedUnit.CentimeterPerSecond); } @@ -547,7 +550,7 @@ public static Speed FromCentimetersPerSecond(QuantityValue centimeterspersecond) /// If value is NaN or Infinity. public static Speed FromDecimetersPerMinutes(QuantityValue decimetersperminutes) { - double value = (double) decimetersperminutes; + QuantityValue value = (QuantityValue) decimetersperminutes; return new Speed(value, SpeedUnit.DecimeterPerMinute); } @@ -557,7 +560,7 @@ public static Speed FromDecimetersPerMinutes(QuantityValue decimetersperminutes) /// If value is NaN or Infinity. public static Speed FromDecimetersPerSecond(QuantityValue decimeterspersecond) { - double value = (double) decimeterspersecond; + QuantityValue value = (QuantityValue) decimeterspersecond; return new Speed(value, SpeedUnit.DecimeterPerSecond); } @@ -567,7 +570,7 @@ public static Speed FromDecimetersPerSecond(QuantityValue decimeterspersecond) /// If value is NaN or Infinity. public static Speed FromFeetPerHour(QuantityValue feetperhour) { - double value = (double) feetperhour; + QuantityValue value = (QuantityValue) feetperhour; return new Speed(value, SpeedUnit.FootPerHour); } @@ -577,7 +580,7 @@ public static Speed FromFeetPerHour(QuantityValue feetperhour) /// If value is NaN or Infinity. public static Speed FromFeetPerMinute(QuantityValue feetperminute) { - double value = (double) feetperminute; + QuantityValue value = (QuantityValue) feetperminute; return new Speed(value, SpeedUnit.FootPerMinute); } @@ -587,7 +590,7 @@ public static Speed FromFeetPerMinute(QuantityValue feetperminute) /// If value is NaN or Infinity. public static Speed FromFeetPerSecond(QuantityValue feetpersecond) { - double value = (double) feetpersecond; + QuantityValue value = (QuantityValue) feetpersecond; return new Speed(value, SpeedUnit.FootPerSecond); } @@ -597,7 +600,7 @@ public static Speed FromFeetPerSecond(QuantityValue feetpersecond) /// If value is NaN or Infinity. public static Speed FromInchesPerHour(QuantityValue inchesperhour) { - double value = (double) inchesperhour; + QuantityValue value = (QuantityValue) inchesperhour; return new Speed(value, SpeedUnit.InchPerHour); } @@ -607,7 +610,7 @@ public static Speed FromInchesPerHour(QuantityValue inchesperhour) /// If value is NaN or Infinity. public static Speed FromInchesPerMinute(QuantityValue inchesperminute) { - double value = (double) inchesperminute; + QuantityValue value = (QuantityValue) inchesperminute; return new Speed(value, SpeedUnit.InchPerMinute); } @@ -617,7 +620,7 @@ public static Speed FromInchesPerMinute(QuantityValue inchesperminute) /// If value is NaN or Infinity. public static Speed FromInchesPerSecond(QuantityValue inchespersecond) { - double value = (double) inchespersecond; + QuantityValue value = (QuantityValue) inchespersecond; return new Speed(value, SpeedUnit.InchPerSecond); } @@ -627,7 +630,7 @@ public static Speed FromInchesPerSecond(QuantityValue inchespersecond) /// If value is NaN or Infinity. public static Speed FromKilometersPerHour(QuantityValue kilometersperhour) { - double value = (double) kilometersperhour; + QuantityValue value = (QuantityValue) kilometersperhour; return new Speed(value, SpeedUnit.KilometerPerHour); } @@ -637,7 +640,7 @@ public static Speed FromKilometersPerHour(QuantityValue kilometersperhour) /// If value is NaN or Infinity. public static Speed FromKilometersPerMinutes(QuantityValue kilometersperminutes) { - double value = (double) kilometersperminutes; + QuantityValue value = (QuantityValue) kilometersperminutes; return new Speed(value, SpeedUnit.KilometerPerMinute); } @@ -647,7 +650,7 @@ public static Speed FromKilometersPerMinutes(QuantityValue kilometersperminutes) /// If value is NaN or Infinity. public static Speed FromKilometersPerSecond(QuantityValue kilometerspersecond) { - double value = (double) kilometerspersecond; + QuantityValue value = (QuantityValue) kilometerspersecond; return new Speed(value, SpeedUnit.KilometerPerSecond); } @@ -657,7 +660,7 @@ public static Speed FromKilometersPerSecond(QuantityValue kilometerspersecond) /// If value is NaN or Infinity. public static Speed FromKnots(QuantityValue knots) { - double value = (double) knots; + QuantityValue value = (QuantityValue) knots; return new Speed(value, SpeedUnit.Knot); } @@ -667,7 +670,7 @@ public static Speed FromKnots(QuantityValue knots) /// If value is NaN or Infinity. public static Speed FromMetersPerHour(QuantityValue metersperhour) { - double value = (double) metersperhour; + QuantityValue value = (QuantityValue) metersperhour; return new Speed(value, SpeedUnit.MeterPerHour); } @@ -677,7 +680,7 @@ public static Speed FromMetersPerHour(QuantityValue metersperhour) /// If value is NaN or Infinity. public static Speed FromMetersPerMinutes(QuantityValue metersperminutes) { - double value = (double) metersperminutes; + QuantityValue value = (QuantityValue) metersperminutes; return new Speed(value, SpeedUnit.MeterPerMinute); } @@ -687,7 +690,7 @@ public static Speed FromMetersPerMinutes(QuantityValue metersperminutes) /// If value is NaN or Infinity. public static Speed FromMetersPerSecond(QuantityValue meterspersecond) { - double value = (double) meterspersecond; + QuantityValue value = (QuantityValue) meterspersecond; return new Speed(value, SpeedUnit.MeterPerSecond); } @@ -697,7 +700,7 @@ public static Speed FromMetersPerSecond(QuantityValue meterspersecond) /// If value is NaN or Infinity. public static Speed FromMicrometersPerMinutes(QuantityValue micrometersperminutes) { - double value = (double) micrometersperminutes; + QuantityValue value = (QuantityValue) micrometersperminutes; return new Speed(value, SpeedUnit.MicrometerPerMinute); } @@ -707,7 +710,7 @@ public static Speed FromMicrometersPerMinutes(QuantityValue micrometersperminute /// If value is NaN or Infinity. public static Speed FromMicrometersPerSecond(QuantityValue micrometerspersecond) { - double value = (double) micrometerspersecond; + QuantityValue value = (QuantityValue) micrometerspersecond; return new Speed(value, SpeedUnit.MicrometerPerSecond); } @@ -717,7 +720,7 @@ public static Speed FromMicrometersPerSecond(QuantityValue micrometerspersecond) /// If value is NaN or Infinity. public static Speed FromMilesPerHour(QuantityValue milesperhour) { - double value = (double) milesperhour; + QuantityValue value = (QuantityValue) milesperhour; return new Speed(value, SpeedUnit.MilePerHour); } @@ -727,7 +730,7 @@ public static Speed FromMilesPerHour(QuantityValue milesperhour) /// If value is NaN or Infinity. public static Speed FromMillimetersPerHour(QuantityValue millimetersperhour) { - double value = (double) millimetersperhour; + QuantityValue value = (QuantityValue) millimetersperhour; return new Speed(value, SpeedUnit.MillimeterPerHour); } @@ -737,7 +740,7 @@ public static Speed FromMillimetersPerHour(QuantityValue millimetersperhour) /// If value is NaN or Infinity. public static Speed FromMillimetersPerMinutes(QuantityValue millimetersperminutes) { - double value = (double) millimetersperminutes; + QuantityValue value = (QuantityValue) millimetersperminutes; return new Speed(value, SpeedUnit.MillimeterPerMinute); } @@ -747,7 +750,7 @@ public static Speed FromMillimetersPerMinutes(QuantityValue millimetersperminute /// If value is NaN or Infinity. public static Speed FromMillimetersPerSecond(QuantityValue millimeterspersecond) { - double value = (double) millimeterspersecond; + QuantityValue value = (QuantityValue) millimeterspersecond; return new Speed(value, SpeedUnit.MillimeterPerSecond); } @@ -757,7 +760,7 @@ public static Speed FromMillimetersPerSecond(QuantityValue millimeterspersecond) /// If value is NaN or Infinity. public static Speed FromNanometersPerMinutes(QuantityValue nanometersperminutes) { - double value = (double) nanometersperminutes; + QuantityValue value = (QuantityValue) nanometersperminutes; return new Speed(value, SpeedUnit.NanometerPerMinute); } @@ -767,7 +770,7 @@ public static Speed FromNanometersPerMinutes(QuantityValue nanometersperminutes) /// If value is NaN or Infinity. public static Speed FromNanometersPerSecond(QuantityValue nanometerspersecond) { - double value = (double) nanometerspersecond; + QuantityValue value = (QuantityValue) nanometerspersecond; return new Speed(value, SpeedUnit.NanometerPerSecond); } @@ -777,7 +780,7 @@ public static Speed FromNanometersPerSecond(QuantityValue nanometerspersecond) /// If value is NaN or Infinity. public static Speed FromUsSurveyFeetPerHour(QuantityValue ussurveyfeetperhour) { - double value = (double) ussurveyfeetperhour; + QuantityValue value = (QuantityValue) ussurveyfeetperhour; return new Speed(value, SpeedUnit.UsSurveyFootPerHour); } @@ -787,7 +790,7 @@ public static Speed FromUsSurveyFeetPerHour(QuantityValue ussurveyfeetperhour) /// If value is NaN or Infinity. public static Speed FromUsSurveyFeetPerMinute(QuantityValue ussurveyfeetperminute) { - double value = (double) ussurveyfeetperminute; + QuantityValue value = (QuantityValue) ussurveyfeetperminute; return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); } @@ -797,7 +800,7 @@ public static Speed FromUsSurveyFeetPerMinute(QuantityValue ussurveyfeetperminut /// If value is NaN or Infinity. public static Speed FromUsSurveyFeetPerSecond(QuantityValue ussurveyfeetpersecond) { - double value = (double) ussurveyfeetpersecond; + QuantityValue value = (QuantityValue) ussurveyfeetpersecond; return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); } @@ -807,7 +810,7 @@ public static Speed FromUsSurveyFeetPerSecond(QuantityValue ussurveyfeetpersecon /// If value is NaN or Infinity. public static Speed FromYardsPerHour(QuantityValue yardsperhour) { - double value = (double) yardsperhour; + QuantityValue value = (QuantityValue) yardsperhour; return new Speed(value, SpeedUnit.YardPerHour); } @@ -817,7 +820,7 @@ public static Speed FromYardsPerHour(QuantityValue yardsperhour) /// If value is NaN or Infinity. public static Speed FromYardsPerMinute(QuantityValue yardsperminute) { - double value = (double) yardsperminute; + QuantityValue value = (QuantityValue) yardsperminute; return new Speed(value, SpeedUnit.YardPerMinute); } @@ -827,7 +830,7 @@ public static Speed FromYardsPerMinute(QuantityValue yardsperminute) /// If value is NaN or Infinity. public static Speed FromYardsPerSecond(QuantityValue yardspersecond) { - double value = (double) yardspersecond; + QuantityValue value = (QuantityValue) yardspersecond; return new Speed(value, SpeedUnit.YardPerSecond); } @@ -839,7 +842,7 @@ public static Speed FromYardsPerSecond(QuantityValue yardspersecond) /// Speed unit value. public static Speed From(QuantityValue value, SpeedUnit fromUnit) { - return new Speed((double)value, fromUnit); + return new Speed((QuantityValue)value, fromUnit); } #endregion @@ -1009,25 +1012,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speed } /// Get from multiplying value and . - public static Speed operator *(double left, Speed right) + public static Speed operator *(QuantityValue left, Speed right) { return new Speed(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Speed operator *(Speed left, double right) + public static Speed operator *(Speed left, QuantityValue right) { return new Speed(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Speed operator /(Speed left, double right) + public static Speed operator /(Speed left, QuantityValue right) { return new Speed(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Speed left, Speed right) + public static QuantityValue operator /(Speed left, Speed right) { return left.MetersPerSecond / right.MetersPerSecond; } @@ -1060,6 +1063,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speed return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Speed left, Speed right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Speed left, Speed right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1072,7 +1088,29 @@ public int CompareTo(object obj) /// public int CompareTo(Speed other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Speed objSpeed)) + return false; + return Equals(objSpeed); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Speed other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1115,13 +1153,13 @@ public int CompareTo(Speed other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Speed other, double tolerance, ComparisonType comparisonType) + public bool Equals(Speed other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1132,7 +1170,7 @@ public bool Equals(Speed other, double tolerance, ComparisonType comparisonType) /// A hash code for the current Speed. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1143,17 +1181,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(SpeedUnit unit) + public QuantityValue As(SpeedUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1168,12 +1205,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is SpeedUnit unitAsSpeedUnit)) + if (!(unit is SpeedUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpeedUnit)} is supported.", nameof(unit)); - return As(unitAsSpeedUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1205,7 +1242,7 @@ public Speed ToUnit(SpeedUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Speed)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(SpeedUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1213,17 +1250,17 @@ public Speed ToUnit(SpeedUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpeedUnit unitAsSpeedUnit)) + if (!(unit is SpeedUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpeedUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsSpeedUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1250,10 +1287,10 @@ public Speed ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(SpeedUnit unit) + private QuantityValue GetValueAs(SpeedUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs index 9267650cd1..9cc738ec93 100644 --- a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The molar flow rate of a gas corrected to standardized conditions of temperature and pressure thus representing a fixed number of moles of gas regardless of composition and actual flow conditions. /// [DataContract] - public partial struct StandardVolumeFlow : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct StandardVolumeFlow : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -80,9 +80,9 @@ static StandardVolumeFlow() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public StandardVolumeFlow(double value, StandardVolumeFlowUnit unit) + public StandardVolumeFlow(QuantityValue value, StandardVolumeFlowUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -94,14 +94,14 @@ public StandardVolumeFlow(double value, StandardVolumeFlowUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public StandardVolumeFlow(double value, UnitSystem unitSystem) + public StandardVolumeFlow(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -142,7 +142,10 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -165,49 +168,49 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardCubicCentimetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); + public QuantityValue StandardCubicCentimetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardCubicFeetPerHour => As(StandardVolumeFlowUnit.StandardCubicFootPerHour); + public QuantityValue StandardCubicFeetPerHour => As(StandardVolumeFlowUnit.StandardCubicFootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardCubicFeetPerMinute => As(StandardVolumeFlowUnit.StandardCubicFootPerMinute); + public QuantityValue StandardCubicFeetPerMinute => As(StandardVolumeFlowUnit.StandardCubicFootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardCubicFeetPerSecond => As(StandardVolumeFlowUnit.StandardCubicFootPerSecond); + public QuantityValue StandardCubicFeetPerSecond => As(StandardVolumeFlowUnit.StandardCubicFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardCubicMetersPerDay => As(StandardVolumeFlowUnit.StandardCubicMeterPerDay); + public QuantityValue StandardCubicMetersPerDay => As(StandardVolumeFlowUnit.StandardCubicMeterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardCubicMetersPerHour => As(StandardVolumeFlowUnit.StandardCubicMeterPerHour); + public QuantityValue StandardCubicMetersPerHour => As(StandardVolumeFlowUnit.StandardCubicMeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardCubicMetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicMeterPerMinute); + public QuantityValue StandardCubicMetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicMeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardCubicMetersPerSecond => As(StandardVolumeFlowUnit.StandardCubicMeterPerSecond); + public QuantityValue StandardCubicMetersPerSecond => As(StandardVolumeFlowUnit.StandardCubicMeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double StandardLitersPerMinute => As(StandardVolumeFlowUnit.StandardLiterPerMinute); + public QuantityValue StandardLitersPerMinute => As(StandardVolumeFlowUnit.StandardLiterPerMinute); #endregion @@ -287,7 +290,7 @@ public static string GetAbbreviation(StandardVolumeFlowUnit unit, IFormatProvide /// If value is NaN or Infinity. public static StandardVolumeFlow FromStandardCubicCentimetersPerMinute(QuantityValue standardcubiccentimetersperminute) { - double value = (double) standardcubiccentimetersperminute; + QuantityValue value = (QuantityValue) standardcubiccentimetersperminute; return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); } @@ -297,7 +300,7 @@ public static StandardVolumeFlow FromStandardCubicCentimetersPerMinute(QuantityV /// If value is NaN or Infinity. public static StandardVolumeFlow FromStandardCubicFeetPerHour(QuantityValue standardcubicfeetperhour) { - double value = (double) standardcubicfeetperhour; + QuantityValue value = (QuantityValue) standardcubicfeetperhour; return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerHour); } @@ -307,7 +310,7 @@ public static StandardVolumeFlow FromStandardCubicFeetPerHour(QuantityValue stan /// If value is NaN or Infinity. public static StandardVolumeFlow FromStandardCubicFeetPerMinute(QuantityValue standardcubicfeetperminute) { - double value = (double) standardcubicfeetperminute; + QuantityValue value = (QuantityValue) standardcubicfeetperminute; return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerMinute); } @@ -317,7 +320,7 @@ public static StandardVolumeFlow FromStandardCubicFeetPerMinute(QuantityValue st /// If value is NaN or Infinity. public static StandardVolumeFlow FromStandardCubicFeetPerSecond(QuantityValue standardcubicfeetpersecond) { - double value = (double) standardcubicfeetpersecond; + QuantityValue value = (QuantityValue) standardcubicfeetpersecond; return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerSecond); } @@ -327,7 +330,7 @@ public static StandardVolumeFlow FromStandardCubicFeetPerSecond(QuantityValue st /// If value is NaN or Infinity. public static StandardVolumeFlow FromStandardCubicMetersPerDay(QuantityValue standardcubicmetersperday) { - double value = (double) standardcubicmetersperday; + QuantityValue value = (QuantityValue) standardcubicmetersperday; return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerDay); } @@ -337,7 +340,7 @@ public static StandardVolumeFlow FromStandardCubicMetersPerDay(QuantityValue sta /// If value is NaN or Infinity. public static StandardVolumeFlow FromStandardCubicMetersPerHour(QuantityValue standardcubicmetersperhour) { - double value = (double) standardcubicmetersperhour; + QuantityValue value = (QuantityValue) standardcubicmetersperhour; return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerHour); } @@ -347,7 +350,7 @@ public static StandardVolumeFlow FromStandardCubicMetersPerHour(QuantityValue st /// If value is NaN or Infinity. public static StandardVolumeFlow FromStandardCubicMetersPerMinute(QuantityValue standardcubicmetersperminute) { - double value = (double) standardcubicmetersperminute; + QuantityValue value = (QuantityValue) standardcubicmetersperminute; return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerMinute); } @@ -357,7 +360,7 @@ public static StandardVolumeFlow FromStandardCubicMetersPerMinute(QuantityValue /// If value is NaN or Infinity. public static StandardVolumeFlow FromStandardCubicMetersPerSecond(QuantityValue standardcubicmeterspersecond) { - double value = (double) standardcubicmeterspersecond; + QuantityValue value = (QuantityValue) standardcubicmeterspersecond; return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerSecond); } @@ -367,7 +370,7 @@ public static StandardVolumeFlow FromStandardCubicMetersPerSecond(QuantityValue /// If value is NaN or Infinity. public static StandardVolumeFlow FromStandardLitersPerMinute(QuantityValue standardlitersperminute) { - double value = (double) standardlitersperminute; + QuantityValue value = (QuantityValue) standardlitersperminute; return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardLiterPerMinute); } @@ -379,7 +382,7 @@ public static StandardVolumeFlow FromStandardLitersPerMinute(QuantityValue stand /// StandardVolumeFlow unit value. public static StandardVolumeFlow From(QuantityValue value, StandardVolumeFlowUnit fromUnit) { - return new StandardVolumeFlow((double)value, fromUnit); + return new StandardVolumeFlow((QuantityValue)value, fromUnit); } #endregion @@ -549,25 +552,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Stand } /// Get from multiplying value and . - public static StandardVolumeFlow operator *(double left, StandardVolumeFlow right) + public static StandardVolumeFlow operator *(QuantityValue left, StandardVolumeFlow right) { return new StandardVolumeFlow(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static StandardVolumeFlow operator *(StandardVolumeFlow left, double right) + public static StandardVolumeFlow operator *(StandardVolumeFlow left, QuantityValue right) { return new StandardVolumeFlow(left.Value * right, left.Unit); } /// Get from dividing by value. - public static StandardVolumeFlow operator /(StandardVolumeFlow left, double right) + public static StandardVolumeFlow operator /(StandardVolumeFlow left, QuantityValue right) { return new StandardVolumeFlow(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(StandardVolumeFlow left, StandardVolumeFlow right) + public static QuantityValue operator /(StandardVolumeFlow left, StandardVolumeFlow right) { return left.StandardCubicMetersPerSecond / right.StandardCubicMetersPerSecond; } @@ -600,6 +603,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Stand return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(StandardVolumeFlow left, StandardVolumeFlow right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(StandardVolumeFlow left, StandardVolumeFlow right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -612,7 +628,29 @@ public int CompareTo(object obj) /// public int CompareTo(StandardVolumeFlow other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is StandardVolumeFlow objStandardVolumeFlow)) + return false; + return Equals(objStandardVolumeFlow); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(StandardVolumeFlow other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -655,13 +693,13 @@ public int CompareTo(StandardVolumeFlow other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(StandardVolumeFlow other, double tolerance, ComparisonType comparisonType) + public bool Equals(StandardVolumeFlow other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -672,7 +710,7 @@ public bool Equals(StandardVolumeFlow other, double tolerance, ComparisonType co /// A hash code for the current StandardVolumeFlow. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -683,17 +721,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(StandardVolumeFlowUnit unit) + public QuantityValue As(StandardVolumeFlowUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -708,12 +745,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is StandardVolumeFlowUnit unitAsStandardVolumeFlowUnit)) + if (!(unit is StandardVolumeFlowUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(StandardVolumeFlowUnit)} is supported.", nameof(unit)); - return As(unitAsStandardVolumeFlowUnit); + return (QuantityValue)As(typedUnit); } /// @@ -745,7 +782,7 @@ public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit, UnitConverter unit var converted = conversionFunction(this); return (StandardVolumeFlow)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(StandardVolumeFlowUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -753,17 +790,17 @@ public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit, UnitConverter unit } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is StandardVolumeFlowUnit unitAsStandardVolumeFlowUnit)) + if (!(unit is StandardVolumeFlowUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(StandardVolumeFlowUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsStandardVolumeFlowUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -790,10 +827,10 @@ public StandardVolumeFlow ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(StandardVolumeFlowUnit unit) + private QuantityValue GetValueAs(StandardVolumeFlowUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs index 9b314a7349..82d5b8ebe8 100644 --- a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics. /// [DataContract] - public partial struct Temperature : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Temperature : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -81,9 +81,9 @@ static Temperature() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Temperature(double value, TemperatureUnit unit) + public Temperature(QuantityValue value, TemperatureUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -95,14 +95,14 @@ public Temperature(double value, TemperatureUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Temperature(double value, UnitSystem unitSystem) + public Temperature(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -143,7 +143,10 @@ public Temperature(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -166,54 +169,54 @@ public Temperature(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesCelsius => As(TemperatureUnit.DegreeCelsius); + public QuantityValue DegreesCelsius => As(TemperatureUnit.DegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesDelisle => As(TemperatureUnit.DegreeDelisle); + public QuantityValue DegreesDelisle => As(TemperatureUnit.DegreeDelisle); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); + public QuantityValue DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesNewton => As(TemperatureUnit.DegreeNewton); + public QuantityValue DegreesNewton => As(TemperatureUnit.DegreeNewton); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesRankine => As(TemperatureUnit.DegreeRankine); + public QuantityValue DegreesRankine => As(TemperatureUnit.DegreeRankine); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesReaumur => As(TemperatureUnit.DegreeReaumur); + public QuantityValue DegreesReaumur => As(TemperatureUnit.DegreeReaumur); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesRoemer => As(TemperatureUnit.DegreeRoemer); + public QuantityValue DegreesRoemer => As(TemperatureUnit.DegreeRoemer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kelvins => As(TemperatureUnit.Kelvin); + public QuantityValue Kelvins => As(TemperatureUnit.Kelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillidegreesCelsius => As(TemperatureUnit.MillidegreeCelsius); + public QuantityValue MillidegreesCelsius => As(TemperatureUnit.MillidegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SolarTemperatures => As(TemperatureUnit.SolarTemperature); + public QuantityValue SolarTemperatures => As(TemperatureUnit.SolarTemperature); #endregion @@ -296,7 +299,7 @@ public static string GetAbbreviation(TemperatureUnit unit, IFormatProvider? prov /// If value is NaN or Infinity. public static Temperature FromDegreesCelsius(QuantityValue degreescelsius) { - double value = (double) degreescelsius; + QuantityValue value = (QuantityValue) degreescelsius; return new Temperature(value, TemperatureUnit.DegreeCelsius); } @@ -306,7 +309,7 @@ public static Temperature FromDegreesCelsius(QuantityValue degreescelsius) /// If value is NaN or Infinity. public static Temperature FromDegreesDelisle(QuantityValue degreesdelisle) { - double value = (double) degreesdelisle; + QuantityValue value = (QuantityValue) degreesdelisle; return new Temperature(value, TemperatureUnit.DegreeDelisle); } @@ -316,7 +319,7 @@ public static Temperature FromDegreesDelisle(QuantityValue degreesdelisle) /// If value is NaN or Infinity. public static Temperature FromDegreesFahrenheit(QuantityValue degreesfahrenheit) { - double value = (double) degreesfahrenheit; + QuantityValue value = (QuantityValue) degreesfahrenheit; return new Temperature(value, TemperatureUnit.DegreeFahrenheit); } @@ -326,7 +329,7 @@ public static Temperature FromDegreesFahrenheit(QuantityValue degreesfahrenheit) /// If value is NaN or Infinity. public static Temperature FromDegreesNewton(QuantityValue degreesnewton) { - double value = (double) degreesnewton; + QuantityValue value = (QuantityValue) degreesnewton; return new Temperature(value, TemperatureUnit.DegreeNewton); } @@ -336,7 +339,7 @@ public static Temperature FromDegreesNewton(QuantityValue degreesnewton) /// If value is NaN or Infinity. public static Temperature FromDegreesRankine(QuantityValue degreesrankine) { - double value = (double) degreesrankine; + QuantityValue value = (QuantityValue) degreesrankine; return new Temperature(value, TemperatureUnit.DegreeRankine); } @@ -346,7 +349,7 @@ public static Temperature FromDegreesRankine(QuantityValue degreesrankine) /// If value is NaN or Infinity. public static Temperature FromDegreesReaumur(QuantityValue degreesreaumur) { - double value = (double) degreesreaumur; + QuantityValue value = (QuantityValue) degreesreaumur; return new Temperature(value, TemperatureUnit.DegreeReaumur); } @@ -356,7 +359,7 @@ public static Temperature FromDegreesReaumur(QuantityValue degreesreaumur) /// If value is NaN or Infinity. public static Temperature FromDegreesRoemer(QuantityValue degreesroemer) { - double value = (double) degreesroemer; + QuantityValue value = (QuantityValue) degreesroemer; return new Temperature(value, TemperatureUnit.DegreeRoemer); } @@ -366,7 +369,7 @@ public static Temperature FromDegreesRoemer(QuantityValue degreesroemer) /// If value is NaN or Infinity. public static Temperature FromKelvins(QuantityValue kelvins) { - double value = (double) kelvins; + QuantityValue value = (QuantityValue) kelvins; return new Temperature(value, TemperatureUnit.Kelvin); } @@ -376,7 +379,7 @@ public static Temperature FromKelvins(QuantityValue kelvins) /// If value is NaN or Infinity. public static Temperature FromMillidegreesCelsius(QuantityValue millidegreescelsius) { - double value = (double) millidegreescelsius; + QuantityValue value = (QuantityValue) millidegreescelsius; return new Temperature(value, TemperatureUnit.MillidegreeCelsius); } @@ -386,7 +389,7 @@ public static Temperature FromMillidegreesCelsius(QuantityValue millidegreescels /// If value is NaN or Infinity. public static Temperature FromSolarTemperatures(QuantityValue solartemperatures) { - double value = (double) solartemperatures; + QuantityValue value = (QuantityValue) solartemperatures; return new Temperature(value, TemperatureUnit.SolarTemperature); } @@ -398,7 +401,7 @@ public static Temperature FromSolarTemperatures(QuantityValue solartemperatures) /// Temperature unit value. public static Temperature From(QuantityValue value, TemperatureUnit fromUnit) { - return new Temperature((double)value, fromUnit); + return new Temperature((QuantityValue)value, fromUnit); } #endregion @@ -573,6 +576,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Temperature left, Temperature right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Temperature left, Temperature right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -585,7 +601,29 @@ public int CompareTo(object obj) /// public int CompareTo(Temperature other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Temperature objTemperature)) + return false; + return Equals(objTemperature); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Temperature other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -628,13 +666,13 @@ public int CompareTo(Temperature other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Temperature other, double tolerance, ComparisonType comparisonType) + public bool Equals(Temperature other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -645,7 +683,7 @@ public bool Equals(Temperature other, double tolerance, ComparisonType compariso /// A hash code for the current Temperature. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -656,17 +694,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(TemperatureUnit unit) + public QuantityValue As(TemperatureUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -681,12 +718,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is TemperatureUnit unitAsTemperatureUnit)) + if (!(unit is TemperatureUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureUnit)} is supported.", nameof(unit)); - return As(unitAsTemperatureUnit); + return (QuantityValue)As(typedUnit); } /// @@ -718,7 +755,7 @@ public Temperature ToUnit(TemperatureUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Temperature)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(TemperatureUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -726,17 +763,17 @@ public Temperature ToUnit(TemperatureUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TemperatureUnit unitAsTemperatureUnit)) + if (!(unit is TemperatureUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTemperatureUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -763,10 +800,10 @@ public Temperature ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(TemperatureUnit unit) + private QuantityValue GetValueAs(TemperatureUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs index 0f3704b67e..a832939860 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time). /// [DataContract] - public partial struct TemperatureChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct TemperatureChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -81,9 +81,9 @@ static TemperatureChangeRate() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public TemperatureChangeRate(double value, TemperatureChangeRateUnit unit) + public TemperatureChangeRate(QuantityValue value, TemperatureChangeRateUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -95,14 +95,14 @@ public TemperatureChangeRate(double value, TemperatureChangeRateUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public TemperatureChangeRate(double value, UnitSystem unitSystem) + public TemperatureChangeRate(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -143,7 +143,10 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -166,54 +169,54 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); + public QuantityValue CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); + public QuantityValue DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); + public QuantityValue DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); + public QuantityValue DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); + public QuantityValue DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + public QuantityValue HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + public QuantityValue KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + public QuantityValue MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + public QuantityValue MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); + public QuantityValue NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); #endregion @@ -296,7 +299,7 @@ public static string GetAbbreviation(TemperatureChangeRateUnit unit, IFormatProv /// If value is NaN or Infinity. public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityValue centidegreescelsiuspersecond) { - double value = (double) centidegreescelsiuspersecond; + QuantityValue value = (QuantityValue) centidegreescelsiuspersecond; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); } @@ -306,7 +309,7 @@ public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityVal /// If value is NaN or Infinity. public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValue decadegreescelsiuspersecond) { - double value = (double) decadegreescelsiuspersecond; + QuantityValue value = (QuantityValue) decadegreescelsiuspersecond; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); } @@ -316,7 +319,7 @@ public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValu /// If value is NaN or Infinity. public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValue decidegreescelsiuspersecond) { - double value = (double) decidegreescelsiuspersecond; + QuantityValue value = (QuantityValue) decidegreescelsiuspersecond; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); } @@ -326,7 +329,7 @@ public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValu /// If value is NaN or Infinity. public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue degreescelsiusperminute) { - double value = (double) degreescelsiusperminute; + QuantityValue value = (QuantityValue) degreescelsiusperminute; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); } @@ -336,7 +339,7 @@ public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue de /// If value is NaN or Infinity. public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue degreescelsiuspersecond) { - double value = (double) degreescelsiuspersecond; + QuantityValue value = (QuantityValue) degreescelsiuspersecond; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); } @@ -346,7 +349,7 @@ public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue de /// If value is NaN or Infinity. public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityValue hectodegreescelsiuspersecond) { - double value = (double) hectodegreescelsiuspersecond; + QuantityValue value = (QuantityValue) hectodegreescelsiuspersecond; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); } @@ -356,7 +359,7 @@ public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityVal /// If value is NaN or Infinity. public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValue kilodegreescelsiuspersecond) { - double value = (double) kilodegreescelsiuspersecond; + QuantityValue value = (QuantityValue) kilodegreescelsiuspersecond; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); } @@ -366,7 +369,7 @@ public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValu /// If value is NaN or Infinity. public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityValue microdegreescelsiuspersecond) { - double value = (double) microdegreescelsiuspersecond; + QuantityValue value = (QuantityValue) microdegreescelsiuspersecond; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); } @@ -376,7 +379,7 @@ public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityVal /// If value is NaN or Infinity. public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityValue millidegreescelsiuspersecond) { - double value = (double) millidegreescelsiuspersecond; + QuantityValue value = (QuantityValue) millidegreescelsiuspersecond; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); } @@ -386,7 +389,7 @@ public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityVal /// If value is NaN or Infinity. public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(QuantityValue nanodegreescelsiuspersecond) { - double value = (double) nanodegreescelsiuspersecond; + QuantityValue value = (QuantityValue) nanodegreescelsiuspersecond; return new TemperatureChangeRate(value, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); } @@ -398,7 +401,7 @@ public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(QuantityValu /// TemperatureChangeRate unit value. public static TemperatureChangeRate From(QuantityValue value, TemperatureChangeRateUnit fromUnit) { - return new TemperatureChangeRate((double)value, fromUnit); + return new TemperatureChangeRate((QuantityValue)value, fromUnit); } #endregion @@ -568,25 +571,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe } /// Get from multiplying value and . - public static TemperatureChangeRate operator *(double left, TemperatureChangeRate right) + public static TemperatureChangeRate operator *(QuantityValue left, TemperatureChangeRate right) { return new TemperatureChangeRate(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static TemperatureChangeRate operator *(TemperatureChangeRate left, double right) + public static TemperatureChangeRate operator *(TemperatureChangeRate left, QuantityValue right) { return new TemperatureChangeRate(left.Value * right, left.Unit); } /// Get from dividing by value. - public static TemperatureChangeRate operator /(TemperatureChangeRate left, double right) + public static TemperatureChangeRate operator /(TemperatureChangeRate left, QuantityValue right) { return new TemperatureChangeRate(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(TemperatureChangeRate left, TemperatureChangeRate right) + public static QuantityValue operator /(TemperatureChangeRate left, TemperatureChangeRate right) { return left.DegreesCelsiusPerSecond / right.DegreesCelsiusPerSecond; } @@ -619,6 +622,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(TemperatureChangeRate left, TemperatureChangeRate right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -631,7 +647,29 @@ public int CompareTo(object obj) /// public int CompareTo(TemperatureChangeRate other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is TemperatureChangeRate objTemperatureChangeRate)) + return false; + return Equals(objTemperatureChangeRate); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(TemperatureChangeRate other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -674,13 +712,13 @@ public int CompareTo(TemperatureChangeRate other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(TemperatureChangeRate other, double tolerance, ComparisonType comparisonType) + public bool Equals(TemperatureChangeRate other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -691,7 +729,7 @@ public bool Equals(TemperatureChangeRate other, double tolerance, ComparisonType /// A hash code for the current TemperatureChangeRate. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -702,17 +740,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(TemperatureChangeRateUnit unit) + public QuantityValue As(TemperatureChangeRateUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -727,12 +764,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is TemperatureChangeRateUnit unitAsTemperatureChangeRateUnit)) + if (!(unit is TemperatureChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsTemperatureChangeRateUnit); + return (QuantityValue)As(typedUnit); } /// @@ -764,7 +801,7 @@ public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit, UnitConverte var converted = conversionFunction(this); return (TemperatureChangeRate)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(TemperatureChangeRateUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -772,17 +809,17 @@ public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit, UnitConverte } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TemperatureChangeRateUnit unitAsTemperatureChangeRateUnit)) + if (!(unit is TemperatureChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureChangeRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTemperatureChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -809,10 +846,10 @@ public TemperatureChangeRate ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(TemperatureChangeRateUnit unit) + private QuantityValue GetValueAs(TemperatureChangeRateUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs index 5fb8eaf2ac..94d9813fe9 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Difference between two temperatures. The conversions are different than for Temperature. /// [DataContract] - public partial struct TemperatureDelta : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct TemperatureDelta : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -80,9 +80,9 @@ static TemperatureDelta() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public TemperatureDelta(double value, TemperatureDeltaUnit unit) + public TemperatureDelta(QuantityValue value, TemperatureDeltaUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -94,14 +94,14 @@ public TemperatureDelta(double value, TemperatureDeltaUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public TemperatureDelta(double value, UnitSystem unitSystem) + public TemperatureDelta(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -142,7 +142,10 @@ public TemperatureDelta(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -165,49 +168,49 @@ public TemperatureDelta(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); + public QuantityValue DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); + public QuantityValue DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); + public QuantityValue DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); + public QuantityValue DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); + public QuantityValue DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); + public QuantityValue DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); + public QuantityValue DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kelvins => As(TemperatureDeltaUnit.Kelvin); + public QuantityValue Kelvins => As(TemperatureDeltaUnit.Kelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillidegreesCelsius => As(TemperatureDeltaUnit.MillidegreeCelsius); + public QuantityValue MillidegreesCelsius => As(TemperatureDeltaUnit.MillidegreeCelsius); #endregion @@ -287,7 +290,7 @@ public static string GetAbbreviation(TemperatureDeltaUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static TemperatureDelta FromDegreesCelsius(QuantityValue degreescelsius) { - double value = (double) degreescelsius; + QuantityValue value = (QuantityValue) degreescelsius; return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); } @@ -297,7 +300,7 @@ public static TemperatureDelta FromDegreesCelsius(QuantityValue degreescelsius) /// If value is NaN or Infinity. public static TemperatureDelta FromDegreesDelisle(QuantityValue degreesdelisle) { - double value = (double) degreesdelisle; + QuantityValue value = (QuantityValue) degreesdelisle; return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); } @@ -307,7 +310,7 @@ public static TemperatureDelta FromDegreesDelisle(QuantityValue degreesdelisle) /// If value is NaN or Infinity. public static TemperatureDelta FromDegreesFahrenheit(QuantityValue degreesfahrenheit) { - double value = (double) degreesfahrenheit; + QuantityValue value = (QuantityValue) degreesfahrenheit; return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); } @@ -317,7 +320,7 @@ public static TemperatureDelta FromDegreesFahrenheit(QuantityValue degreesfahren /// If value is NaN or Infinity. public static TemperatureDelta FromDegreesNewton(QuantityValue degreesnewton) { - double value = (double) degreesnewton; + QuantityValue value = (QuantityValue) degreesnewton; return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); } @@ -327,7 +330,7 @@ public static TemperatureDelta FromDegreesNewton(QuantityValue degreesnewton) /// If value is NaN or Infinity. public static TemperatureDelta FromDegreesRankine(QuantityValue degreesrankine) { - double value = (double) degreesrankine; + QuantityValue value = (QuantityValue) degreesrankine; return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); } @@ -337,7 +340,7 @@ public static TemperatureDelta FromDegreesRankine(QuantityValue degreesrankine) /// If value is NaN or Infinity. public static TemperatureDelta FromDegreesReaumur(QuantityValue degreesreaumur) { - double value = (double) degreesreaumur; + QuantityValue value = (QuantityValue) degreesreaumur; return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); } @@ -347,7 +350,7 @@ public static TemperatureDelta FromDegreesReaumur(QuantityValue degreesreaumur) /// If value is NaN or Infinity. public static TemperatureDelta FromDegreesRoemer(QuantityValue degreesroemer) { - double value = (double) degreesroemer; + QuantityValue value = (QuantityValue) degreesroemer; return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); } @@ -357,7 +360,7 @@ public static TemperatureDelta FromDegreesRoemer(QuantityValue degreesroemer) /// If value is NaN or Infinity. public static TemperatureDelta FromKelvins(QuantityValue kelvins) { - double value = (double) kelvins; + QuantityValue value = (QuantityValue) kelvins; return new TemperatureDelta(value, TemperatureDeltaUnit.Kelvin); } @@ -367,7 +370,7 @@ public static TemperatureDelta FromKelvins(QuantityValue kelvins) /// If value is NaN or Infinity. public static TemperatureDelta FromMillidegreesCelsius(QuantityValue millidegreescelsius) { - double value = (double) millidegreescelsius; + QuantityValue value = (QuantityValue) millidegreescelsius; return new TemperatureDelta(value, TemperatureDeltaUnit.MillidegreeCelsius); } @@ -379,7 +382,7 @@ public static TemperatureDelta FromMillidegreesCelsius(QuantityValue millidegree /// TemperatureDelta unit value. public static TemperatureDelta From(QuantityValue value, TemperatureDeltaUnit fromUnit) { - return new TemperatureDelta((double)value, fromUnit); + return new TemperatureDelta((QuantityValue)value, fromUnit); } #endregion @@ -549,25 +552,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe } /// Get from multiplying value and . - public static TemperatureDelta operator *(double left, TemperatureDelta right) + public static TemperatureDelta operator *(QuantityValue left, TemperatureDelta right) { return new TemperatureDelta(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static TemperatureDelta operator *(TemperatureDelta left, double right) + public static TemperatureDelta operator *(TemperatureDelta left, QuantityValue right) { return new TemperatureDelta(left.Value * right, left.Unit); } /// Get from dividing by value. - public static TemperatureDelta operator /(TemperatureDelta left, double right) + public static TemperatureDelta operator /(TemperatureDelta left, QuantityValue right) { return new TemperatureDelta(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(TemperatureDelta left, TemperatureDelta right) + public static QuantityValue operator /(TemperatureDelta left, TemperatureDelta right) { return left.Kelvins / right.Kelvins; } @@ -600,6 +603,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(TemperatureDelta left, TemperatureDelta right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(TemperatureDelta left, TemperatureDelta right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -612,7 +628,29 @@ public int CompareTo(object obj) /// public int CompareTo(TemperatureDelta other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is TemperatureDelta objTemperatureDelta)) + return false; + return Equals(objTemperatureDelta); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(TemperatureDelta other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -655,13 +693,13 @@ public int CompareTo(TemperatureDelta other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(TemperatureDelta other, double tolerance, ComparisonType comparisonType) + public bool Equals(TemperatureDelta other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -672,7 +710,7 @@ public bool Equals(TemperatureDelta other, double tolerance, ComparisonType comp /// A hash code for the current TemperatureDelta. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -683,17 +721,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(TemperatureDeltaUnit unit) + public QuantityValue As(TemperatureDeltaUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -708,12 +745,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is TemperatureDeltaUnit unitAsTemperatureDeltaUnit)) + if (!(unit is TemperatureDeltaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureDeltaUnit)} is supported.", nameof(unit)); - return As(unitAsTemperatureDeltaUnit); + return (QuantityValue)As(typedUnit); } /// @@ -745,7 +782,7 @@ public TemperatureDelta ToUnit(TemperatureDeltaUnit unit, UnitConverter unitConv var converted = conversionFunction(this); return (TemperatureDelta)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(TemperatureDeltaUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -753,17 +790,17 @@ public TemperatureDelta ToUnit(TemperatureDeltaUnit unit, UnitConverter unitConv } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TemperatureDeltaUnit unitAsTemperatureDeltaUnit)) + if (!(unit is TemperatureDeltaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureDeltaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTemperatureDeltaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -790,10 +827,10 @@ public TemperatureDelta ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(TemperatureDeltaUnit unit) + private QuantityValue GetValueAs(TemperatureDeltaUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs index aaff14abca..1d2405a4e2 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// /// [DataContract] - public partial struct TemperatureGradient : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct TemperatureGradient : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static TemperatureGradient() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public TemperatureGradient(double value, TemperatureGradientUnit unit) + public TemperatureGradient(QuantityValue value, TemperatureGradientUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public TemperatureGradient(double value, TemperatureGradientUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public TemperatureGradient(double value, UnitSystem unitSystem) + public TemperatureGradient(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public TemperatureGradient(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,24 +163,24 @@ public TemperatureGradient(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesCelciusPerKilometer => As(TemperatureGradientUnit.DegreeCelsiusPerKilometer); + public QuantityValue DegreesCelciusPerKilometer => As(TemperatureGradientUnit.DegreeCelsiusPerKilometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesCelciusPerMeter => As(TemperatureGradientUnit.DegreeCelsiusPerMeter); + public QuantityValue DegreesCelciusPerMeter => As(TemperatureGradientUnit.DegreeCelsiusPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DegreesFahrenheitPerFoot => As(TemperatureGradientUnit.DegreeFahrenheitPerFoot); + public QuantityValue DegreesFahrenheitPerFoot => As(TemperatureGradientUnit.DegreeFahrenheitPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KelvinsPerMeter => As(TemperatureGradientUnit.KelvinPerMeter); + public QuantityValue KelvinsPerMeter => As(TemperatureGradientUnit.KelvinPerMeter); #endregion @@ -242,7 +245,7 @@ public static string GetAbbreviation(TemperatureGradientUnit unit, IFormatProvid /// If value is NaN or Infinity. public static TemperatureGradient FromDegreesCelciusPerKilometer(QuantityValue degreescelciusperkilometer) { - double value = (double) degreescelciusperkilometer; + QuantityValue value = (QuantityValue) degreescelciusperkilometer; return new TemperatureGradient(value, TemperatureGradientUnit.DegreeCelsiusPerKilometer); } @@ -252,7 +255,7 @@ public static TemperatureGradient FromDegreesCelciusPerKilometer(QuantityValue d /// If value is NaN or Infinity. public static TemperatureGradient FromDegreesCelciusPerMeter(QuantityValue degreescelciuspermeter) { - double value = (double) degreescelciuspermeter; + QuantityValue value = (QuantityValue) degreescelciuspermeter; return new TemperatureGradient(value, TemperatureGradientUnit.DegreeCelsiusPerMeter); } @@ -262,7 +265,7 @@ public static TemperatureGradient FromDegreesCelciusPerMeter(QuantityValue degre /// If value is NaN or Infinity. public static TemperatureGradient FromDegreesFahrenheitPerFoot(QuantityValue degreesfahrenheitperfoot) { - double value = (double) degreesfahrenheitperfoot; + QuantityValue value = (QuantityValue) degreesfahrenheitperfoot; return new TemperatureGradient(value, TemperatureGradientUnit.DegreeFahrenheitPerFoot); } @@ -272,7 +275,7 @@ public static TemperatureGradient FromDegreesFahrenheitPerFoot(QuantityValue deg /// If value is NaN or Infinity. public static TemperatureGradient FromKelvinsPerMeter(QuantityValue kelvinspermeter) { - double value = (double) kelvinspermeter; + QuantityValue value = (QuantityValue) kelvinspermeter; return new TemperatureGradient(value, TemperatureGradientUnit.KelvinPerMeter); } @@ -284,7 +287,7 @@ public static TemperatureGradient FromKelvinsPerMeter(QuantityValue kelvinsperme /// TemperatureGradient unit value. public static TemperatureGradient From(QuantityValue value, TemperatureGradientUnit fromUnit) { - return new TemperatureGradient((double)value, fromUnit); + return new TemperatureGradient((QuantityValue)value, fromUnit); } #endregion @@ -454,25 +457,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe } /// Get from multiplying value and . - public static TemperatureGradient operator *(double left, TemperatureGradient right) + public static TemperatureGradient operator *(QuantityValue left, TemperatureGradient right) { return new TemperatureGradient(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static TemperatureGradient operator *(TemperatureGradient left, double right) + public static TemperatureGradient operator *(TemperatureGradient left, QuantityValue right) { return new TemperatureGradient(left.Value * right, left.Unit); } /// Get from dividing by value. - public static TemperatureGradient operator /(TemperatureGradient left, double right) + public static TemperatureGradient operator /(TemperatureGradient left, QuantityValue right) { return new TemperatureGradient(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(TemperatureGradient left, TemperatureGradient right) + public static QuantityValue operator /(TemperatureGradient left, TemperatureGradient right) { return left.KelvinsPerMeter / right.KelvinsPerMeter; } @@ -505,6 +508,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(TemperatureGradient left, TemperatureGradient right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(TemperatureGradient left, TemperatureGradient right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -517,7 +533,29 @@ public int CompareTo(object obj) /// public int CompareTo(TemperatureGradient other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is TemperatureGradient objTemperatureGradient)) + return false; + return Equals(objTemperatureGradient); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(TemperatureGradient other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -560,13 +598,13 @@ public int CompareTo(TemperatureGradient other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(TemperatureGradient other, double tolerance, ComparisonType comparisonType) + public bool Equals(TemperatureGradient other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -577,7 +615,7 @@ public bool Equals(TemperatureGradient other, double tolerance, ComparisonType c /// A hash code for the current TemperatureGradient. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -588,17 +626,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(TemperatureGradientUnit unit) + public QuantityValue As(TemperatureGradientUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -613,12 +650,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is TemperatureGradientUnit unitAsTemperatureGradientUnit)) + if (!(unit is TemperatureGradientUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureGradientUnit)} is supported.", nameof(unit)); - return As(unitAsTemperatureGradientUnit); + return (QuantityValue)As(typedUnit); } /// @@ -650,7 +687,7 @@ public TemperatureGradient ToUnit(TemperatureGradientUnit unit, UnitConverter un var converted = conversionFunction(this); return (TemperatureGradient)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(TemperatureGradientUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -658,17 +695,17 @@ public TemperatureGradient ToUnit(TemperatureGradientUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TemperatureGradientUnit unitAsTemperatureGradientUnit)) + if (!(unit is TemperatureGradientUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureGradientUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTemperatureGradientUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -695,10 +732,10 @@ public TemperatureGradient ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(TemperatureGradientUnit unit) + private QuantityValue GetValueAs(TemperatureGradientUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs index 0da7968b47..2dea56e22d 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Thermal_Conductivity /// [DataContract] - public partial struct ThermalConductivity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ThermalConductivity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -76,9 +76,9 @@ static ThermalConductivity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ThermalConductivity(double value, ThermalConductivityUnit unit) + public ThermalConductivity(QuantityValue value, ThermalConductivityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -90,14 +90,14 @@ public ThermalConductivity(double value, ThermalConductivityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ThermalConductivity(double value, UnitSystem unitSystem) + public ThermalConductivity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -138,7 +138,10 @@ public ThermalConductivity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -161,14 +164,14 @@ public ThermalConductivity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); + public QuantityValue BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); + public QuantityValue WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); #endregion @@ -227,7 +230,7 @@ public static string GetAbbreviation(ThermalConductivityUnit unit, IFormatProvid /// If value is NaN or Infinity. public static ThermalConductivity FromBtusPerHourFootFahrenheit(QuantityValue btusperhourfootfahrenheit) { - double value = (double) btusperhourfootfahrenheit; + QuantityValue value = (QuantityValue) btusperhourfootfahrenheit; return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); } @@ -237,7 +240,7 @@ public static ThermalConductivity FromBtusPerHourFootFahrenheit(QuantityValue bt /// If value is NaN or Infinity. public static ThermalConductivity FromWattsPerMeterKelvin(QuantityValue wattspermeterkelvin) { - double value = (double) wattspermeterkelvin; + QuantityValue value = (QuantityValue) wattspermeterkelvin; return new ThermalConductivity(value, ThermalConductivityUnit.WattPerMeterKelvin); } @@ -249,7 +252,7 @@ public static ThermalConductivity FromWattsPerMeterKelvin(QuantityValue wattsper /// ThermalConductivity unit value. public static ThermalConductivity From(QuantityValue value, ThermalConductivityUnit fromUnit) { - return new ThermalConductivity((double)value, fromUnit); + return new ThermalConductivity((QuantityValue)value, fromUnit); } #endregion @@ -419,25 +422,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Therm } /// Get from multiplying value and . - public static ThermalConductivity operator *(double left, ThermalConductivity right) + public static ThermalConductivity operator *(QuantityValue left, ThermalConductivity right) { return new ThermalConductivity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ThermalConductivity operator *(ThermalConductivity left, double right) + public static ThermalConductivity operator *(ThermalConductivity left, QuantityValue right) { return new ThermalConductivity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ThermalConductivity operator /(ThermalConductivity left, double right) + public static ThermalConductivity operator /(ThermalConductivity left, QuantityValue right) { return new ThermalConductivity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ThermalConductivity left, ThermalConductivity right) + public static QuantityValue operator /(ThermalConductivity left, ThermalConductivity right) { return left.WattsPerMeterKelvin / right.WattsPerMeterKelvin; } @@ -470,6 +473,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Therm return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ThermalConductivity left, ThermalConductivity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ThermalConductivity left, ThermalConductivity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -482,7 +498,29 @@ public int CompareTo(object obj) /// public int CompareTo(ThermalConductivity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ThermalConductivity objThermalConductivity)) + return false; + return Equals(objThermalConductivity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ThermalConductivity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -525,13 +563,13 @@ public int CompareTo(ThermalConductivity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ThermalConductivity other, double tolerance, ComparisonType comparisonType) + public bool Equals(ThermalConductivity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -542,7 +580,7 @@ public bool Equals(ThermalConductivity other, double tolerance, ComparisonType c /// A hash code for the current ThermalConductivity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -553,17 +591,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ThermalConductivityUnit unit) + public QuantityValue As(ThermalConductivityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -578,12 +615,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ThermalConductivityUnit unitAsThermalConductivityUnit)) + if (!(unit is ThermalConductivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalConductivityUnit)} is supported.", nameof(unit)); - return As(unitAsThermalConductivityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -615,7 +652,7 @@ public ThermalConductivity ToUnit(ThermalConductivityUnit unit, UnitConverter un var converted = conversionFunction(this); return (ThermalConductivity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ThermalConductivityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -623,17 +660,17 @@ public ThermalConductivity ToUnit(ThermalConductivityUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ThermalConductivityUnit unitAsThermalConductivityUnit)) + if (!(unit is ThermalConductivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalConductivityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsThermalConductivityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -660,10 +697,10 @@ public ThermalConductivity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ThermalConductivityUnit unit) + private QuantityValue GetValueAs(ThermalConductivityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs index 7ab40b994c..520040cd26 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. /// [DataContract] - public partial struct ThermalResistance : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct ThermalResistance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -77,9 +77,9 @@ static ThermalResistance() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public ThermalResistance(double value, ThermalResistanceUnit unit) + public ThermalResistance(QuantityValue value, ThermalResistanceUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -91,14 +91,14 @@ public ThermalResistance(double value, ThermalResistanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ThermalResistance(double value, UnitSystem unitSystem) + public ThermalResistance(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -139,7 +139,10 @@ public ThermalResistance(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -162,34 +165,34 @@ public ThermalResistance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + public QuantityValue HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + public QuantityValue SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareCentimeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); + public QuantityValue SquareCentimeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareMeterDegreesCelsiusPerWatt => As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); + public QuantityValue SquareMeterDegreesCelsiusPerWatt => As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareMeterKelvinsPerKilowatt => As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); + public QuantityValue SquareMeterKelvinsPerKilowatt => As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double SquareMeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareMeterKelvinPerWatt); + public QuantityValue SquareMeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareMeterKelvinPerWatt); #endregion @@ -260,7 +263,7 @@ public static string GetAbbreviation(ThermalResistanceUnit unit, IFormatProvider /// If value is NaN or Infinity. public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue hoursquarefeetdegreesfahrenheitperbtu) { - double value = (double) hoursquarefeetdegreesfahrenheitperbtu; + QuantityValue value = (QuantityValue) hoursquarefeetdegreesfahrenheitperbtu; return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); } @@ -270,7 +273,7 @@ public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(Quanti /// If value is NaN or Infinity. public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue squarecentimeterhourdegreescelsiusperkilocalorie) { - double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; + QuantityValue value = (QuantityValue) squarecentimeterhourdegreescelsiusperkilocalorie; return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); } @@ -280,7 +283,7 @@ public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocal /// If value is NaN or Infinity. public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(QuantityValue squarecentimeterkelvinsperwatt) { - double value = (double) squarecentimeterkelvinsperwatt; + QuantityValue value = (QuantityValue) squarecentimeterkelvinsperwatt; return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); } @@ -290,7 +293,7 @@ public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(QuantityValue /// If value is NaN or Infinity. public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(QuantityValue squaremeterdegreescelsiusperwatt) { - double value = (double) squaremeterdegreescelsiusperwatt; + QuantityValue value = (QuantityValue) squaremeterdegreescelsiusperwatt; return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); } @@ -300,7 +303,7 @@ public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(QuantityVal /// If value is NaN or Infinity. public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(QuantityValue squaremeterkelvinsperkilowatt) { - double value = (double) squaremeterkelvinsperkilowatt; + QuantityValue value = (QuantityValue) squaremeterkelvinsperkilowatt; return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); } @@ -310,7 +313,7 @@ public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(QuantityValue /// If value is NaN or Infinity. public static ThermalResistance FromSquareMeterKelvinsPerWatt(QuantityValue squaremeterkelvinsperwatt) { - double value = (double) squaremeterkelvinsperwatt; + QuantityValue value = (QuantityValue) squaremeterkelvinsperwatt; return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerWatt); } @@ -322,7 +325,7 @@ public static ThermalResistance FromSquareMeterKelvinsPerWatt(QuantityValue squa /// ThermalResistance unit value. public static ThermalResistance From(QuantityValue value, ThermalResistanceUnit fromUnit) { - return new ThermalResistance((double)value, fromUnit); + return new ThermalResistance((QuantityValue)value, fromUnit); } #endregion @@ -492,25 +495,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Therm } /// Get from multiplying value and . - public static ThermalResistance operator *(double left, ThermalResistance right) + public static ThermalResistance operator *(QuantityValue left, ThermalResistance right) { return new ThermalResistance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ThermalResistance operator *(ThermalResistance left, double right) + public static ThermalResistance operator *(ThermalResistance left, QuantityValue right) { return new ThermalResistance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ThermalResistance operator /(ThermalResistance left, double right) + public static ThermalResistance operator /(ThermalResistance left, QuantityValue right) { return new ThermalResistance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ThermalResistance left, ThermalResistance right) + public static QuantityValue operator /(ThermalResistance left, ThermalResistance right) { return left.SquareMeterKelvinsPerKilowatt / right.SquareMeterKelvinsPerKilowatt; } @@ -543,6 +546,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Therm return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(ThermalResistance left, ThermalResistance right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(ThermalResistance left, ThermalResistance right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -555,7 +571,29 @@ public int CompareTo(object obj) /// public int CompareTo(ThermalResistance other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is ThermalResistance objThermalResistance)) + return false; + return Equals(objThermalResistance); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(ThermalResistance other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -598,13 +636,13 @@ public int CompareTo(ThermalResistance other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ThermalResistance other, double tolerance, ComparisonType comparisonType) + public bool Equals(ThermalResistance other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -615,7 +653,7 @@ public bool Equals(ThermalResistance other, double tolerance, ComparisonType com /// A hash code for the current ThermalResistance. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -626,17 +664,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(ThermalResistanceUnit unit) + public QuantityValue As(ThermalResistanceUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -651,12 +688,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is ThermalResistanceUnit unitAsThermalResistanceUnit)) + if (!(unit is ThermalResistanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalResistanceUnit)} is supported.", nameof(unit)); - return As(unitAsThermalResistanceUnit); + return (QuantityValue)As(typedUnit); } /// @@ -688,7 +725,7 @@ public ThermalResistance ToUnit(ThermalResistanceUnit unit, UnitConverter unitCo var converted = conversionFunction(this); return (ThermalResistance)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(ThermalResistanceUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -696,17 +733,17 @@ public ThermalResistance ToUnit(ThermalResistanceUnit unit, UnitConverter unitCo } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ThermalResistanceUnit unitAsThermalResistanceUnit)) + if (!(unit is ThermalResistanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalResistanceUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsThermalResistanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -733,10 +770,10 @@ public ThermalResistance ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(ThermalResistanceUnit unit) + private QuantityValue GetValueAs(ThermalResistanceUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs index 2a512729ec..de02228368 100644 --- a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt. /// [DataContract] - public partial struct Torque : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Torque : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -96,9 +96,9 @@ static Torque() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Torque(double value, TorqueUnit unit) + public Torque(QuantityValue value, TorqueUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -110,14 +110,14 @@ public Torque(double value, TorqueUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Torque(double value, UnitSystem unitSystem) + public Torque(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -158,7 +158,10 @@ public Torque(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -181,129 +184,129 @@ public Torque(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramForceCentimeters => As(TorqueUnit.GramForceCentimeter); + public QuantityValue GramForceCentimeters => As(TorqueUnit.GramForceCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramForceMeters => As(TorqueUnit.GramForceMeter); + public QuantityValue GramForceMeters => As(TorqueUnit.GramForceMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double GramForceMillimeters => As(TorqueUnit.GramForceMillimeter); + public QuantityValue GramForceMillimeters => As(TorqueUnit.GramForceMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); + public QuantityValue KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); + public QuantityValue KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); + public QuantityValue KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); + public QuantityValue KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); + public QuantityValue KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); + public QuantityValue KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); + public QuantityValue KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); + public QuantityValue KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); + public QuantityValue MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); + public QuantityValue MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); + public QuantityValue MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); + public QuantityValue MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); + public QuantityValue MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); + public QuantityValue NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonMeters => As(TorqueUnit.NewtonMeter); + public QuantityValue NewtonMeters => As(TorqueUnit.NewtonMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); + public QuantityValue NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundalFeet => As(TorqueUnit.PoundalFoot); + public QuantityValue PoundalFeet => As(TorqueUnit.PoundalFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundForceFeet => As(TorqueUnit.PoundForceFoot); + public QuantityValue PoundForceFeet => As(TorqueUnit.PoundForceFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundForceInches => As(TorqueUnit.PoundForceInch); + public QuantityValue PoundForceInches => As(TorqueUnit.PoundForceInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); + public QuantityValue TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneForceMeters => As(TorqueUnit.TonneForceMeter); + public QuantityValue TonneForceMeters => As(TorqueUnit.TonneForceMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); + public QuantityValue TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); #endregion @@ -434,7 +437,7 @@ public static string GetAbbreviation(TorqueUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Torque FromGramForceCentimeters(QuantityValue gramforcecentimeters) { - double value = (double) gramforcecentimeters; + QuantityValue value = (QuantityValue) gramforcecentimeters; return new Torque(value, TorqueUnit.GramForceCentimeter); } @@ -444,7 +447,7 @@ public static Torque FromGramForceCentimeters(QuantityValue gramforcecentimeters /// If value is NaN or Infinity. public static Torque FromGramForceMeters(QuantityValue gramforcemeters) { - double value = (double) gramforcemeters; + QuantityValue value = (QuantityValue) gramforcemeters; return new Torque(value, TorqueUnit.GramForceMeter); } @@ -454,7 +457,7 @@ public static Torque FromGramForceMeters(QuantityValue gramforcemeters) /// If value is NaN or Infinity. public static Torque FromGramForceMillimeters(QuantityValue gramforcemillimeters) { - double value = (double) gramforcemillimeters; + QuantityValue value = (QuantityValue) gramforcemillimeters; return new Torque(value, TorqueUnit.GramForceMillimeter); } @@ -464,7 +467,7 @@ public static Torque FromGramForceMillimeters(QuantityValue gramforcemillimeters /// If value is NaN or Infinity. public static Torque FromKilogramForceCentimeters(QuantityValue kilogramforcecentimeters) { - double value = (double) kilogramforcecentimeters; + QuantityValue value = (QuantityValue) kilogramforcecentimeters; return new Torque(value, TorqueUnit.KilogramForceCentimeter); } @@ -474,7 +477,7 @@ public static Torque FromKilogramForceCentimeters(QuantityValue kilogramforcecen /// If value is NaN or Infinity. public static Torque FromKilogramForceMeters(QuantityValue kilogramforcemeters) { - double value = (double) kilogramforcemeters; + QuantityValue value = (QuantityValue) kilogramforcemeters; return new Torque(value, TorqueUnit.KilogramForceMeter); } @@ -484,7 +487,7 @@ public static Torque FromKilogramForceMeters(QuantityValue kilogramforcemeters) /// If value is NaN or Infinity. public static Torque FromKilogramForceMillimeters(QuantityValue kilogramforcemillimeters) { - double value = (double) kilogramforcemillimeters; + QuantityValue value = (QuantityValue) kilogramforcemillimeters; return new Torque(value, TorqueUnit.KilogramForceMillimeter); } @@ -494,7 +497,7 @@ public static Torque FromKilogramForceMillimeters(QuantityValue kilogramforcemil /// If value is NaN or Infinity. public static Torque FromKilonewtonCentimeters(QuantityValue kilonewtoncentimeters) { - double value = (double) kilonewtoncentimeters; + QuantityValue value = (QuantityValue) kilonewtoncentimeters; return new Torque(value, TorqueUnit.KilonewtonCentimeter); } @@ -504,7 +507,7 @@ public static Torque FromKilonewtonCentimeters(QuantityValue kilonewtoncentimete /// If value is NaN or Infinity. public static Torque FromKilonewtonMeters(QuantityValue kilonewtonmeters) { - double value = (double) kilonewtonmeters; + QuantityValue value = (QuantityValue) kilonewtonmeters; return new Torque(value, TorqueUnit.KilonewtonMeter); } @@ -514,7 +517,7 @@ public static Torque FromKilonewtonMeters(QuantityValue kilonewtonmeters) /// If value is NaN or Infinity. public static Torque FromKilonewtonMillimeters(QuantityValue kilonewtonmillimeters) { - double value = (double) kilonewtonmillimeters; + QuantityValue value = (QuantityValue) kilonewtonmillimeters; return new Torque(value, TorqueUnit.KilonewtonMillimeter); } @@ -524,7 +527,7 @@ public static Torque FromKilonewtonMillimeters(QuantityValue kilonewtonmillimete /// If value is NaN or Infinity. public static Torque FromKilopoundForceFeet(QuantityValue kilopoundforcefeet) { - double value = (double) kilopoundforcefeet; + QuantityValue value = (QuantityValue) kilopoundforcefeet; return new Torque(value, TorqueUnit.KilopoundForceFoot); } @@ -534,7 +537,7 @@ public static Torque FromKilopoundForceFeet(QuantityValue kilopoundforcefeet) /// If value is NaN or Infinity. public static Torque FromKilopoundForceInches(QuantityValue kilopoundforceinches) { - double value = (double) kilopoundforceinches; + QuantityValue value = (QuantityValue) kilopoundforceinches; return new Torque(value, TorqueUnit.KilopoundForceInch); } @@ -544,7 +547,7 @@ public static Torque FromKilopoundForceInches(QuantityValue kilopoundforceinches /// If value is NaN or Infinity. public static Torque FromMeganewtonCentimeters(QuantityValue meganewtoncentimeters) { - double value = (double) meganewtoncentimeters; + QuantityValue value = (QuantityValue) meganewtoncentimeters; return new Torque(value, TorqueUnit.MeganewtonCentimeter); } @@ -554,7 +557,7 @@ public static Torque FromMeganewtonCentimeters(QuantityValue meganewtoncentimete /// If value is NaN or Infinity. public static Torque FromMeganewtonMeters(QuantityValue meganewtonmeters) { - double value = (double) meganewtonmeters; + QuantityValue value = (QuantityValue) meganewtonmeters; return new Torque(value, TorqueUnit.MeganewtonMeter); } @@ -564,7 +567,7 @@ public static Torque FromMeganewtonMeters(QuantityValue meganewtonmeters) /// If value is NaN or Infinity. public static Torque FromMeganewtonMillimeters(QuantityValue meganewtonmillimeters) { - double value = (double) meganewtonmillimeters; + QuantityValue value = (QuantityValue) meganewtonmillimeters; return new Torque(value, TorqueUnit.MeganewtonMillimeter); } @@ -574,7 +577,7 @@ public static Torque FromMeganewtonMillimeters(QuantityValue meganewtonmillimete /// If value is NaN or Infinity. public static Torque FromMegapoundForceFeet(QuantityValue megapoundforcefeet) { - double value = (double) megapoundforcefeet; + QuantityValue value = (QuantityValue) megapoundforcefeet; return new Torque(value, TorqueUnit.MegapoundForceFoot); } @@ -584,7 +587,7 @@ public static Torque FromMegapoundForceFeet(QuantityValue megapoundforcefeet) /// If value is NaN or Infinity. public static Torque FromMegapoundForceInches(QuantityValue megapoundforceinches) { - double value = (double) megapoundforceinches; + QuantityValue value = (QuantityValue) megapoundforceinches; return new Torque(value, TorqueUnit.MegapoundForceInch); } @@ -594,7 +597,7 @@ public static Torque FromMegapoundForceInches(QuantityValue megapoundforceinches /// If value is NaN or Infinity. public static Torque FromNewtonCentimeters(QuantityValue newtoncentimeters) { - double value = (double) newtoncentimeters; + QuantityValue value = (QuantityValue) newtoncentimeters; return new Torque(value, TorqueUnit.NewtonCentimeter); } @@ -604,7 +607,7 @@ public static Torque FromNewtonCentimeters(QuantityValue newtoncentimeters) /// If value is NaN or Infinity. public static Torque FromNewtonMeters(QuantityValue newtonmeters) { - double value = (double) newtonmeters; + QuantityValue value = (QuantityValue) newtonmeters; return new Torque(value, TorqueUnit.NewtonMeter); } @@ -614,7 +617,7 @@ public static Torque FromNewtonMeters(QuantityValue newtonmeters) /// If value is NaN or Infinity. public static Torque FromNewtonMillimeters(QuantityValue newtonmillimeters) { - double value = (double) newtonmillimeters; + QuantityValue value = (QuantityValue) newtonmillimeters; return new Torque(value, TorqueUnit.NewtonMillimeter); } @@ -624,7 +627,7 @@ public static Torque FromNewtonMillimeters(QuantityValue newtonmillimeters) /// If value is NaN or Infinity. public static Torque FromPoundalFeet(QuantityValue poundalfeet) { - double value = (double) poundalfeet; + QuantityValue value = (QuantityValue) poundalfeet; return new Torque(value, TorqueUnit.PoundalFoot); } @@ -634,7 +637,7 @@ public static Torque FromPoundalFeet(QuantityValue poundalfeet) /// If value is NaN or Infinity. public static Torque FromPoundForceFeet(QuantityValue poundforcefeet) { - double value = (double) poundforcefeet; + QuantityValue value = (QuantityValue) poundforcefeet; return new Torque(value, TorqueUnit.PoundForceFoot); } @@ -644,7 +647,7 @@ public static Torque FromPoundForceFeet(QuantityValue poundforcefeet) /// If value is NaN or Infinity. public static Torque FromPoundForceInches(QuantityValue poundforceinches) { - double value = (double) poundforceinches; + QuantityValue value = (QuantityValue) poundforceinches; return new Torque(value, TorqueUnit.PoundForceInch); } @@ -654,7 +657,7 @@ public static Torque FromPoundForceInches(QuantityValue poundforceinches) /// If value is NaN or Infinity. public static Torque FromTonneForceCentimeters(QuantityValue tonneforcecentimeters) { - double value = (double) tonneforcecentimeters; + QuantityValue value = (QuantityValue) tonneforcecentimeters; return new Torque(value, TorqueUnit.TonneForceCentimeter); } @@ -664,7 +667,7 @@ public static Torque FromTonneForceCentimeters(QuantityValue tonneforcecentimete /// If value is NaN or Infinity. public static Torque FromTonneForceMeters(QuantityValue tonneforcemeters) { - double value = (double) tonneforcemeters; + QuantityValue value = (QuantityValue) tonneforcemeters; return new Torque(value, TorqueUnit.TonneForceMeter); } @@ -674,7 +677,7 @@ public static Torque FromTonneForceMeters(QuantityValue tonneforcemeters) /// If value is NaN or Infinity. public static Torque FromTonneForceMillimeters(QuantityValue tonneforcemillimeters) { - double value = (double) tonneforcemillimeters; + QuantityValue value = (QuantityValue) tonneforcemillimeters; return new Torque(value, TorqueUnit.TonneForceMillimeter); } @@ -686,7 +689,7 @@ public static Torque FromTonneForceMillimeters(QuantityValue tonneforcemillimete /// Torque unit value. public static Torque From(QuantityValue value, TorqueUnit fromUnit) { - return new Torque((double)value, fromUnit); + return new Torque((QuantityValue)value, fromUnit); } #endregion @@ -856,25 +859,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Torqu } /// Get from multiplying value and . - public static Torque operator *(double left, Torque right) + public static Torque operator *(QuantityValue left, Torque right) { return new Torque(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Torque operator *(Torque left, double right) + public static Torque operator *(Torque left, QuantityValue right) { return new Torque(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Torque operator /(Torque left, double right) + public static Torque operator /(Torque left, QuantityValue right) { return new Torque(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Torque left, Torque right) + public static QuantityValue operator /(Torque left, Torque right) { return left.NewtonMeters / right.NewtonMeters; } @@ -907,6 +910,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Torqu return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Torque left, Torque right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Torque left, Torque right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -919,7 +935,29 @@ public int CompareTo(object obj) /// public int CompareTo(Torque other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Torque objTorque)) + return false; + return Equals(objTorque); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Torque other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -962,13 +1000,13 @@ public int CompareTo(Torque other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Torque other, double tolerance, ComparisonType comparisonType) + public bool Equals(Torque other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -979,7 +1017,7 @@ public bool Equals(Torque other, double tolerance, ComparisonType comparisonType /// A hash code for the current Torque. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -990,17 +1028,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(TorqueUnit unit) + public QuantityValue As(TorqueUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1015,12 +1052,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is TorqueUnit unitAsTorqueUnit)) + if (!(unit is TorqueUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorqueUnit)} is supported.", nameof(unit)); - return As(unitAsTorqueUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1052,7 +1089,7 @@ public Torque ToUnit(TorqueUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Torque)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(TorqueUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1060,17 +1097,17 @@ public Torque ToUnit(TorqueUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TorqueUnit unitAsTorqueUnit)) + if (!(unit is TorqueUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorqueUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTorqueUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1097,10 +1134,10 @@ public Torque ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(TorqueUnit unit) + private QuantityValue GetValueAs(TorqueUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs index 4fd2f5f8ef..534f572aef 100644 --- a/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// The magnitude of torque per unit length. /// [DataContract] - public partial struct TorquePerLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct TorquePerLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -92,9 +92,9 @@ static TorquePerLength() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public TorquePerLength(double value, TorquePerLengthUnit unit) + public TorquePerLength(QuantityValue value, TorquePerLengthUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -106,14 +106,14 @@ public TorquePerLength(double value, TorquePerLengthUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public TorquePerLength(double value, UnitSystem unitSystem) + public TorquePerLength(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -154,7 +154,10 @@ public TorquePerLength(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -177,109 +180,109 @@ public TorquePerLength(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramForceCentimetersPerMeter => As(TorquePerLengthUnit.KilogramForceCentimeterPerMeter); + public QuantityValue KilogramForceCentimetersPerMeter => As(TorquePerLengthUnit.KilogramForceCentimeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramForceMetersPerMeter => As(TorquePerLengthUnit.KilogramForceMeterPerMeter); + public QuantityValue KilogramForceMetersPerMeter => As(TorquePerLengthUnit.KilogramForceMeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilogramForceMillimetersPerMeter => As(TorquePerLengthUnit.KilogramForceMillimeterPerMeter); + public QuantityValue KilogramForceMillimetersPerMeter => As(TorquePerLengthUnit.KilogramForceMillimeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonCentimetersPerMeter => As(TorquePerLengthUnit.KilonewtonCentimeterPerMeter); + public QuantityValue KilonewtonCentimetersPerMeter => As(TorquePerLengthUnit.KilonewtonCentimeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonMetersPerMeter => As(TorquePerLengthUnit.KilonewtonMeterPerMeter); + public QuantityValue KilonewtonMetersPerMeter => As(TorquePerLengthUnit.KilonewtonMeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilonewtonMillimetersPerMeter => As(TorquePerLengthUnit.KilonewtonMillimeterPerMeter); + public QuantityValue KilonewtonMillimetersPerMeter => As(TorquePerLengthUnit.KilonewtonMillimeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundForceFeetPerFoot => As(TorquePerLengthUnit.KilopoundForceFootPerFoot); + public QuantityValue KilopoundForceFeetPerFoot => As(TorquePerLengthUnit.KilopoundForceFootPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilopoundForceInchesPerFoot => As(TorquePerLengthUnit.KilopoundForceInchPerFoot); + public QuantityValue KilopoundForceInchesPerFoot => As(TorquePerLengthUnit.KilopoundForceInchPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonCentimetersPerMeter => As(TorquePerLengthUnit.MeganewtonCentimeterPerMeter); + public QuantityValue MeganewtonCentimetersPerMeter => As(TorquePerLengthUnit.MeganewtonCentimeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonMetersPerMeter => As(TorquePerLengthUnit.MeganewtonMeterPerMeter); + public QuantityValue MeganewtonMetersPerMeter => As(TorquePerLengthUnit.MeganewtonMeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MeganewtonMillimetersPerMeter => As(TorquePerLengthUnit.MeganewtonMillimeterPerMeter); + public QuantityValue MeganewtonMillimetersPerMeter => As(TorquePerLengthUnit.MeganewtonMillimeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundForceFeetPerFoot => As(TorquePerLengthUnit.MegapoundForceFootPerFoot); + public QuantityValue MegapoundForceFeetPerFoot => As(TorquePerLengthUnit.MegapoundForceFootPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegapoundForceInchesPerFoot => As(TorquePerLengthUnit.MegapoundForceInchPerFoot); + public QuantityValue MegapoundForceInchesPerFoot => As(TorquePerLengthUnit.MegapoundForceInchPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonCentimetersPerMeter => As(TorquePerLengthUnit.NewtonCentimeterPerMeter); + public QuantityValue NewtonCentimetersPerMeter => As(TorquePerLengthUnit.NewtonCentimeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonMetersPerMeter => As(TorquePerLengthUnit.NewtonMeterPerMeter); + public QuantityValue NewtonMetersPerMeter => As(TorquePerLengthUnit.NewtonMeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NewtonMillimetersPerMeter => As(TorquePerLengthUnit.NewtonMillimeterPerMeter); + public QuantityValue NewtonMillimetersPerMeter => As(TorquePerLengthUnit.NewtonMillimeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundForceFeetPerFoot => As(TorquePerLengthUnit.PoundForceFootPerFoot); + public QuantityValue PoundForceFeetPerFoot => As(TorquePerLengthUnit.PoundForceFootPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PoundForceInchesPerFoot => As(TorquePerLengthUnit.PoundForceInchPerFoot); + public QuantityValue PoundForceInchesPerFoot => As(TorquePerLengthUnit.PoundForceInchPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneForceCentimetersPerMeter => As(TorquePerLengthUnit.TonneForceCentimeterPerMeter); + public QuantityValue TonneForceCentimetersPerMeter => As(TorquePerLengthUnit.TonneForceCentimeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneForceMetersPerMeter => As(TorquePerLengthUnit.TonneForceMeterPerMeter); + public QuantityValue TonneForceMetersPerMeter => As(TorquePerLengthUnit.TonneForceMeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double TonneForceMillimetersPerMeter => As(TorquePerLengthUnit.TonneForceMillimeterPerMeter); + public QuantityValue TonneForceMillimetersPerMeter => As(TorquePerLengthUnit.TonneForceMillimeterPerMeter); #endregion @@ -398,7 +401,7 @@ public static string GetAbbreviation(TorquePerLengthUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static TorquePerLength FromKilogramForceCentimetersPerMeter(QuantityValue kilogramforcecentimeterspermeter) { - double value = (double) kilogramforcecentimeterspermeter; + QuantityValue value = (QuantityValue) kilogramforcecentimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.KilogramForceCentimeterPerMeter); } @@ -408,7 +411,7 @@ public static TorquePerLength FromKilogramForceCentimetersPerMeter(QuantityValue /// If value is NaN or Infinity. public static TorquePerLength FromKilogramForceMetersPerMeter(QuantityValue kilogramforcemeterspermeter) { - double value = (double) kilogramforcemeterspermeter; + QuantityValue value = (QuantityValue) kilogramforcemeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.KilogramForceMeterPerMeter); } @@ -418,7 +421,7 @@ public static TorquePerLength FromKilogramForceMetersPerMeter(QuantityValue kilo /// If value is NaN or Infinity. public static TorquePerLength FromKilogramForceMillimetersPerMeter(QuantityValue kilogramforcemillimeterspermeter) { - double value = (double) kilogramforcemillimeterspermeter; + QuantityValue value = (QuantityValue) kilogramforcemillimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.KilogramForceMillimeterPerMeter); } @@ -428,7 +431,7 @@ public static TorquePerLength FromKilogramForceMillimetersPerMeter(QuantityValue /// If value is NaN or Infinity. public static TorquePerLength FromKilonewtonCentimetersPerMeter(QuantityValue kilonewtoncentimeterspermeter) { - double value = (double) kilonewtoncentimeterspermeter; + QuantityValue value = (QuantityValue) kilonewtoncentimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.KilonewtonCentimeterPerMeter); } @@ -438,7 +441,7 @@ public static TorquePerLength FromKilonewtonCentimetersPerMeter(QuantityValue ki /// If value is NaN or Infinity. public static TorquePerLength FromKilonewtonMetersPerMeter(QuantityValue kilonewtonmeterspermeter) { - double value = (double) kilonewtonmeterspermeter; + QuantityValue value = (QuantityValue) kilonewtonmeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.KilonewtonMeterPerMeter); } @@ -448,7 +451,7 @@ public static TorquePerLength FromKilonewtonMetersPerMeter(QuantityValue kilonew /// If value is NaN or Infinity. public static TorquePerLength FromKilonewtonMillimetersPerMeter(QuantityValue kilonewtonmillimeterspermeter) { - double value = (double) kilonewtonmillimeterspermeter; + QuantityValue value = (QuantityValue) kilonewtonmillimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.KilonewtonMillimeterPerMeter); } @@ -458,7 +461,7 @@ public static TorquePerLength FromKilonewtonMillimetersPerMeter(QuantityValue ki /// If value is NaN or Infinity. public static TorquePerLength FromKilopoundForceFeetPerFoot(QuantityValue kilopoundforcefeetperfoot) { - double value = (double) kilopoundforcefeetperfoot; + QuantityValue value = (QuantityValue) kilopoundforcefeetperfoot; return new TorquePerLength(value, TorquePerLengthUnit.KilopoundForceFootPerFoot); } @@ -468,7 +471,7 @@ public static TorquePerLength FromKilopoundForceFeetPerFoot(QuantityValue kilopo /// If value is NaN or Infinity. public static TorquePerLength FromKilopoundForceInchesPerFoot(QuantityValue kilopoundforceinchesperfoot) { - double value = (double) kilopoundforceinchesperfoot; + QuantityValue value = (QuantityValue) kilopoundforceinchesperfoot; return new TorquePerLength(value, TorquePerLengthUnit.KilopoundForceInchPerFoot); } @@ -478,7 +481,7 @@ public static TorquePerLength FromKilopoundForceInchesPerFoot(QuantityValue kilo /// If value is NaN or Infinity. public static TorquePerLength FromMeganewtonCentimetersPerMeter(QuantityValue meganewtoncentimeterspermeter) { - double value = (double) meganewtoncentimeterspermeter; + QuantityValue value = (QuantityValue) meganewtoncentimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.MeganewtonCentimeterPerMeter); } @@ -488,7 +491,7 @@ public static TorquePerLength FromMeganewtonCentimetersPerMeter(QuantityValue me /// If value is NaN or Infinity. public static TorquePerLength FromMeganewtonMetersPerMeter(QuantityValue meganewtonmeterspermeter) { - double value = (double) meganewtonmeterspermeter; + QuantityValue value = (QuantityValue) meganewtonmeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.MeganewtonMeterPerMeter); } @@ -498,7 +501,7 @@ public static TorquePerLength FromMeganewtonMetersPerMeter(QuantityValue meganew /// If value is NaN or Infinity. public static TorquePerLength FromMeganewtonMillimetersPerMeter(QuantityValue meganewtonmillimeterspermeter) { - double value = (double) meganewtonmillimeterspermeter; + QuantityValue value = (QuantityValue) meganewtonmillimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.MeganewtonMillimeterPerMeter); } @@ -508,7 +511,7 @@ public static TorquePerLength FromMeganewtonMillimetersPerMeter(QuantityValue me /// If value is NaN or Infinity. public static TorquePerLength FromMegapoundForceFeetPerFoot(QuantityValue megapoundforcefeetperfoot) { - double value = (double) megapoundforcefeetperfoot; + QuantityValue value = (QuantityValue) megapoundforcefeetperfoot; return new TorquePerLength(value, TorquePerLengthUnit.MegapoundForceFootPerFoot); } @@ -518,7 +521,7 @@ public static TorquePerLength FromMegapoundForceFeetPerFoot(QuantityValue megapo /// If value is NaN or Infinity. public static TorquePerLength FromMegapoundForceInchesPerFoot(QuantityValue megapoundforceinchesperfoot) { - double value = (double) megapoundforceinchesperfoot; + QuantityValue value = (QuantityValue) megapoundforceinchesperfoot; return new TorquePerLength(value, TorquePerLengthUnit.MegapoundForceInchPerFoot); } @@ -528,7 +531,7 @@ public static TorquePerLength FromMegapoundForceInchesPerFoot(QuantityValue mega /// If value is NaN or Infinity. public static TorquePerLength FromNewtonCentimetersPerMeter(QuantityValue newtoncentimeterspermeter) { - double value = (double) newtoncentimeterspermeter; + QuantityValue value = (QuantityValue) newtoncentimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.NewtonCentimeterPerMeter); } @@ -538,7 +541,7 @@ public static TorquePerLength FromNewtonCentimetersPerMeter(QuantityValue newton /// If value is NaN or Infinity. public static TorquePerLength FromNewtonMetersPerMeter(QuantityValue newtonmeterspermeter) { - double value = (double) newtonmeterspermeter; + QuantityValue value = (QuantityValue) newtonmeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.NewtonMeterPerMeter); } @@ -548,7 +551,7 @@ public static TorquePerLength FromNewtonMetersPerMeter(QuantityValue newtonmeter /// If value is NaN or Infinity. public static TorquePerLength FromNewtonMillimetersPerMeter(QuantityValue newtonmillimeterspermeter) { - double value = (double) newtonmillimeterspermeter; + QuantityValue value = (QuantityValue) newtonmillimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.NewtonMillimeterPerMeter); } @@ -558,7 +561,7 @@ public static TorquePerLength FromNewtonMillimetersPerMeter(QuantityValue newton /// If value is NaN or Infinity. public static TorquePerLength FromPoundForceFeetPerFoot(QuantityValue poundforcefeetperfoot) { - double value = (double) poundforcefeetperfoot; + QuantityValue value = (QuantityValue) poundforcefeetperfoot; return new TorquePerLength(value, TorquePerLengthUnit.PoundForceFootPerFoot); } @@ -568,7 +571,7 @@ public static TorquePerLength FromPoundForceFeetPerFoot(QuantityValue poundforce /// If value is NaN or Infinity. public static TorquePerLength FromPoundForceInchesPerFoot(QuantityValue poundforceinchesperfoot) { - double value = (double) poundforceinchesperfoot; + QuantityValue value = (QuantityValue) poundforceinchesperfoot; return new TorquePerLength(value, TorquePerLengthUnit.PoundForceInchPerFoot); } @@ -578,7 +581,7 @@ public static TorquePerLength FromPoundForceInchesPerFoot(QuantityValue poundfor /// If value is NaN or Infinity. public static TorquePerLength FromTonneForceCentimetersPerMeter(QuantityValue tonneforcecentimeterspermeter) { - double value = (double) tonneforcecentimeterspermeter; + QuantityValue value = (QuantityValue) tonneforcecentimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.TonneForceCentimeterPerMeter); } @@ -588,7 +591,7 @@ public static TorquePerLength FromTonneForceCentimetersPerMeter(QuantityValue to /// If value is NaN or Infinity. public static TorquePerLength FromTonneForceMetersPerMeter(QuantityValue tonneforcemeterspermeter) { - double value = (double) tonneforcemeterspermeter; + QuantityValue value = (QuantityValue) tonneforcemeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.TonneForceMeterPerMeter); } @@ -598,7 +601,7 @@ public static TorquePerLength FromTonneForceMetersPerMeter(QuantityValue tonnefo /// If value is NaN or Infinity. public static TorquePerLength FromTonneForceMillimetersPerMeter(QuantityValue tonneforcemillimeterspermeter) { - double value = (double) tonneforcemillimeterspermeter; + QuantityValue value = (QuantityValue) tonneforcemillimeterspermeter; return new TorquePerLength(value, TorquePerLengthUnit.TonneForceMillimeterPerMeter); } @@ -610,7 +613,7 @@ public static TorquePerLength FromTonneForceMillimetersPerMeter(QuantityValue to /// TorquePerLength unit value. public static TorquePerLength From(QuantityValue value, TorquePerLengthUnit fromUnit) { - return new TorquePerLength((double)value, fromUnit); + return new TorquePerLength((QuantityValue)value, fromUnit); } #endregion @@ -780,25 +783,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Torqu } /// Get from multiplying value and . - public static TorquePerLength operator *(double left, TorquePerLength right) + public static TorquePerLength operator *(QuantityValue left, TorquePerLength right) { return new TorquePerLength(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static TorquePerLength operator *(TorquePerLength left, double right) + public static TorquePerLength operator *(TorquePerLength left, QuantityValue right) { return new TorquePerLength(left.Value * right, left.Unit); } /// Get from dividing by value. - public static TorquePerLength operator /(TorquePerLength left, double right) + public static TorquePerLength operator /(TorquePerLength left, QuantityValue right) { return new TorquePerLength(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(TorquePerLength left, TorquePerLength right) + public static QuantityValue operator /(TorquePerLength left, TorquePerLength right) { return left.NewtonMetersPerMeter / right.NewtonMetersPerMeter; } @@ -831,6 +834,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Torqu return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(TorquePerLength left, TorquePerLength right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(TorquePerLength left, TorquePerLength right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -843,7 +859,29 @@ public int CompareTo(object obj) /// public int CompareTo(TorquePerLength other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is TorquePerLength objTorquePerLength)) + return false; + return Equals(objTorquePerLength); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(TorquePerLength other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -886,13 +924,13 @@ public int CompareTo(TorquePerLength other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(TorquePerLength other, double tolerance, ComparisonType comparisonType) + public bool Equals(TorquePerLength other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -903,7 +941,7 @@ public bool Equals(TorquePerLength other, double tolerance, ComparisonType compa /// A hash code for the current TorquePerLength. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -914,17 +952,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(TorquePerLengthUnit unit) + public QuantityValue As(TorquePerLengthUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -939,12 +976,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is TorquePerLengthUnit unitAsTorquePerLengthUnit)) + if (!(unit is TorquePerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorquePerLengthUnit)} is supported.", nameof(unit)); - return As(unitAsTorquePerLengthUnit); + return (QuantityValue)As(typedUnit); } /// @@ -976,7 +1013,7 @@ public TorquePerLength ToUnit(TorquePerLengthUnit unit, UnitConverter unitConver var converted = conversionFunction(this); return (TorquePerLength)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(TorquePerLengthUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -984,17 +1021,17 @@ public TorquePerLength ToUnit(TorquePerLengthUnit unit, UnitConverter unitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TorquePerLengthUnit unitAsTorquePerLengthUnit)) + if (!(unit is TorquePerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorquePerLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTorquePerLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1021,10 +1058,10 @@ public TorquePerLength ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(TorquePerLengthUnit unit) + private QuantityValue GetValueAs(TorquePerLengthUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs index f94f7592e1..0e87ea313b 100644 --- a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Turbidity /// [DataContract] - public partial struct Turbidity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Turbidity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -75,9 +75,9 @@ static Turbidity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Turbidity(double value, TurbidityUnit unit) + public Turbidity(QuantityValue value, TurbidityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -89,14 +89,14 @@ public Turbidity(double value, TurbidityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Turbidity(double value, UnitSystem unitSystem) + public Turbidity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -137,7 +137,10 @@ public Turbidity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -160,9 +163,9 @@ public Turbidity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NTU => As(TurbidityUnit.NTU); + public QuantityValue NTU => As(TurbidityUnit.NTU); #endregion @@ -218,7 +221,7 @@ public static string GetAbbreviation(TurbidityUnit unit, IFormatProvider? provid /// If value is NaN or Infinity. public static Turbidity FromNTU(QuantityValue ntu) { - double value = (double) ntu; + QuantityValue value = (QuantityValue) ntu; return new Turbidity(value, TurbidityUnit.NTU); } @@ -230,7 +233,7 @@ public static Turbidity FromNTU(QuantityValue ntu) /// Turbidity unit value. public static Turbidity From(QuantityValue value, TurbidityUnit fromUnit) { - return new Turbidity((double)value, fromUnit); + return new Turbidity((QuantityValue)value, fromUnit); } #endregion @@ -400,25 +403,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Turbi } /// Get from multiplying value and . - public static Turbidity operator *(double left, Turbidity right) + public static Turbidity operator *(QuantityValue left, Turbidity right) { return new Turbidity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Turbidity operator *(Turbidity left, double right) + public static Turbidity operator *(Turbidity left, QuantityValue right) { return new Turbidity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Turbidity operator /(Turbidity left, double right) + public static Turbidity operator /(Turbidity left, QuantityValue right) { return new Turbidity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Turbidity left, Turbidity right) + public static QuantityValue operator /(Turbidity left, Turbidity right) { return left.NTU / right.NTU; } @@ -451,6 +454,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Turbi return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Turbidity left, Turbidity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Turbidity left, Turbidity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -463,7 +479,29 @@ public int CompareTo(object obj) /// public int CompareTo(Turbidity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Turbidity objTurbidity)) + return false; + return Equals(objTurbidity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Turbidity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -506,13 +544,13 @@ public int CompareTo(Turbidity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Turbidity other, double tolerance, ComparisonType comparisonType) + public bool Equals(Turbidity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -523,7 +561,7 @@ public bool Equals(Turbidity other, double tolerance, ComparisonType comparisonT /// A hash code for the current Turbidity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -534,17 +572,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(TurbidityUnit unit) + public QuantityValue As(TurbidityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -559,12 +596,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is TurbidityUnit unitAsTurbidityUnit)) + if (!(unit is TurbidityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TurbidityUnit)} is supported.", nameof(unit)); - return As(unitAsTurbidityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -596,7 +633,7 @@ public Turbidity ToUnit(TurbidityUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Turbidity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(TurbidityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -604,17 +641,17 @@ public Turbidity ToUnit(TurbidityUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TurbidityUnit unitAsTurbidityUnit)) + if (!(unit is TurbidityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TurbidityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsTurbidityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -641,10 +678,10 @@ public Turbidity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(TurbidityUnit unit) + private QuantityValue GetValueAs(TurbidityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs index 454db0c919..2bedd85d64 100644 --- a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene. /// [DataContract] - public partial struct VitaminA : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct VitaminA : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -72,9 +72,9 @@ static VitaminA() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public VitaminA(double value, VitaminAUnit unit) + public VitaminA(QuantityValue value, VitaminAUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -86,14 +86,14 @@ public VitaminA(double value, VitaminAUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public VitaminA(double value, UnitSystem unitSystem) + public VitaminA(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -134,7 +134,10 @@ public VitaminA(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -157,9 +160,9 @@ public VitaminA(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InternationalUnits => As(VitaminAUnit.InternationalUnit); + public QuantityValue InternationalUnits => As(VitaminAUnit.InternationalUnit); #endregion @@ -215,7 +218,7 @@ public static string GetAbbreviation(VitaminAUnit unit, IFormatProvider? provide /// If value is NaN or Infinity. public static VitaminA FromInternationalUnits(QuantityValue internationalunits) { - double value = (double) internationalunits; + QuantityValue value = (QuantityValue) internationalunits; return new VitaminA(value, VitaminAUnit.InternationalUnit); } @@ -227,7 +230,7 @@ public static VitaminA FromInternationalUnits(QuantityValue internationalunits) /// VitaminA unit value. public static VitaminA From(QuantityValue value, VitaminAUnit fromUnit) { - return new VitaminA((double)value, fromUnit); + return new VitaminA((QuantityValue)value, fromUnit); } #endregion @@ -397,25 +400,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Vitam } /// Get from multiplying value and . - public static VitaminA operator *(double left, VitaminA right) + public static VitaminA operator *(QuantityValue left, VitaminA right) { return new VitaminA(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static VitaminA operator *(VitaminA left, double right) + public static VitaminA operator *(VitaminA left, QuantityValue right) { return new VitaminA(left.Value * right, left.Unit); } /// Get from dividing by value. - public static VitaminA operator /(VitaminA left, double right) + public static VitaminA operator /(VitaminA left, QuantityValue right) { return new VitaminA(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(VitaminA left, VitaminA right) + public static QuantityValue operator /(VitaminA left, VitaminA right) { return left.InternationalUnits / right.InternationalUnits; } @@ -448,6 +451,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Vitam return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(VitaminA left, VitaminA right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(VitaminA left, VitaminA right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -460,7 +476,29 @@ public int CompareTo(object obj) /// public int CompareTo(VitaminA other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is VitaminA objVitaminA)) + return false; + return Equals(objVitaminA); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(VitaminA other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -503,13 +541,13 @@ public int CompareTo(VitaminA other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VitaminA other, double tolerance, ComparisonType comparisonType) + public bool Equals(VitaminA other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -520,7 +558,7 @@ public bool Equals(VitaminA other, double tolerance, ComparisonType comparisonTy /// A hash code for the current VitaminA. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -531,17 +569,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(VitaminAUnit unit) + public QuantityValue As(VitaminAUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -556,12 +593,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is VitaminAUnit unitAsVitaminAUnit)) + if (!(unit is VitaminAUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VitaminAUnit)} is supported.", nameof(unit)); - return As(unitAsVitaminAUnit); + return (QuantityValue)As(typedUnit); } /// @@ -593,7 +630,7 @@ public VitaminA ToUnit(VitaminAUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (VitaminA)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(VitaminAUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -601,17 +638,17 @@ public VitaminA ToUnit(VitaminAUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VitaminAUnit unitAsVitaminAUnit)) + if (!(unit is VitaminAUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VitaminAUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVitaminAUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -638,10 +675,10 @@ public VitaminA ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(VitaminAUnit unit) + private QuantityValue GetValueAs(VitaminAUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs index 2d54789723..80f0571e29 100644 --- a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces. /// [DataContract] - public partial struct Volume : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct Volume : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -123,9 +123,9 @@ static Volume() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public Volume(double value, VolumeUnit unit) + public Volume(QuantityValue value, VolumeUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -137,14 +137,14 @@ public Volume(double value, VolumeUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Volume(double value, UnitSystem unitSystem) + public Volume(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -185,7 +185,10 @@ public Volume(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -208,264 +211,264 @@ public Volume(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AcreFeet => As(VolumeUnit.AcreFoot); + public QuantityValue AcreFeet => As(VolumeUnit.AcreFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AuTablespoons => As(VolumeUnit.AuTablespoon); + public QuantityValue AuTablespoons => As(VolumeUnit.AuTablespoon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BoardFeet => As(VolumeUnit.BoardFoot); + public QuantityValue BoardFeet => As(VolumeUnit.BoardFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Centiliters => As(VolumeUnit.Centiliter); + public QuantityValue Centiliters => As(VolumeUnit.Centiliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicCentimeters => As(VolumeUnit.CubicCentimeter); + public QuantityValue CubicCentimeters => As(VolumeUnit.CubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicDecimeters => As(VolumeUnit.CubicDecimeter); + public QuantityValue CubicDecimeters => As(VolumeUnit.CubicDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicFeet => As(VolumeUnit.CubicFoot); + public QuantityValue CubicFeet => As(VolumeUnit.CubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicHectometers => As(VolumeUnit.CubicHectometer); + public QuantityValue CubicHectometers => As(VolumeUnit.CubicHectometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicInches => As(VolumeUnit.CubicInch); + public QuantityValue CubicInches => As(VolumeUnit.CubicInch); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicKilometers => As(VolumeUnit.CubicKilometer); + public QuantityValue CubicKilometers => As(VolumeUnit.CubicKilometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMeters => As(VolumeUnit.CubicMeter); + public QuantityValue CubicMeters => As(VolumeUnit.CubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMicrometers => As(VolumeUnit.CubicMicrometer); + public QuantityValue CubicMicrometers => As(VolumeUnit.CubicMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMiles => As(VolumeUnit.CubicMile); + public QuantityValue CubicMiles => As(VolumeUnit.CubicMile); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMillimeters => As(VolumeUnit.CubicMillimeter); + public QuantityValue CubicMillimeters => As(VolumeUnit.CubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicYards => As(VolumeUnit.CubicYard); + public QuantityValue CubicYards => As(VolumeUnit.CubicYard); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Decaliters => As(VolumeUnit.Decaliter); + public QuantityValue Decaliters => As(VolumeUnit.Decaliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecausGallons => As(VolumeUnit.DecausGallon); + public QuantityValue DecausGallons => As(VolumeUnit.DecausGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Deciliters => As(VolumeUnit.Deciliter); + public QuantityValue Deciliters => As(VolumeUnit.Deciliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DeciusGallons => As(VolumeUnit.DeciusGallon); + public QuantityValue DeciusGallons => As(VolumeUnit.DeciusGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HectocubicFeet => As(VolumeUnit.HectocubicFoot); + public QuantityValue HectocubicFeet => As(VolumeUnit.HectocubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HectocubicMeters => As(VolumeUnit.HectocubicMeter); + public QuantityValue HectocubicMeters => As(VolumeUnit.HectocubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Hectoliters => As(VolumeUnit.Hectoliter); + public QuantityValue Hectoliters => As(VolumeUnit.Hectoliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double HectousGallons => As(VolumeUnit.HectousGallon); + public QuantityValue HectousGallons => As(VolumeUnit.HectousGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); + public QuantityValue ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ImperialGallons => As(VolumeUnit.ImperialGallon); + public QuantityValue ImperialGallons => As(VolumeUnit.ImperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ImperialOunces => As(VolumeUnit.ImperialOunce); + public QuantityValue ImperialOunces => As(VolumeUnit.ImperialOunce); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double ImperialPints => As(VolumeUnit.ImperialPint); + public QuantityValue ImperialPints => As(VolumeUnit.ImperialPint); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilocubicFeet => As(VolumeUnit.KilocubicFoot); + public QuantityValue KilocubicFeet => As(VolumeUnit.KilocubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilocubicMeters => As(VolumeUnit.KilocubicMeter); + public QuantityValue KilocubicMeters => As(VolumeUnit.KilocubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); + public QuantityValue KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Kiloliters => As(VolumeUnit.Kiloliter); + public QuantityValue Kiloliters => As(VolumeUnit.Kiloliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilousGallons => As(VolumeUnit.KilousGallon); + public QuantityValue KilousGallons => As(VolumeUnit.KilousGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Liters => As(VolumeUnit.Liter); + public QuantityValue Liters => As(VolumeUnit.Liter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegacubicFeet => As(VolumeUnit.MegacubicFoot); + public QuantityValue MegacubicFeet => As(VolumeUnit.MegacubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); + public QuantityValue MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Megaliters => As(VolumeUnit.Megaliter); + public QuantityValue Megaliters => As(VolumeUnit.Megaliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegausGallons => As(VolumeUnit.MegausGallon); + public QuantityValue MegausGallons => As(VolumeUnit.MegausGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetricCups => As(VolumeUnit.MetricCup); + public QuantityValue MetricCups => As(VolumeUnit.MetricCup); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); + public QuantityValue MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Microliters => As(VolumeUnit.Microliter); + public QuantityValue Microliters => As(VolumeUnit.Microliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Milliliters => As(VolumeUnit.Milliliter); + public QuantityValue Milliliters => As(VolumeUnit.Milliliter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OilBarrels => As(VolumeUnit.OilBarrel); + public QuantityValue OilBarrels => As(VolumeUnit.OilBarrel); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UkTablespoons => As(VolumeUnit.UkTablespoon); + public QuantityValue UkTablespoons => As(VolumeUnit.UkTablespoon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); + public QuantityValue UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); + public QuantityValue UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsGallons => As(VolumeUnit.UsGallon); + public QuantityValue UsGallons => As(VolumeUnit.UsGallon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsLegalCups => As(VolumeUnit.UsLegalCup); + public QuantityValue UsLegalCups => As(VolumeUnit.UsLegalCup); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsOunces => As(VolumeUnit.UsOunce); + public QuantityValue UsOunces => As(VolumeUnit.UsOunce); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsPints => As(VolumeUnit.UsPint); + public QuantityValue UsPints => As(VolumeUnit.UsPint); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsQuarts => As(VolumeUnit.UsQuart); + public QuantityValue UsQuarts => As(VolumeUnit.UsQuart); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsTablespoons => As(VolumeUnit.UsTablespoon); + public QuantityValue UsTablespoons => As(VolumeUnit.UsTablespoon); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsTeaspoons => As(VolumeUnit.UsTeaspoon); + public QuantityValue UsTeaspoons => As(VolumeUnit.UsTeaspoon); #endregion @@ -721,7 +724,7 @@ public static string GetAbbreviation(VolumeUnit unit, IFormatProvider? provider) /// If value is NaN or Infinity. public static Volume FromAcreFeet(QuantityValue acrefeet) { - double value = (double) acrefeet; + QuantityValue value = (QuantityValue) acrefeet; return new Volume(value, VolumeUnit.AcreFoot); } @@ -731,7 +734,7 @@ public static Volume FromAcreFeet(QuantityValue acrefeet) /// If value is NaN or Infinity. public static Volume FromAuTablespoons(QuantityValue autablespoons) { - double value = (double) autablespoons; + QuantityValue value = (QuantityValue) autablespoons; return new Volume(value, VolumeUnit.AuTablespoon); } @@ -741,7 +744,7 @@ public static Volume FromAuTablespoons(QuantityValue autablespoons) /// If value is NaN or Infinity. public static Volume FromBoardFeet(QuantityValue boardfeet) { - double value = (double) boardfeet; + QuantityValue value = (QuantityValue) boardfeet; return new Volume(value, VolumeUnit.BoardFoot); } @@ -751,7 +754,7 @@ public static Volume FromBoardFeet(QuantityValue boardfeet) /// If value is NaN or Infinity. public static Volume FromCentiliters(QuantityValue centiliters) { - double value = (double) centiliters; + QuantityValue value = (QuantityValue) centiliters; return new Volume(value, VolumeUnit.Centiliter); } @@ -761,7 +764,7 @@ public static Volume FromCentiliters(QuantityValue centiliters) /// If value is NaN or Infinity. public static Volume FromCubicCentimeters(QuantityValue cubiccentimeters) { - double value = (double) cubiccentimeters; + QuantityValue value = (QuantityValue) cubiccentimeters; return new Volume(value, VolumeUnit.CubicCentimeter); } @@ -771,7 +774,7 @@ public static Volume FromCubicCentimeters(QuantityValue cubiccentimeters) /// If value is NaN or Infinity. public static Volume FromCubicDecimeters(QuantityValue cubicdecimeters) { - double value = (double) cubicdecimeters; + QuantityValue value = (QuantityValue) cubicdecimeters; return new Volume(value, VolumeUnit.CubicDecimeter); } @@ -781,7 +784,7 @@ public static Volume FromCubicDecimeters(QuantityValue cubicdecimeters) /// If value is NaN or Infinity. public static Volume FromCubicFeet(QuantityValue cubicfeet) { - double value = (double) cubicfeet; + QuantityValue value = (QuantityValue) cubicfeet; return new Volume(value, VolumeUnit.CubicFoot); } @@ -791,7 +794,7 @@ public static Volume FromCubicFeet(QuantityValue cubicfeet) /// If value is NaN or Infinity. public static Volume FromCubicHectometers(QuantityValue cubichectometers) { - double value = (double) cubichectometers; + QuantityValue value = (QuantityValue) cubichectometers; return new Volume(value, VolumeUnit.CubicHectometer); } @@ -801,7 +804,7 @@ public static Volume FromCubicHectometers(QuantityValue cubichectometers) /// If value is NaN or Infinity. public static Volume FromCubicInches(QuantityValue cubicinches) { - double value = (double) cubicinches; + QuantityValue value = (QuantityValue) cubicinches; return new Volume(value, VolumeUnit.CubicInch); } @@ -811,7 +814,7 @@ public static Volume FromCubicInches(QuantityValue cubicinches) /// If value is NaN or Infinity. public static Volume FromCubicKilometers(QuantityValue cubickilometers) { - double value = (double) cubickilometers; + QuantityValue value = (QuantityValue) cubickilometers; return new Volume(value, VolumeUnit.CubicKilometer); } @@ -821,7 +824,7 @@ public static Volume FromCubicKilometers(QuantityValue cubickilometers) /// If value is NaN or Infinity. public static Volume FromCubicMeters(QuantityValue cubicmeters) { - double value = (double) cubicmeters; + QuantityValue value = (QuantityValue) cubicmeters; return new Volume(value, VolumeUnit.CubicMeter); } @@ -831,7 +834,7 @@ public static Volume FromCubicMeters(QuantityValue cubicmeters) /// If value is NaN or Infinity. public static Volume FromCubicMicrometers(QuantityValue cubicmicrometers) { - double value = (double) cubicmicrometers; + QuantityValue value = (QuantityValue) cubicmicrometers; return new Volume(value, VolumeUnit.CubicMicrometer); } @@ -841,7 +844,7 @@ public static Volume FromCubicMicrometers(QuantityValue cubicmicrometers) /// If value is NaN or Infinity. public static Volume FromCubicMiles(QuantityValue cubicmiles) { - double value = (double) cubicmiles; + QuantityValue value = (QuantityValue) cubicmiles; return new Volume(value, VolumeUnit.CubicMile); } @@ -851,7 +854,7 @@ public static Volume FromCubicMiles(QuantityValue cubicmiles) /// If value is NaN or Infinity. public static Volume FromCubicMillimeters(QuantityValue cubicmillimeters) { - double value = (double) cubicmillimeters; + QuantityValue value = (QuantityValue) cubicmillimeters; return new Volume(value, VolumeUnit.CubicMillimeter); } @@ -861,7 +864,7 @@ public static Volume FromCubicMillimeters(QuantityValue cubicmillimeters) /// If value is NaN or Infinity. public static Volume FromCubicYards(QuantityValue cubicyards) { - double value = (double) cubicyards; + QuantityValue value = (QuantityValue) cubicyards; return new Volume(value, VolumeUnit.CubicYard); } @@ -871,7 +874,7 @@ public static Volume FromCubicYards(QuantityValue cubicyards) /// If value is NaN or Infinity. public static Volume FromDecaliters(QuantityValue decaliters) { - double value = (double) decaliters; + QuantityValue value = (QuantityValue) decaliters; return new Volume(value, VolumeUnit.Decaliter); } @@ -881,7 +884,7 @@ public static Volume FromDecaliters(QuantityValue decaliters) /// If value is NaN or Infinity. public static Volume FromDecausGallons(QuantityValue decausgallons) { - double value = (double) decausgallons; + QuantityValue value = (QuantityValue) decausgallons; return new Volume(value, VolumeUnit.DecausGallon); } @@ -891,7 +894,7 @@ public static Volume FromDecausGallons(QuantityValue decausgallons) /// If value is NaN or Infinity. public static Volume FromDeciliters(QuantityValue deciliters) { - double value = (double) deciliters; + QuantityValue value = (QuantityValue) deciliters; return new Volume(value, VolumeUnit.Deciliter); } @@ -901,7 +904,7 @@ public static Volume FromDeciliters(QuantityValue deciliters) /// If value is NaN or Infinity. public static Volume FromDeciusGallons(QuantityValue deciusgallons) { - double value = (double) deciusgallons; + QuantityValue value = (QuantityValue) deciusgallons; return new Volume(value, VolumeUnit.DeciusGallon); } @@ -911,7 +914,7 @@ public static Volume FromDeciusGallons(QuantityValue deciusgallons) /// If value is NaN or Infinity. public static Volume FromHectocubicFeet(QuantityValue hectocubicfeet) { - double value = (double) hectocubicfeet; + QuantityValue value = (QuantityValue) hectocubicfeet; return new Volume(value, VolumeUnit.HectocubicFoot); } @@ -921,7 +924,7 @@ public static Volume FromHectocubicFeet(QuantityValue hectocubicfeet) /// If value is NaN or Infinity. public static Volume FromHectocubicMeters(QuantityValue hectocubicmeters) { - double value = (double) hectocubicmeters; + QuantityValue value = (QuantityValue) hectocubicmeters; return new Volume(value, VolumeUnit.HectocubicMeter); } @@ -931,7 +934,7 @@ public static Volume FromHectocubicMeters(QuantityValue hectocubicmeters) /// If value is NaN or Infinity. public static Volume FromHectoliters(QuantityValue hectoliters) { - double value = (double) hectoliters; + QuantityValue value = (QuantityValue) hectoliters; return new Volume(value, VolumeUnit.Hectoliter); } @@ -941,7 +944,7 @@ public static Volume FromHectoliters(QuantityValue hectoliters) /// If value is NaN or Infinity. public static Volume FromHectousGallons(QuantityValue hectousgallons) { - double value = (double) hectousgallons; + QuantityValue value = (QuantityValue) hectousgallons; return new Volume(value, VolumeUnit.HectousGallon); } @@ -951,7 +954,7 @@ public static Volume FromHectousGallons(QuantityValue hectousgallons) /// If value is NaN or Infinity. public static Volume FromImperialBeerBarrels(QuantityValue imperialbeerbarrels) { - double value = (double) imperialbeerbarrels; + QuantityValue value = (QuantityValue) imperialbeerbarrels; return new Volume(value, VolumeUnit.ImperialBeerBarrel); } @@ -961,7 +964,7 @@ public static Volume FromImperialBeerBarrels(QuantityValue imperialbeerbarrels) /// If value is NaN or Infinity. public static Volume FromImperialGallons(QuantityValue imperialgallons) { - double value = (double) imperialgallons; + QuantityValue value = (QuantityValue) imperialgallons; return new Volume(value, VolumeUnit.ImperialGallon); } @@ -971,7 +974,7 @@ public static Volume FromImperialGallons(QuantityValue imperialgallons) /// If value is NaN or Infinity. public static Volume FromImperialOunces(QuantityValue imperialounces) { - double value = (double) imperialounces; + QuantityValue value = (QuantityValue) imperialounces; return new Volume(value, VolumeUnit.ImperialOunce); } @@ -981,7 +984,7 @@ public static Volume FromImperialOunces(QuantityValue imperialounces) /// If value is NaN or Infinity. public static Volume FromImperialPints(QuantityValue imperialpints) { - double value = (double) imperialpints; + QuantityValue value = (QuantityValue) imperialpints; return new Volume(value, VolumeUnit.ImperialPint); } @@ -991,7 +994,7 @@ public static Volume FromImperialPints(QuantityValue imperialpints) /// If value is NaN or Infinity. public static Volume FromKilocubicFeet(QuantityValue kilocubicfeet) { - double value = (double) kilocubicfeet; + QuantityValue value = (QuantityValue) kilocubicfeet; return new Volume(value, VolumeUnit.KilocubicFoot); } @@ -1001,7 +1004,7 @@ public static Volume FromKilocubicFeet(QuantityValue kilocubicfeet) /// If value is NaN or Infinity. public static Volume FromKilocubicMeters(QuantityValue kilocubicmeters) { - double value = (double) kilocubicmeters; + QuantityValue value = (QuantityValue) kilocubicmeters; return new Volume(value, VolumeUnit.KilocubicMeter); } @@ -1011,7 +1014,7 @@ public static Volume FromKilocubicMeters(QuantityValue kilocubicmeters) /// If value is NaN or Infinity. public static Volume FromKiloimperialGallons(QuantityValue kiloimperialgallons) { - double value = (double) kiloimperialgallons; + QuantityValue value = (QuantityValue) kiloimperialgallons; return new Volume(value, VolumeUnit.KiloimperialGallon); } @@ -1021,7 +1024,7 @@ public static Volume FromKiloimperialGallons(QuantityValue kiloimperialgallons) /// If value is NaN or Infinity. public static Volume FromKiloliters(QuantityValue kiloliters) { - double value = (double) kiloliters; + QuantityValue value = (QuantityValue) kiloliters; return new Volume(value, VolumeUnit.Kiloliter); } @@ -1031,7 +1034,7 @@ public static Volume FromKiloliters(QuantityValue kiloliters) /// If value is NaN or Infinity. public static Volume FromKilousGallons(QuantityValue kilousgallons) { - double value = (double) kilousgallons; + QuantityValue value = (QuantityValue) kilousgallons; return new Volume(value, VolumeUnit.KilousGallon); } @@ -1041,7 +1044,7 @@ public static Volume FromKilousGallons(QuantityValue kilousgallons) /// If value is NaN or Infinity. public static Volume FromLiters(QuantityValue liters) { - double value = (double) liters; + QuantityValue value = (QuantityValue) liters; return new Volume(value, VolumeUnit.Liter); } @@ -1051,7 +1054,7 @@ public static Volume FromLiters(QuantityValue liters) /// If value is NaN or Infinity. public static Volume FromMegacubicFeet(QuantityValue megacubicfeet) { - double value = (double) megacubicfeet; + QuantityValue value = (QuantityValue) megacubicfeet; return new Volume(value, VolumeUnit.MegacubicFoot); } @@ -1061,7 +1064,7 @@ public static Volume FromMegacubicFeet(QuantityValue megacubicfeet) /// If value is NaN or Infinity. public static Volume FromMegaimperialGallons(QuantityValue megaimperialgallons) { - double value = (double) megaimperialgallons; + QuantityValue value = (QuantityValue) megaimperialgallons; return new Volume(value, VolumeUnit.MegaimperialGallon); } @@ -1071,7 +1074,7 @@ public static Volume FromMegaimperialGallons(QuantityValue megaimperialgallons) /// If value is NaN or Infinity. public static Volume FromMegaliters(QuantityValue megaliters) { - double value = (double) megaliters; + QuantityValue value = (QuantityValue) megaliters; return new Volume(value, VolumeUnit.Megaliter); } @@ -1081,7 +1084,7 @@ public static Volume FromMegaliters(QuantityValue megaliters) /// If value is NaN or Infinity. public static Volume FromMegausGallons(QuantityValue megausgallons) { - double value = (double) megausgallons; + QuantityValue value = (QuantityValue) megausgallons; return new Volume(value, VolumeUnit.MegausGallon); } @@ -1091,7 +1094,7 @@ public static Volume FromMegausGallons(QuantityValue megausgallons) /// If value is NaN or Infinity. public static Volume FromMetricCups(QuantityValue metriccups) { - double value = (double) metriccups; + QuantityValue value = (QuantityValue) metriccups; return new Volume(value, VolumeUnit.MetricCup); } @@ -1101,7 +1104,7 @@ public static Volume FromMetricCups(QuantityValue metriccups) /// If value is NaN or Infinity. public static Volume FromMetricTeaspoons(QuantityValue metricteaspoons) { - double value = (double) metricteaspoons; + QuantityValue value = (QuantityValue) metricteaspoons; return new Volume(value, VolumeUnit.MetricTeaspoon); } @@ -1111,7 +1114,7 @@ public static Volume FromMetricTeaspoons(QuantityValue metricteaspoons) /// If value is NaN or Infinity. public static Volume FromMicroliters(QuantityValue microliters) { - double value = (double) microliters; + QuantityValue value = (QuantityValue) microliters; return new Volume(value, VolumeUnit.Microliter); } @@ -1121,7 +1124,7 @@ public static Volume FromMicroliters(QuantityValue microliters) /// If value is NaN or Infinity. public static Volume FromMilliliters(QuantityValue milliliters) { - double value = (double) milliliters; + QuantityValue value = (QuantityValue) milliliters; return new Volume(value, VolumeUnit.Milliliter); } @@ -1131,7 +1134,7 @@ public static Volume FromMilliliters(QuantityValue milliliters) /// If value is NaN or Infinity. public static Volume FromOilBarrels(QuantityValue oilbarrels) { - double value = (double) oilbarrels; + QuantityValue value = (QuantityValue) oilbarrels; return new Volume(value, VolumeUnit.OilBarrel); } @@ -1141,7 +1144,7 @@ public static Volume FromOilBarrels(QuantityValue oilbarrels) /// If value is NaN or Infinity. public static Volume FromUkTablespoons(QuantityValue uktablespoons) { - double value = (double) uktablespoons; + QuantityValue value = (QuantityValue) uktablespoons; return new Volume(value, VolumeUnit.UkTablespoon); } @@ -1151,7 +1154,7 @@ public static Volume FromUkTablespoons(QuantityValue uktablespoons) /// If value is NaN or Infinity. public static Volume FromUsBeerBarrels(QuantityValue usbeerbarrels) { - double value = (double) usbeerbarrels; + QuantityValue value = (QuantityValue) usbeerbarrels; return new Volume(value, VolumeUnit.UsBeerBarrel); } @@ -1161,7 +1164,7 @@ public static Volume FromUsBeerBarrels(QuantityValue usbeerbarrels) /// If value is NaN or Infinity. public static Volume FromUsCustomaryCups(QuantityValue uscustomarycups) { - double value = (double) uscustomarycups; + QuantityValue value = (QuantityValue) uscustomarycups; return new Volume(value, VolumeUnit.UsCustomaryCup); } @@ -1171,7 +1174,7 @@ public static Volume FromUsCustomaryCups(QuantityValue uscustomarycups) /// If value is NaN or Infinity. public static Volume FromUsGallons(QuantityValue usgallons) { - double value = (double) usgallons; + QuantityValue value = (QuantityValue) usgallons; return new Volume(value, VolumeUnit.UsGallon); } @@ -1181,7 +1184,7 @@ public static Volume FromUsGallons(QuantityValue usgallons) /// If value is NaN or Infinity. public static Volume FromUsLegalCups(QuantityValue uslegalcups) { - double value = (double) uslegalcups; + QuantityValue value = (QuantityValue) uslegalcups; return new Volume(value, VolumeUnit.UsLegalCup); } @@ -1191,7 +1194,7 @@ public static Volume FromUsLegalCups(QuantityValue uslegalcups) /// If value is NaN or Infinity. public static Volume FromUsOunces(QuantityValue usounces) { - double value = (double) usounces; + QuantityValue value = (QuantityValue) usounces; return new Volume(value, VolumeUnit.UsOunce); } @@ -1201,7 +1204,7 @@ public static Volume FromUsOunces(QuantityValue usounces) /// If value is NaN or Infinity. public static Volume FromUsPints(QuantityValue uspints) { - double value = (double) uspints; + QuantityValue value = (QuantityValue) uspints; return new Volume(value, VolumeUnit.UsPint); } @@ -1211,7 +1214,7 @@ public static Volume FromUsPints(QuantityValue uspints) /// If value is NaN or Infinity. public static Volume FromUsQuarts(QuantityValue usquarts) { - double value = (double) usquarts; + QuantityValue value = (QuantityValue) usquarts; return new Volume(value, VolumeUnit.UsQuart); } @@ -1221,7 +1224,7 @@ public static Volume FromUsQuarts(QuantityValue usquarts) /// If value is NaN or Infinity. public static Volume FromUsTablespoons(QuantityValue ustablespoons) { - double value = (double) ustablespoons; + QuantityValue value = (QuantityValue) ustablespoons; return new Volume(value, VolumeUnit.UsTablespoon); } @@ -1231,7 +1234,7 @@ public static Volume FromUsTablespoons(QuantityValue ustablespoons) /// If value is NaN or Infinity. public static Volume FromUsTeaspoons(QuantityValue usteaspoons) { - double value = (double) usteaspoons; + QuantityValue value = (QuantityValue) usteaspoons; return new Volume(value, VolumeUnit.UsTeaspoon); } @@ -1243,7 +1246,7 @@ public static Volume FromUsTeaspoons(QuantityValue usteaspoons) /// Volume unit value. public static Volume From(QuantityValue value, VolumeUnit fromUnit) { - return new Volume((double)value, fromUnit); + return new Volume((QuantityValue)value, fromUnit); } #endregion @@ -1413,25 +1416,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum } /// Get from multiplying value and . - public static Volume operator *(double left, Volume right) + public static Volume operator *(QuantityValue left, Volume right) { return new Volume(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Volume operator *(Volume left, double right) + public static Volume operator *(Volume left, QuantityValue right) { return new Volume(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Volume operator /(Volume left, double right) + public static Volume operator /(Volume left, QuantityValue right) { return new Volume(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Volume left, Volume right) + public static QuantityValue operator /(Volume left, Volume right) { return left.CubicMeters / right.CubicMeters; } @@ -1464,6 +1467,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(Volume left, Volume right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(Volume left, Volume right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1476,7 +1492,29 @@ public int CompareTo(object obj) /// public int CompareTo(Volume other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is Volume objVolume)) + return false; + return Equals(objVolume); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(Volume other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1519,13 +1557,13 @@ public int CompareTo(Volume other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Volume other, double tolerance, ComparisonType comparisonType) + public bool Equals(Volume other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1536,7 +1574,7 @@ public bool Equals(Volume other, double tolerance, ComparisonType comparisonType /// A hash code for the current Volume. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1547,17 +1585,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(VolumeUnit unit) + public QuantityValue As(VolumeUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1572,12 +1609,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is VolumeUnit unitAsVolumeUnit)) + if (!(unit is VolumeUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeUnit)} is supported.", nameof(unit)); - return As(unitAsVolumeUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1609,7 +1646,7 @@ public Volume ToUnit(VolumeUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (Volume)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(VolumeUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1617,17 +1654,17 @@ public Volume ToUnit(VolumeUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumeUnit unitAsVolumeUnit)) + if (!(unit is VolumeUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumeUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1654,10 +1691,10 @@ public Volume ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(VolumeUnit unit) + private QuantityValue GetValueAs(VolumeUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs index 26d1de1beb..4f81ca2c36 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Concentration#Volume_concentration /// [DataContract] - public partial struct VolumeConcentration : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct VolumeConcentration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -94,9 +94,9 @@ static VolumeConcentration() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public VolumeConcentration(double value, VolumeConcentrationUnit unit) + public VolumeConcentration(QuantityValue value, VolumeConcentrationUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -108,14 +108,14 @@ public VolumeConcentration(double value, VolumeConcentrationUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public VolumeConcentration(double value, UnitSystem unitSystem) + public VolumeConcentration(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -156,7 +156,10 @@ public VolumeConcentration(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -179,104 +182,104 @@ public VolumeConcentration(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentilitersPerLiter => As(VolumeConcentrationUnit.CentilitersPerLiter); + public QuantityValue CentilitersPerLiter => As(VolumeConcentrationUnit.CentilitersPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentilitersPerMililiter => As(VolumeConcentrationUnit.CentilitersPerMililiter); + public QuantityValue CentilitersPerMililiter => As(VolumeConcentrationUnit.CentilitersPerMililiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecilitersPerLiter => As(VolumeConcentrationUnit.DecilitersPerLiter); + public QuantityValue DecilitersPerLiter => As(VolumeConcentrationUnit.DecilitersPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecilitersPerMililiter => As(VolumeConcentrationUnit.DecilitersPerMililiter); + public QuantityValue DecilitersPerMililiter => As(VolumeConcentrationUnit.DecilitersPerMililiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimalFractions => As(VolumeConcentrationUnit.DecimalFraction); + public QuantityValue DecimalFractions => As(VolumeConcentrationUnit.DecimalFraction); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPerLiter => As(VolumeConcentrationUnit.LitersPerLiter); + public QuantityValue LitersPerLiter => As(VolumeConcentrationUnit.LitersPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPerMililiter => As(VolumeConcentrationUnit.LitersPerMililiter); + public QuantityValue LitersPerMililiter => As(VolumeConcentrationUnit.LitersPerMililiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrolitersPerLiter => As(VolumeConcentrationUnit.MicrolitersPerLiter); + public QuantityValue MicrolitersPerLiter => As(VolumeConcentrationUnit.MicrolitersPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrolitersPerMililiter => As(VolumeConcentrationUnit.MicrolitersPerMililiter); + public QuantityValue MicrolitersPerMililiter => As(VolumeConcentrationUnit.MicrolitersPerMililiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillilitersPerLiter => As(VolumeConcentrationUnit.MillilitersPerLiter); + public QuantityValue MillilitersPerLiter => As(VolumeConcentrationUnit.MillilitersPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillilitersPerMililiter => As(VolumeConcentrationUnit.MillilitersPerMililiter); + public QuantityValue MillilitersPerMililiter => As(VolumeConcentrationUnit.MillilitersPerMililiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanolitersPerLiter => As(VolumeConcentrationUnit.NanolitersPerLiter); + public QuantityValue NanolitersPerLiter => As(VolumeConcentrationUnit.NanolitersPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanolitersPerMililiter => As(VolumeConcentrationUnit.NanolitersPerMililiter); + public QuantityValue NanolitersPerMililiter => As(VolumeConcentrationUnit.NanolitersPerMililiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerBillion => As(VolumeConcentrationUnit.PartPerBillion); + public QuantityValue PartsPerBillion => As(VolumeConcentrationUnit.PartPerBillion); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerMillion => As(VolumeConcentrationUnit.PartPerMillion); + public QuantityValue PartsPerMillion => As(VolumeConcentrationUnit.PartPerMillion); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerThousand => As(VolumeConcentrationUnit.PartPerThousand); + public QuantityValue PartsPerThousand => As(VolumeConcentrationUnit.PartPerThousand); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PartsPerTrillion => As(VolumeConcentrationUnit.PartPerTrillion); + public QuantityValue PartsPerTrillion => As(VolumeConcentrationUnit.PartPerTrillion); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double Percent => As(VolumeConcentrationUnit.Percent); + public QuantityValue Percent => As(VolumeConcentrationUnit.Percent); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicolitersPerLiter => As(VolumeConcentrationUnit.PicolitersPerLiter); + public QuantityValue PicolitersPerLiter => As(VolumeConcentrationUnit.PicolitersPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double PicolitersPerMililiter => As(VolumeConcentrationUnit.PicolitersPerMililiter); + public QuantityValue PicolitersPerMililiter => As(VolumeConcentrationUnit.PicolitersPerMililiter); #endregion @@ -389,7 +392,7 @@ public static string GetAbbreviation(VolumeConcentrationUnit unit, IFormatProvid /// If value is NaN or Infinity. public static VolumeConcentration FromCentilitersPerLiter(QuantityValue centilitersperliter) { - double value = (double) centilitersperliter; + QuantityValue value = (QuantityValue) centilitersperliter; return new VolumeConcentration(value, VolumeConcentrationUnit.CentilitersPerLiter); } @@ -399,7 +402,7 @@ public static VolumeConcentration FromCentilitersPerLiter(QuantityValue centilit /// If value is NaN or Infinity. public static VolumeConcentration FromCentilitersPerMililiter(QuantityValue centiliterspermililiter) { - double value = (double) centiliterspermililiter; + QuantityValue value = (QuantityValue) centiliterspermililiter; return new VolumeConcentration(value, VolumeConcentrationUnit.CentilitersPerMililiter); } @@ -409,7 +412,7 @@ public static VolumeConcentration FromCentilitersPerMililiter(QuantityValue cent /// If value is NaN or Infinity. public static VolumeConcentration FromDecilitersPerLiter(QuantityValue decilitersperliter) { - double value = (double) decilitersperliter; + QuantityValue value = (QuantityValue) decilitersperliter; return new VolumeConcentration(value, VolumeConcentrationUnit.DecilitersPerLiter); } @@ -419,7 +422,7 @@ public static VolumeConcentration FromDecilitersPerLiter(QuantityValue deciliter /// If value is NaN or Infinity. public static VolumeConcentration FromDecilitersPerMililiter(QuantityValue deciliterspermililiter) { - double value = (double) deciliterspermililiter; + QuantityValue value = (QuantityValue) deciliterspermililiter; return new VolumeConcentration(value, VolumeConcentrationUnit.DecilitersPerMililiter); } @@ -429,7 +432,7 @@ public static VolumeConcentration FromDecilitersPerMililiter(QuantityValue decil /// If value is NaN or Infinity. public static VolumeConcentration FromDecimalFractions(QuantityValue decimalfractions) { - double value = (double) decimalfractions; + QuantityValue value = (QuantityValue) decimalfractions; return new VolumeConcentration(value, VolumeConcentrationUnit.DecimalFraction); } @@ -439,7 +442,7 @@ public static VolumeConcentration FromDecimalFractions(QuantityValue decimalfrac /// If value is NaN or Infinity. public static VolumeConcentration FromLitersPerLiter(QuantityValue litersperliter) { - double value = (double) litersperliter; + QuantityValue value = (QuantityValue) litersperliter; return new VolumeConcentration(value, VolumeConcentrationUnit.LitersPerLiter); } @@ -449,7 +452,7 @@ public static VolumeConcentration FromLitersPerLiter(QuantityValue litersperlite /// If value is NaN or Infinity. public static VolumeConcentration FromLitersPerMililiter(QuantityValue literspermililiter) { - double value = (double) literspermililiter; + QuantityValue value = (QuantityValue) literspermililiter; return new VolumeConcentration(value, VolumeConcentrationUnit.LitersPerMililiter); } @@ -459,7 +462,7 @@ public static VolumeConcentration FromLitersPerMililiter(QuantityValue litersper /// If value is NaN or Infinity. public static VolumeConcentration FromMicrolitersPerLiter(QuantityValue microlitersperliter) { - double value = (double) microlitersperliter; + QuantityValue value = (QuantityValue) microlitersperliter; return new VolumeConcentration(value, VolumeConcentrationUnit.MicrolitersPerLiter); } @@ -469,7 +472,7 @@ public static VolumeConcentration FromMicrolitersPerLiter(QuantityValue microlit /// If value is NaN or Infinity. public static VolumeConcentration FromMicrolitersPerMililiter(QuantityValue microliterspermililiter) { - double value = (double) microliterspermililiter; + QuantityValue value = (QuantityValue) microliterspermililiter; return new VolumeConcentration(value, VolumeConcentrationUnit.MicrolitersPerMililiter); } @@ -479,7 +482,7 @@ public static VolumeConcentration FromMicrolitersPerMililiter(QuantityValue micr /// If value is NaN or Infinity. public static VolumeConcentration FromMillilitersPerLiter(QuantityValue millilitersperliter) { - double value = (double) millilitersperliter; + QuantityValue value = (QuantityValue) millilitersperliter; return new VolumeConcentration(value, VolumeConcentrationUnit.MillilitersPerLiter); } @@ -489,7 +492,7 @@ public static VolumeConcentration FromMillilitersPerLiter(QuantityValue millilit /// If value is NaN or Infinity. public static VolumeConcentration FromMillilitersPerMililiter(QuantityValue milliliterspermililiter) { - double value = (double) milliliterspermililiter; + QuantityValue value = (QuantityValue) milliliterspermililiter; return new VolumeConcentration(value, VolumeConcentrationUnit.MillilitersPerMililiter); } @@ -499,7 +502,7 @@ public static VolumeConcentration FromMillilitersPerMililiter(QuantityValue mill /// If value is NaN or Infinity. public static VolumeConcentration FromNanolitersPerLiter(QuantityValue nanolitersperliter) { - double value = (double) nanolitersperliter; + QuantityValue value = (QuantityValue) nanolitersperliter; return new VolumeConcentration(value, VolumeConcentrationUnit.NanolitersPerLiter); } @@ -509,7 +512,7 @@ public static VolumeConcentration FromNanolitersPerLiter(QuantityValue nanoliter /// If value is NaN or Infinity. public static VolumeConcentration FromNanolitersPerMililiter(QuantityValue nanoliterspermililiter) { - double value = (double) nanoliterspermililiter; + QuantityValue value = (QuantityValue) nanoliterspermililiter; return new VolumeConcentration(value, VolumeConcentrationUnit.NanolitersPerMililiter); } @@ -519,7 +522,7 @@ public static VolumeConcentration FromNanolitersPerMililiter(QuantityValue nanol /// If value is NaN or Infinity. public static VolumeConcentration FromPartsPerBillion(QuantityValue partsperbillion) { - double value = (double) partsperbillion; + QuantityValue value = (QuantityValue) partsperbillion; return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerBillion); } @@ -529,7 +532,7 @@ public static VolumeConcentration FromPartsPerBillion(QuantityValue partsperbill /// If value is NaN or Infinity. public static VolumeConcentration FromPartsPerMillion(QuantityValue partspermillion) { - double value = (double) partspermillion; + QuantityValue value = (QuantityValue) partspermillion; return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerMillion); } @@ -539,7 +542,7 @@ public static VolumeConcentration FromPartsPerMillion(QuantityValue partspermill /// If value is NaN or Infinity. public static VolumeConcentration FromPartsPerThousand(QuantityValue partsperthousand) { - double value = (double) partsperthousand; + QuantityValue value = (QuantityValue) partsperthousand; return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerThousand); } @@ -549,7 +552,7 @@ public static VolumeConcentration FromPartsPerThousand(QuantityValue partspertho /// If value is NaN or Infinity. public static VolumeConcentration FromPartsPerTrillion(QuantityValue partspertrillion) { - double value = (double) partspertrillion; + QuantityValue value = (QuantityValue) partspertrillion; return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerTrillion); } @@ -559,7 +562,7 @@ public static VolumeConcentration FromPartsPerTrillion(QuantityValue partspertri /// If value is NaN or Infinity. public static VolumeConcentration FromPercent(QuantityValue percent) { - double value = (double) percent; + QuantityValue value = (QuantityValue) percent; return new VolumeConcentration(value, VolumeConcentrationUnit.Percent); } @@ -569,7 +572,7 @@ public static VolumeConcentration FromPercent(QuantityValue percent) /// If value is NaN or Infinity. public static VolumeConcentration FromPicolitersPerLiter(QuantityValue picolitersperliter) { - double value = (double) picolitersperliter; + QuantityValue value = (QuantityValue) picolitersperliter; return new VolumeConcentration(value, VolumeConcentrationUnit.PicolitersPerLiter); } @@ -579,7 +582,7 @@ public static VolumeConcentration FromPicolitersPerLiter(QuantityValue picoliter /// If value is NaN or Infinity. public static VolumeConcentration FromPicolitersPerMililiter(QuantityValue picoliterspermililiter) { - double value = (double) picoliterspermililiter; + QuantityValue value = (QuantityValue) picoliterspermililiter; return new VolumeConcentration(value, VolumeConcentrationUnit.PicolitersPerMililiter); } @@ -591,7 +594,7 @@ public static VolumeConcentration FromPicolitersPerMililiter(QuantityValue picol /// VolumeConcentration unit value. public static VolumeConcentration From(QuantityValue value, VolumeConcentrationUnit fromUnit) { - return new VolumeConcentration((double)value, fromUnit); + return new VolumeConcentration((QuantityValue)value, fromUnit); } #endregion @@ -761,25 +764,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum } /// Get from multiplying value and . - public static VolumeConcentration operator *(double left, VolumeConcentration right) + public static VolumeConcentration operator *(QuantityValue left, VolumeConcentration right) { return new VolumeConcentration(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static VolumeConcentration operator *(VolumeConcentration left, double right) + public static VolumeConcentration operator *(VolumeConcentration left, QuantityValue right) { return new VolumeConcentration(left.Value * right, left.Unit); } /// Get from dividing by value. - public static VolumeConcentration operator /(VolumeConcentration left, double right) + public static VolumeConcentration operator /(VolumeConcentration left, QuantityValue right) { return new VolumeConcentration(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(VolumeConcentration left, VolumeConcentration right) + public static QuantityValue operator /(VolumeConcentration left, VolumeConcentration right) { return left.DecimalFractions / right.DecimalFractions; } @@ -812,6 +815,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(VolumeConcentration left, VolumeConcentration right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(VolumeConcentration left, VolumeConcentration right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -824,7 +840,29 @@ public int CompareTo(object obj) /// public int CompareTo(VolumeConcentration other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is VolumeConcentration objVolumeConcentration)) + return false; + return Equals(objVolumeConcentration); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(VolumeConcentration other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -867,13 +905,13 @@ public int CompareTo(VolumeConcentration other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VolumeConcentration other, double tolerance, ComparisonType comparisonType) + public bool Equals(VolumeConcentration other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -884,7 +922,7 @@ public bool Equals(VolumeConcentration other, double tolerance, ComparisonType c /// A hash code for the current VolumeConcentration. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -895,17 +933,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(VolumeConcentrationUnit unit) + public QuantityValue As(VolumeConcentrationUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -920,12 +957,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is VolumeConcentrationUnit unitAsVolumeConcentrationUnit)) + if (!(unit is VolumeConcentrationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeConcentrationUnit)} is supported.", nameof(unit)); - return As(unitAsVolumeConcentrationUnit); + return (QuantityValue)As(typedUnit); } /// @@ -957,7 +994,7 @@ public VolumeConcentration ToUnit(VolumeConcentrationUnit unit, UnitConverter un var converted = conversionFunction(this); return (VolumeConcentration)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(VolumeConcentrationUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -965,17 +1002,17 @@ public VolumeConcentration ToUnit(VolumeConcentrationUnit unit, UnitConverter un } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumeConcentrationUnit unitAsVolumeConcentrationUnit)) + if (!(unit is VolumeConcentrationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeConcentrationUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumeConcentrationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1002,10 +1039,10 @@ public VolumeConcentration ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(VolumeConcentrationUnit unit) + private QuantityValue GetValueAs(VolumeConcentrationUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs index 14cecc5941..db17809849 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. /// [DataContract] - public partial struct VolumeFlow : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct VolumeFlow : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -133,9 +133,9 @@ static VolumeFlow() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public VolumeFlow(double value, VolumeFlowUnit unit) + public VolumeFlow(QuantityValue value, VolumeFlowUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -147,14 +147,14 @@ public VolumeFlow(double value, VolumeFlowUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public VolumeFlow(double value, UnitSystem unitSystem) + public VolumeFlow(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -195,7 +195,10 @@ public VolumeFlow(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -218,314 +221,314 @@ public VolumeFlow(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AcreFeetPerDay => As(VolumeFlowUnit.AcreFootPerDay); + public QuantityValue AcreFeetPerDay => As(VolumeFlowUnit.AcreFootPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AcreFeetPerHour => As(VolumeFlowUnit.AcreFootPerHour); + public QuantityValue AcreFeetPerHour => As(VolumeFlowUnit.AcreFootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AcreFeetPerMinute => As(VolumeFlowUnit.AcreFootPerMinute); + public QuantityValue AcreFeetPerMinute => As(VolumeFlowUnit.AcreFootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double AcreFeetPerSecond => As(VolumeFlowUnit.AcreFootPerSecond); + public QuantityValue AcreFeetPerSecond => As(VolumeFlowUnit.AcreFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentilitersPerDay => As(VolumeFlowUnit.CentiliterPerDay); + public QuantityValue CentilitersPerDay => As(VolumeFlowUnit.CentiliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentilitersPerHour => As(VolumeFlowUnit.CentiliterPerHour); + public QuantityValue CentilitersPerHour => As(VolumeFlowUnit.CentiliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentilitersPerMinute => As(VolumeFlowUnit.CentiliterPerMinute); + public QuantityValue CentilitersPerMinute => As(VolumeFlowUnit.CentiliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentilitersPerSecond => As(VolumeFlowUnit.CentiliterPerSecond); + public QuantityValue CentilitersPerSecond => As(VolumeFlowUnit.CentiliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicCentimetersPerMinute => As(VolumeFlowUnit.CubicCentimeterPerMinute); + public QuantityValue CubicCentimetersPerMinute => As(VolumeFlowUnit.CubicCentimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); + public QuantityValue CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); + public QuantityValue CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); + public QuantityValue CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); + public QuantityValue CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMetersPerDay => As(VolumeFlowUnit.CubicMeterPerDay); + public QuantityValue CubicMetersPerDay => As(VolumeFlowUnit.CubicMeterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); + public QuantityValue CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); + public QuantityValue CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); + public QuantityValue CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMillimetersPerSecond => As(VolumeFlowUnit.CubicMillimeterPerSecond); + public QuantityValue CubicMillimetersPerSecond => As(VolumeFlowUnit.CubicMillimeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicYardsPerDay => As(VolumeFlowUnit.CubicYardPerDay); + public QuantityValue CubicYardsPerDay => As(VolumeFlowUnit.CubicYardPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); + public QuantityValue CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); + public QuantityValue CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); + public QuantityValue CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecilitersPerDay => As(VolumeFlowUnit.DeciliterPerDay); + public QuantityValue DecilitersPerDay => As(VolumeFlowUnit.DeciliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecilitersPerHour => As(VolumeFlowUnit.DeciliterPerHour); + public QuantityValue DecilitersPerHour => As(VolumeFlowUnit.DeciliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecilitersPerMinute => As(VolumeFlowUnit.DeciliterPerMinute); + public QuantityValue DecilitersPerMinute => As(VolumeFlowUnit.DeciliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecilitersPerSecond => As(VolumeFlowUnit.DeciliterPerSecond); + public QuantityValue DecilitersPerSecond => As(VolumeFlowUnit.DeciliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilolitersPerDay => As(VolumeFlowUnit.KiloliterPerDay); + public QuantityValue KilolitersPerDay => As(VolumeFlowUnit.KiloliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilolitersPerHour => As(VolumeFlowUnit.KiloliterPerHour); + public QuantityValue KilolitersPerHour => As(VolumeFlowUnit.KiloliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilolitersPerMinute => As(VolumeFlowUnit.KiloliterPerMinute); + public QuantityValue KilolitersPerMinute => As(VolumeFlowUnit.KiloliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilolitersPerSecond => As(VolumeFlowUnit.KiloliterPerSecond); + public QuantityValue KilolitersPerSecond => As(VolumeFlowUnit.KiloliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilousGallonsPerMinute => As(VolumeFlowUnit.KilousGallonPerMinute); + public QuantityValue KilousGallonsPerMinute => As(VolumeFlowUnit.KilousGallonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPerDay => As(VolumeFlowUnit.LiterPerDay); + public QuantityValue LitersPerDay => As(VolumeFlowUnit.LiterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPerHour => As(VolumeFlowUnit.LiterPerHour); + public QuantityValue LitersPerHour => As(VolumeFlowUnit.LiterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPerMinute => As(VolumeFlowUnit.LiterPerMinute); + public QuantityValue LitersPerMinute => As(VolumeFlowUnit.LiterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPerSecond => As(VolumeFlowUnit.LiterPerSecond); + public QuantityValue LitersPerSecond => As(VolumeFlowUnit.LiterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegalitersPerDay => As(VolumeFlowUnit.MegaliterPerDay); + public QuantityValue MegalitersPerDay => As(VolumeFlowUnit.MegaliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegaukGallonsPerSecond => As(VolumeFlowUnit.MegaukGallonPerSecond); + public QuantityValue MegaukGallonsPerSecond => As(VolumeFlowUnit.MegaukGallonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrolitersPerDay => As(VolumeFlowUnit.MicroliterPerDay); + public QuantityValue MicrolitersPerDay => As(VolumeFlowUnit.MicroliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrolitersPerHour => As(VolumeFlowUnit.MicroliterPerHour); + public QuantityValue MicrolitersPerHour => As(VolumeFlowUnit.MicroliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrolitersPerMinute => As(VolumeFlowUnit.MicroliterPerMinute); + public QuantityValue MicrolitersPerMinute => As(VolumeFlowUnit.MicroliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MicrolitersPerSecond => As(VolumeFlowUnit.MicroliterPerSecond); + public QuantityValue MicrolitersPerSecond => As(VolumeFlowUnit.MicroliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillilitersPerDay => As(VolumeFlowUnit.MilliliterPerDay); + public QuantityValue MillilitersPerDay => As(VolumeFlowUnit.MilliliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillilitersPerHour => As(VolumeFlowUnit.MilliliterPerHour); + public QuantityValue MillilitersPerHour => As(VolumeFlowUnit.MilliliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillilitersPerMinute => As(VolumeFlowUnit.MilliliterPerMinute); + public QuantityValue MillilitersPerMinute => As(VolumeFlowUnit.MilliliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillilitersPerSecond => As(VolumeFlowUnit.MilliliterPerSecond); + public QuantityValue MillilitersPerSecond => As(VolumeFlowUnit.MilliliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonPerDay); + public QuantityValue MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanolitersPerDay => As(VolumeFlowUnit.NanoliterPerDay); + public QuantityValue NanolitersPerDay => As(VolumeFlowUnit.NanoliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanolitersPerHour => As(VolumeFlowUnit.NanoliterPerHour); + public QuantityValue NanolitersPerHour => As(VolumeFlowUnit.NanoliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanolitersPerMinute => As(VolumeFlowUnit.NanoliterPerMinute); + public QuantityValue NanolitersPerMinute => As(VolumeFlowUnit.NanoliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double NanolitersPerSecond => As(VolumeFlowUnit.NanoliterPerSecond); + public QuantityValue NanolitersPerSecond => As(VolumeFlowUnit.NanoliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelPerDay); + public QuantityValue OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OilBarrelsPerHour => As(VolumeFlowUnit.OilBarrelPerHour); + public QuantityValue OilBarrelsPerHour => As(VolumeFlowUnit.OilBarrelPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OilBarrelsPerMinute => As(VolumeFlowUnit.OilBarrelPerMinute); + public QuantityValue OilBarrelsPerMinute => As(VolumeFlowUnit.OilBarrelPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OilBarrelsPerSecond => As(VolumeFlowUnit.OilBarrelPerSecond); + public QuantityValue OilBarrelsPerSecond => As(VolumeFlowUnit.OilBarrelPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UkGallonsPerDay => As(VolumeFlowUnit.UkGallonPerDay); + public QuantityValue UkGallonsPerDay => As(VolumeFlowUnit.UkGallonPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UkGallonsPerHour => As(VolumeFlowUnit.UkGallonPerHour); + public QuantityValue UkGallonsPerHour => As(VolumeFlowUnit.UkGallonPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UkGallonsPerMinute => As(VolumeFlowUnit.UkGallonPerMinute); + public QuantityValue UkGallonsPerMinute => As(VolumeFlowUnit.UkGallonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UkGallonsPerSecond => As(VolumeFlowUnit.UkGallonPerSecond); + public QuantityValue UkGallonsPerSecond => As(VolumeFlowUnit.UkGallonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsGallonsPerDay => As(VolumeFlowUnit.UsGallonPerDay); + public QuantityValue UsGallonsPerDay => As(VolumeFlowUnit.UsGallonPerDay); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsGallonsPerHour => As(VolumeFlowUnit.UsGallonPerHour); + public QuantityValue UsGallonsPerHour => As(VolumeFlowUnit.UsGallonPerHour); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonPerMinute); + public QuantityValue UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonPerSecond); + public QuantityValue UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonPerSecond); #endregion @@ -791,7 +794,7 @@ public static string GetAbbreviation(VolumeFlowUnit unit, IFormatProvider? provi /// If value is NaN or Infinity. public static VolumeFlow FromAcreFeetPerDay(QuantityValue acrefeetperday) { - double value = (double) acrefeetperday; + QuantityValue value = (QuantityValue) acrefeetperday; return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerDay); } @@ -801,7 +804,7 @@ public static VolumeFlow FromAcreFeetPerDay(QuantityValue acrefeetperday) /// If value is NaN or Infinity. public static VolumeFlow FromAcreFeetPerHour(QuantityValue acrefeetperhour) { - double value = (double) acrefeetperhour; + QuantityValue value = (QuantityValue) acrefeetperhour; return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerHour); } @@ -811,7 +814,7 @@ public static VolumeFlow FromAcreFeetPerHour(QuantityValue acrefeetperhour) /// If value is NaN or Infinity. public static VolumeFlow FromAcreFeetPerMinute(QuantityValue acrefeetperminute) { - double value = (double) acrefeetperminute; + QuantityValue value = (QuantityValue) acrefeetperminute; return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerMinute); } @@ -821,7 +824,7 @@ public static VolumeFlow FromAcreFeetPerMinute(QuantityValue acrefeetperminute) /// If value is NaN or Infinity. public static VolumeFlow FromAcreFeetPerSecond(QuantityValue acrefeetpersecond) { - double value = (double) acrefeetpersecond; + QuantityValue value = (QuantityValue) acrefeetpersecond; return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerSecond); } @@ -831,7 +834,7 @@ public static VolumeFlow FromAcreFeetPerSecond(QuantityValue acrefeetpersecond) /// If value is NaN or Infinity. public static VolumeFlow FromCentilitersPerDay(QuantityValue centilitersperday) { - double value = (double) centilitersperday; + QuantityValue value = (QuantityValue) centilitersperday; return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerDay); } @@ -841,7 +844,7 @@ public static VolumeFlow FromCentilitersPerDay(QuantityValue centilitersperday) /// If value is NaN or Infinity. public static VolumeFlow FromCentilitersPerHour(QuantityValue centilitersperhour) { - double value = (double) centilitersperhour; + QuantityValue value = (QuantityValue) centilitersperhour; return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerHour); } @@ -851,7 +854,7 @@ public static VolumeFlow FromCentilitersPerHour(QuantityValue centilitersperhour /// If value is NaN or Infinity. public static VolumeFlow FromCentilitersPerMinute(QuantityValue centilitersperminute) { - double value = (double) centilitersperminute; + QuantityValue value = (QuantityValue) centilitersperminute; return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerMinute); } @@ -861,7 +864,7 @@ public static VolumeFlow FromCentilitersPerMinute(QuantityValue centiliterspermi /// If value is NaN or Infinity. public static VolumeFlow FromCentilitersPerSecond(QuantityValue centiliterspersecond) { - double value = (double) centiliterspersecond; + QuantityValue value = (QuantityValue) centiliterspersecond; return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerSecond); } @@ -871,7 +874,7 @@ public static VolumeFlow FromCentilitersPerSecond(QuantityValue centilitersperse /// If value is NaN or Infinity. public static VolumeFlow FromCubicCentimetersPerMinute(QuantityValue cubiccentimetersperminute) { - double value = (double) cubiccentimetersperminute; + QuantityValue value = (QuantityValue) cubiccentimetersperminute; return new VolumeFlow(value, VolumeFlowUnit.CubicCentimeterPerMinute); } @@ -881,7 +884,7 @@ public static VolumeFlow FromCubicCentimetersPerMinute(QuantityValue cubiccentim /// If value is NaN or Infinity. public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersperminute) { - double value = (double) cubicdecimetersperminute; + QuantityValue value = (QuantityValue) cubicdecimetersperminute; return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); } @@ -891,7 +894,7 @@ public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue cubicdecimet /// If value is NaN or Infinity. public static VolumeFlow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) { - double value = (double) cubicfeetperhour; + QuantityValue value = (QuantityValue) cubicfeetperhour; return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); } @@ -901,7 +904,7 @@ public static VolumeFlow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) /// If value is NaN or Infinity. public static VolumeFlow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) { - double value = (double) cubicfeetperminute; + QuantityValue value = (QuantityValue) cubicfeetperminute; return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); } @@ -911,7 +914,7 @@ public static VolumeFlow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute /// If value is NaN or Infinity. public static VolumeFlow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) { - double value = (double) cubicfeetpersecond; + QuantityValue value = (QuantityValue) cubicfeetpersecond; return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); } @@ -921,7 +924,7 @@ public static VolumeFlow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond /// If value is NaN or Infinity. public static VolumeFlow FromCubicMetersPerDay(QuantityValue cubicmetersperday) { - double value = (double) cubicmetersperday; + QuantityValue value = (QuantityValue) cubicmetersperday; return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerDay); } @@ -931,7 +934,7 @@ public static VolumeFlow FromCubicMetersPerDay(QuantityValue cubicmetersperday) /// If value is NaN or Infinity. public static VolumeFlow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) { - double value = (double) cubicmetersperhour; + QuantityValue value = (QuantityValue) cubicmetersperhour; return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); } @@ -941,7 +944,7 @@ public static VolumeFlow FromCubicMetersPerHour(QuantityValue cubicmetersperhour /// If value is NaN or Infinity. public static VolumeFlow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) { - double value = (double) cubicmetersperminute; + QuantityValue value = (QuantityValue) cubicmetersperminute; return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); } @@ -951,7 +954,7 @@ public static VolumeFlow FromCubicMetersPerMinute(QuantityValue cubicmeterspermi /// If value is NaN or Infinity. public static VolumeFlow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) { - double value = (double) cubicmeterspersecond; + QuantityValue value = (QuantityValue) cubicmeterspersecond; return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); } @@ -961,7 +964,7 @@ public static VolumeFlow FromCubicMetersPerSecond(QuantityValue cubicmetersperse /// If value is NaN or Infinity. public static VolumeFlow FromCubicMillimetersPerSecond(QuantityValue cubicmillimeterspersecond) { - double value = (double) cubicmillimeterspersecond; + QuantityValue value = (QuantityValue) cubicmillimeterspersecond; return new VolumeFlow(value, VolumeFlowUnit.CubicMillimeterPerSecond); } @@ -971,7 +974,7 @@ public static VolumeFlow FromCubicMillimetersPerSecond(QuantityValue cubicmillim /// If value is NaN or Infinity. public static VolumeFlow FromCubicYardsPerDay(QuantityValue cubicyardsperday) { - double value = (double) cubicyardsperday; + QuantityValue value = (QuantityValue) cubicyardsperday; return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerDay); } @@ -981,7 +984,7 @@ public static VolumeFlow FromCubicYardsPerDay(QuantityValue cubicyardsperday) /// If value is NaN or Infinity. public static VolumeFlow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) { - double value = (double) cubicyardsperhour; + QuantityValue value = (QuantityValue) cubicyardsperhour; return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); } @@ -991,7 +994,7 @@ public static VolumeFlow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) /// If value is NaN or Infinity. public static VolumeFlow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) { - double value = (double) cubicyardsperminute; + QuantityValue value = (QuantityValue) cubicyardsperminute; return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); } @@ -1001,7 +1004,7 @@ public static VolumeFlow FromCubicYardsPerMinute(QuantityValue cubicyardsperminu /// If value is NaN or Infinity. public static VolumeFlow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) { - double value = (double) cubicyardspersecond; + QuantityValue value = (QuantityValue) cubicyardspersecond; return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); } @@ -1011,7 +1014,7 @@ public static VolumeFlow FromCubicYardsPerSecond(QuantityValue cubicyardsperseco /// If value is NaN or Infinity. public static VolumeFlow FromDecilitersPerDay(QuantityValue decilitersperday) { - double value = (double) decilitersperday; + QuantityValue value = (QuantityValue) decilitersperday; return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerDay); } @@ -1021,7 +1024,7 @@ public static VolumeFlow FromDecilitersPerDay(QuantityValue decilitersperday) /// If value is NaN or Infinity. public static VolumeFlow FromDecilitersPerHour(QuantityValue decilitersperhour) { - double value = (double) decilitersperhour; + QuantityValue value = (QuantityValue) decilitersperhour; return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerHour); } @@ -1031,7 +1034,7 @@ public static VolumeFlow FromDecilitersPerHour(QuantityValue decilitersperhour) /// If value is NaN or Infinity. public static VolumeFlow FromDecilitersPerMinute(QuantityValue decilitersperminute) { - double value = (double) decilitersperminute; + QuantityValue value = (QuantityValue) decilitersperminute; return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerMinute); } @@ -1041,7 +1044,7 @@ public static VolumeFlow FromDecilitersPerMinute(QuantityValue decilitersperminu /// If value is NaN or Infinity. public static VolumeFlow FromDecilitersPerSecond(QuantityValue deciliterspersecond) { - double value = (double) deciliterspersecond; + QuantityValue value = (QuantityValue) deciliterspersecond; return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerSecond); } @@ -1051,7 +1054,7 @@ public static VolumeFlow FromDecilitersPerSecond(QuantityValue decilitersperseco /// If value is NaN or Infinity. public static VolumeFlow FromKilolitersPerDay(QuantityValue kilolitersperday) { - double value = (double) kilolitersperday; + QuantityValue value = (QuantityValue) kilolitersperday; return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerDay); } @@ -1061,7 +1064,7 @@ public static VolumeFlow FromKilolitersPerDay(QuantityValue kilolitersperday) /// If value is NaN or Infinity. public static VolumeFlow FromKilolitersPerHour(QuantityValue kilolitersperhour) { - double value = (double) kilolitersperhour; + QuantityValue value = (QuantityValue) kilolitersperhour; return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerHour); } @@ -1071,7 +1074,7 @@ public static VolumeFlow FromKilolitersPerHour(QuantityValue kilolitersperhour) /// If value is NaN or Infinity. public static VolumeFlow FromKilolitersPerMinute(QuantityValue kilolitersperminute) { - double value = (double) kilolitersperminute; + QuantityValue value = (QuantityValue) kilolitersperminute; return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerMinute); } @@ -1081,7 +1084,7 @@ public static VolumeFlow FromKilolitersPerMinute(QuantityValue kilolitersperminu /// If value is NaN or Infinity. public static VolumeFlow FromKilolitersPerSecond(QuantityValue kiloliterspersecond) { - double value = (double) kiloliterspersecond; + QuantityValue value = (QuantityValue) kiloliterspersecond; return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerSecond); } @@ -1091,7 +1094,7 @@ public static VolumeFlow FromKilolitersPerSecond(QuantityValue kilolitersperseco /// If value is NaN or Infinity. public static VolumeFlow FromKilousGallonsPerMinute(QuantityValue kilousgallonsperminute) { - double value = (double) kilousgallonsperminute; + QuantityValue value = (QuantityValue) kilousgallonsperminute; return new VolumeFlow(value, VolumeFlowUnit.KilousGallonPerMinute); } @@ -1101,7 +1104,7 @@ public static VolumeFlow FromKilousGallonsPerMinute(QuantityValue kilousgallonsp /// If value is NaN or Infinity. public static VolumeFlow FromLitersPerDay(QuantityValue litersperday) { - double value = (double) litersperday; + QuantityValue value = (QuantityValue) litersperday; return new VolumeFlow(value, VolumeFlowUnit.LiterPerDay); } @@ -1111,7 +1114,7 @@ public static VolumeFlow FromLitersPerDay(QuantityValue litersperday) /// If value is NaN or Infinity. public static VolumeFlow FromLitersPerHour(QuantityValue litersperhour) { - double value = (double) litersperhour; + QuantityValue value = (QuantityValue) litersperhour; return new VolumeFlow(value, VolumeFlowUnit.LiterPerHour); } @@ -1121,7 +1124,7 @@ public static VolumeFlow FromLitersPerHour(QuantityValue litersperhour) /// If value is NaN or Infinity. public static VolumeFlow FromLitersPerMinute(QuantityValue litersperminute) { - double value = (double) litersperminute; + QuantityValue value = (QuantityValue) litersperminute; return new VolumeFlow(value, VolumeFlowUnit.LiterPerMinute); } @@ -1131,7 +1134,7 @@ public static VolumeFlow FromLitersPerMinute(QuantityValue litersperminute) /// If value is NaN or Infinity. public static VolumeFlow FromLitersPerSecond(QuantityValue literspersecond) { - double value = (double) literspersecond; + QuantityValue value = (QuantityValue) literspersecond; return new VolumeFlow(value, VolumeFlowUnit.LiterPerSecond); } @@ -1141,7 +1144,7 @@ public static VolumeFlow FromLitersPerSecond(QuantityValue literspersecond) /// If value is NaN or Infinity. public static VolumeFlow FromMegalitersPerDay(QuantityValue megalitersperday) { - double value = (double) megalitersperday; + QuantityValue value = (QuantityValue) megalitersperday; return new VolumeFlow(value, VolumeFlowUnit.MegaliterPerDay); } @@ -1151,7 +1154,7 @@ public static VolumeFlow FromMegalitersPerDay(QuantityValue megalitersperday) /// If value is NaN or Infinity. public static VolumeFlow FromMegaukGallonsPerSecond(QuantityValue megaukgallonspersecond) { - double value = (double) megaukgallonspersecond; + QuantityValue value = (QuantityValue) megaukgallonspersecond; return new VolumeFlow(value, VolumeFlowUnit.MegaukGallonPerSecond); } @@ -1161,7 +1164,7 @@ public static VolumeFlow FromMegaukGallonsPerSecond(QuantityValue megaukgallonsp /// If value is NaN or Infinity. public static VolumeFlow FromMicrolitersPerDay(QuantityValue microlitersperday) { - double value = (double) microlitersperday; + QuantityValue value = (QuantityValue) microlitersperday; return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerDay); } @@ -1171,7 +1174,7 @@ public static VolumeFlow FromMicrolitersPerDay(QuantityValue microlitersperday) /// If value is NaN or Infinity. public static VolumeFlow FromMicrolitersPerHour(QuantityValue microlitersperhour) { - double value = (double) microlitersperhour; + QuantityValue value = (QuantityValue) microlitersperhour; return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerHour); } @@ -1181,7 +1184,7 @@ public static VolumeFlow FromMicrolitersPerHour(QuantityValue microlitersperhour /// If value is NaN or Infinity. public static VolumeFlow FromMicrolitersPerMinute(QuantityValue microlitersperminute) { - double value = (double) microlitersperminute; + QuantityValue value = (QuantityValue) microlitersperminute; return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerMinute); } @@ -1191,7 +1194,7 @@ public static VolumeFlow FromMicrolitersPerMinute(QuantityValue microliterspermi /// If value is NaN or Infinity. public static VolumeFlow FromMicrolitersPerSecond(QuantityValue microliterspersecond) { - double value = (double) microliterspersecond; + QuantityValue value = (QuantityValue) microliterspersecond; return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerSecond); } @@ -1201,7 +1204,7 @@ public static VolumeFlow FromMicrolitersPerSecond(QuantityValue microlitersperse /// If value is NaN or Infinity. public static VolumeFlow FromMillilitersPerDay(QuantityValue millilitersperday) { - double value = (double) millilitersperday; + QuantityValue value = (QuantityValue) millilitersperday; return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerDay); } @@ -1211,7 +1214,7 @@ public static VolumeFlow FromMillilitersPerDay(QuantityValue millilitersperday) /// If value is NaN or Infinity. public static VolumeFlow FromMillilitersPerHour(QuantityValue millilitersperhour) { - double value = (double) millilitersperhour; + QuantityValue value = (QuantityValue) millilitersperhour; return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerHour); } @@ -1221,7 +1224,7 @@ public static VolumeFlow FromMillilitersPerHour(QuantityValue millilitersperhour /// If value is NaN or Infinity. public static VolumeFlow FromMillilitersPerMinute(QuantityValue millilitersperminute) { - double value = (double) millilitersperminute; + QuantityValue value = (QuantityValue) millilitersperminute; return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerMinute); } @@ -1231,7 +1234,7 @@ public static VolumeFlow FromMillilitersPerMinute(QuantityValue milliliterspermi /// If value is NaN or Infinity. public static VolumeFlow FromMillilitersPerSecond(QuantityValue milliliterspersecond) { - double value = (double) milliliterspersecond; + QuantityValue value = (QuantityValue) milliliterspersecond; return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerSecond); } @@ -1241,7 +1244,7 @@ public static VolumeFlow FromMillilitersPerSecond(QuantityValue millilitersperse /// If value is NaN or Infinity. public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) { - double value = (double) millionusgallonsperday; + QuantityValue value = (QuantityValue) millionusgallonsperday; return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonPerDay); } @@ -1251,7 +1254,7 @@ public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallo /// If value is NaN or Infinity. public static VolumeFlow FromNanolitersPerDay(QuantityValue nanolitersperday) { - double value = (double) nanolitersperday; + QuantityValue value = (QuantityValue) nanolitersperday; return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerDay); } @@ -1261,7 +1264,7 @@ public static VolumeFlow FromNanolitersPerDay(QuantityValue nanolitersperday) /// If value is NaN or Infinity. public static VolumeFlow FromNanolitersPerHour(QuantityValue nanolitersperhour) { - double value = (double) nanolitersperhour; + QuantityValue value = (QuantityValue) nanolitersperhour; return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerHour); } @@ -1271,7 +1274,7 @@ public static VolumeFlow FromNanolitersPerHour(QuantityValue nanolitersperhour) /// If value is NaN or Infinity. public static VolumeFlow FromNanolitersPerMinute(QuantityValue nanolitersperminute) { - double value = (double) nanolitersperminute; + QuantityValue value = (QuantityValue) nanolitersperminute; return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerMinute); } @@ -1281,7 +1284,7 @@ public static VolumeFlow FromNanolitersPerMinute(QuantityValue nanolitersperminu /// If value is NaN or Infinity. public static VolumeFlow FromNanolitersPerSecond(QuantityValue nanoliterspersecond) { - double value = (double) nanoliterspersecond; + QuantityValue value = (QuantityValue) nanoliterspersecond; return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerSecond); } @@ -1291,7 +1294,7 @@ public static VolumeFlow FromNanolitersPerSecond(QuantityValue nanolitersperseco /// If value is NaN or Infinity. public static VolumeFlow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) { - double value = (double) oilbarrelsperday; + QuantityValue value = (QuantityValue) oilbarrelsperday; return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerDay); } @@ -1301,7 +1304,7 @@ public static VolumeFlow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) /// If value is NaN or Infinity. public static VolumeFlow FromOilBarrelsPerHour(QuantityValue oilbarrelsperhour) { - double value = (double) oilbarrelsperhour; + QuantityValue value = (QuantityValue) oilbarrelsperhour; return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerHour); } @@ -1311,7 +1314,7 @@ public static VolumeFlow FromOilBarrelsPerHour(QuantityValue oilbarrelsperhour) /// If value is NaN or Infinity. public static VolumeFlow FromOilBarrelsPerMinute(QuantityValue oilbarrelsperminute) { - double value = (double) oilbarrelsperminute; + QuantityValue value = (QuantityValue) oilbarrelsperminute; return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerMinute); } @@ -1321,7 +1324,7 @@ public static VolumeFlow FromOilBarrelsPerMinute(QuantityValue oilbarrelsperminu /// If value is NaN or Infinity. public static VolumeFlow FromOilBarrelsPerSecond(QuantityValue oilbarrelspersecond) { - double value = (double) oilbarrelspersecond; + QuantityValue value = (QuantityValue) oilbarrelspersecond; return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerSecond); } @@ -1331,7 +1334,7 @@ public static VolumeFlow FromOilBarrelsPerSecond(QuantityValue oilbarrelsperseco /// If value is NaN or Infinity. public static VolumeFlow FromUkGallonsPerDay(QuantityValue ukgallonsperday) { - double value = (double) ukgallonsperday; + QuantityValue value = (QuantityValue) ukgallonsperday; return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerDay); } @@ -1341,7 +1344,7 @@ public static VolumeFlow FromUkGallonsPerDay(QuantityValue ukgallonsperday) /// If value is NaN or Infinity. public static VolumeFlow FromUkGallonsPerHour(QuantityValue ukgallonsperhour) { - double value = (double) ukgallonsperhour; + QuantityValue value = (QuantityValue) ukgallonsperhour; return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerHour); } @@ -1351,7 +1354,7 @@ public static VolumeFlow FromUkGallonsPerHour(QuantityValue ukgallonsperhour) /// If value is NaN or Infinity. public static VolumeFlow FromUkGallonsPerMinute(QuantityValue ukgallonsperminute) { - double value = (double) ukgallonsperminute; + QuantityValue value = (QuantityValue) ukgallonsperminute; return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerMinute); } @@ -1361,7 +1364,7 @@ public static VolumeFlow FromUkGallonsPerMinute(QuantityValue ukgallonsperminute /// If value is NaN or Infinity. public static VolumeFlow FromUkGallonsPerSecond(QuantityValue ukgallonspersecond) { - double value = (double) ukgallonspersecond; + QuantityValue value = (QuantityValue) ukgallonspersecond; return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerSecond); } @@ -1371,7 +1374,7 @@ public static VolumeFlow FromUkGallonsPerSecond(QuantityValue ukgallonspersecond /// If value is NaN or Infinity. public static VolumeFlow FromUsGallonsPerDay(QuantityValue usgallonsperday) { - double value = (double) usgallonsperday; + QuantityValue value = (QuantityValue) usgallonsperday; return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerDay); } @@ -1381,7 +1384,7 @@ public static VolumeFlow FromUsGallonsPerDay(QuantityValue usgallonsperday) /// If value is NaN or Infinity. public static VolumeFlow FromUsGallonsPerHour(QuantityValue usgallonsperhour) { - double value = (double) usgallonsperhour; + QuantityValue value = (QuantityValue) usgallonsperhour; return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerHour); } @@ -1391,7 +1394,7 @@ public static VolumeFlow FromUsGallonsPerHour(QuantityValue usgallonsperhour) /// If value is NaN or Infinity. public static VolumeFlow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) { - double value = (double) usgallonsperminute; + QuantityValue value = (QuantityValue) usgallonsperminute; return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerMinute); } @@ -1401,7 +1404,7 @@ public static VolumeFlow FromUsGallonsPerMinute(QuantityValue usgallonsperminute /// If value is NaN or Infinity. public static VolumeFlow FromUsGallonsPerSecond(QuantityValue usgallonspersecond) { - double value = (double) usgallonspersecond; + QuantityValue value = (QuantityValue) usgallonspersecond; return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerSecond); } @@ -1413,7 +1416,7 @@ public static VolumeFlow FromUsGallonsPerSecond(QuantityValue usgallonspersecond /// VolumeFlow unit value. public static VolumeFlow From(QuantityValue value, VolumeFlowUnit fromUnit) { - return new VolumeFlow((double)value, fromUnit); + return new VolumeFlow((QuantityValue)value, fromUnit); } #endregion @@ -1583,25 +1586,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum } /// Get from multiplying value and . - public static VolumeFlow operator *(double left, VolumeFlow right) + public static VolumeFlow operator *(QuantityValue left, VolumeFlow right) { return new VolumeFlow(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static VolumeFlow operator *(VolumeFlow left, double right) + public static VolumeFlow operator *(VolumeFlow left, QuantityValue right) { return new VolumeFlow(left.Value * right, left.Unit); } /// Get from dividing by value. - public static VolumeFlow operator /(VolumeFlow left, double right) + public static VolumeFlow operator /(VolumeFlow left, QuantityValue right) { return new VolumeFlow(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(VolumeFlow left, VolumeFlow right) + public static QuantityValue operator /(VolumeFlow left, VolumeFlow right) { return left.CubicMetersPerSecond / right.CubicMetersPerSecond; } @@ -1634,6 +1637,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(VolumeFlow left, VolumeFlow right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(VolumeFlow left, VolumeFlow right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -1646,7 +1662,29 @@ public int CompareTo(object obj) /// public int CompareTo(VolumeFlow other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is VolumeFlow objVolumeFlow)) + return false; + return Equals(objVolumeFlow); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(VolumeFlow other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -1689,13 +1727,13 @@ public int CompareTo(VolumeFlow other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VolumeFlow other, double tolerance, ComparisonType comparisonType) + public bool Equals(VolumeFlow other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1706,7 +1744,7 @@ public bool Equals(VolumeFlow other, double tolerance, ComparisonType comparison /// A hash code for the current VolumeFlow. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -1717,17 +1755,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(VolumeFlowUnit unit) + public QuantityValue As(VolumeFlowUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1742,12 +1779,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is VolumeFlowUnit unitAsVolumeFlowUnit)) + if (!(unit is VolumeFlowUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowUnit)} is supported.", nameof(unit)); - return As(unitAsVolumeFlowUnit); + return (QuantityValue)As(typedUnit); } /// @@ -1779,7 +1816,7 @@ public VolumeFlow ToUnit(VolumeFlowUnit unit, UnitConverter unitConverter) var converted = conversionFunction(this); return (VolumeFlow)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(VolumeFlowUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -1787,17 +1824,17 @@ public VolumeFlow ToUnit(VolumeFlowUnit unit, UnitConverter unitConverter) } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumeFlowUnit unitAsVolumeFlowUnit)) + if (!(unit is VolumeFlowUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumeFlowUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1824,10 +1861,10 @@ public VolumeFlow ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(VolumeFlowUnit unit) + private QuantityValue GetValueAs(VolumeFlowUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs index 93e98d1704..4f27c89490 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// /// [DataContract] - public partial struct VolumeFlowPerArea : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct VolumeFlowPerArea : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -73,9 +73,9 @@ static VolumeFlowPerArea() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public VolumeFlowPerArea(double value, VolumeFlowPerAreaUnit unit) + public VolumeFlowPerArea(QuantityValue value, VolumeFlowPerAreaUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -87,14 +87,14 @@ public VolumeFlowPerArea(double value, VolumeFlowPerAreaUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public VolumeFlowPerArea(double value, UnitSystem unitSystem) + public VolumeFlowPerArea(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -135,7 +135,10 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -158,14 +161,14 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicFeetPerMinutePerSquareFoot => As(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); + public QuantityValue CubicFeetPerMinutePerSquareFoot => As(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMetersPerSecondPerSquareMeter => As(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); + public QuantityValue CubicMetersPerSecondPerSquareMeter => As(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); #endregion @@ -224,7 +227,7 @@ public static string GetAbbreviation(VolumeFlowPerAreaUnit unit, IFormatProvider /// If value is NaN or Infinity. public static VolumeFlowPerArea FromCubicFeetPerMinutePerSquareFoot(QuantityValue cubicfeetperminutepersquarefoot) { - double value = (double) cubicfeetperminutepersquarefoot; + QuantityValue value = (QuantityValue) cubicfeetperminutepersquarefoot; return new VolumeFlowPerArea(value, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); } @@ -234,7 +237,7 @@ public static VolumeFlowPerArea FromCubicFeetPerMinutePerSquareFoot(QuantityValu /// If value is NaN or Infinity. public static VolumeFlowPerArea FromCubicMetersPerSecondPerSquareMeter(QuantityValue cubicmeterspersecondpersquaremeter) { - double value = (double) cubicmeterspersecondpersquaremeter; + QuantityValue value = (QuantityValue) cubicmeterspersecondpersquaremeter; return new VolumeFlowPerArea(value, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); } @@ -246,7 +249,7 @@ public static VolumeFlowPerArea FromCubicMetersPerSecondPerSquareMeter(QuantityV /// VolumeFlowPerArea unit value. public static VolumeFlowPerArea From(QuantityValue value, VolumeFlowPerAreaUnit fromUnit) { - return new VolumeFlowPerArea((double)value, fromUnit); + return new VolumeFlowPerArea((QuantityValue)value, fromUnit); } #endregion @@ -416,25 +419,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum } /// Get from multiplying value and . - public static VolumeFlowPerArea operator *(double left, VolumeFlowPerArea right) + public static VolumeFlowPerArea operator *(QuantityValue left, VolumeFlowPerArea right) { return new VolumeFlowPerArea(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static VolumeFlowPerArea operator *(VolumeFlowPerArea left, double right) + public static VolumeFlowPerArea operator *(VolumeFlowPerArea left, QuantityValue right) { return new VolumeFlowPerArea(left.Value * right, left.Unit); } /// Get from dividing by value. - public static VolumeFlowPerArea operator /(VolumeFlowPerArea left, double right) + public static VolumeFlowPerArea operator /(VolumeFlowPerArea left, QuantityValue right) { return new VolumeFlowPerArea(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(VolumeFlowPerArea left, VolumeFlowPerArea right) + public static QuantityValue operator /(VolumeFlowPerArea left, VolumeFlowPerArea right) { return left.CubicMetersPerSecondPerSquareMeter / right.CubicMetersPerSecondPerSquareMeter; } @@ -467,6 +470,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -479,7 +495,29 @@ public int CompareTo(object obj) /// public int CompareTo(VolumeFlowPerArea other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is VolumeFlowPerArea objVolumeFlowPerArea)) + return false; + return Equals(objVolumeFlowPerArea); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(VolumeFlowPerArea other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -522,13 +560,13 @@ public int CompareTo(VolumeFlowPerArea other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VolumeFlowPerArea other, double tolerance, ComparisonType comparisonType) + public bool Equals(VolumeFlowPerArea other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -539,7 +577,7 @@ public bool Equals(VolumeFlowPerArea other, double tolerance, ComparisonType com /// A hash code for the current VolumeFlowPerArea. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -550,17 +588,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(VolumeFlowPerAreaUnit unit) + public QuantityValue As(VolumeFlowPerAreaUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -575,12 +612,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is VolumeFlowPerAreaUnit unitAsVolumeFlowPerAreaUnit)) + if (!(unit is VolumeFlowPerAreaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowPerAreaUnit)} is supported.", nameof(unit)); - return As(unitAsVolumeFlowPerAreaUnit); + return (QuantityValue)As(typedUnit); } /// @@ -612,7 +649,7 @@ public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit, UnitConverter unitCo var converted = conversionFunction(this); return (VolumeFlowPerArea)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(VolumeFlowPerAreaUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -620,17 +657,17 @@ public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit, UnitConverter unitCo } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumeFlowPerAreaUnit unitAsVolumeFlowPerAreaUnit)) + if (!(unit is VolumeFlowPerAreaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowPerAreaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumeFlowPerAreaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -657,10 +694,10 @@ public VolumeFlowPerArea ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(VolumeFlowPerAreaUnit unit) + private QuantityValue GetValueAs(VolumeFlowPerAreaUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs index d07460ee38..3b401ddbe6 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// Volume, typically of fluid, that a container can hold within a unit of length. /// [DataContract] - public partial struct VolumePerLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct VolumePerLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -78,9 +78,9 @@ static VolumePerLength() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public VolumePerLength(double value, VolumePerLengthUnit unit) + public VolumePerLength(QuantityValue value, VolumePerLengthUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -92,14 +92,14 @@ public VolumePerLength(double value, VolumePerLengthUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public VolumePerLength(double value, UnitSystem unitSystem) + public VolumePerLength(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -140,7 +140,10 @@ public VolumePerLength(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -163,39 +166,39 @@ public VolumePerLength(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicMetersPerMeter => As(VolumePerLengthUnit.CubicMeterPerMeter); + public QuantityValue CubicMetersPerMeter => As(VolumePerLengthUnit.CubicMeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicYardsPerFoot => As(VolumePerLengthUnit.CubicYardPerFoot); + public QuantityValue CubicYardsPerFoot => As(VolumePerLengthUnit.CubicYardPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CubicYardsPerUsSurveyFoot => As(VolumePerLengthUnit.CubicYardPerUsSurveyFoot); + public QuantityValue CubicYardsPerUsSurveyFoot => As(VolumePerLengthUnit.CubicYardPerUsSurveyFoot); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPerKilometer => As(VolumePerLengthUnit.LiterPerKilometer); + public QuantityValue LitersPerKilometer => As(VolumePerLengthUnit.LiterPerKilometer); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPerMeter => As(VolumePerLengthUnit.LiterPerMeter); + public QuantityValue LitersPerMeter => As(VolumePerLengthUnit.LiterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double LitersPerMillimeter => As(VolumePerLengthUnit.LiterPerMillimeter); + public QuantityValue LitersPerMillimeter => As(VolumePerLengthUnit.LiterPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double OilBarrelsPerFoot => As(VolumePerLengthUnit.OilBarrelPerFoot); + public QuantityValue OilBarrelsPerFoot => As(VolumePerLengthUnit.OilBarrelPerFoot); #endregion @@ -269,7 +272,7 @@ public static string GetAbbreviation(VolumePerLengthUnit unit, IFormatProvider? /// If value is NaN or Infinity. public static VolumePerLength FromCubicMetersPerMeter(QuantityValue cubicmeterspermeter) { - double value = (double) cubicmeterspermeter; + QuantityValue value = (QuantityValue) cubicmeterspermeter; return new VolumePerLength(value, VolumePerLengthUnit.CubicMeterPerMeter); } @@ -279,7 +282,7 @@ public static VolumePerLength FromCubicMetersPerMeter(QuantityValue cubicmetersp /// If value is NaN or Infinity. public static VolumePerLength FromCubicYardsPerFoot(QuantityValue cubicyardsperfoot) { - double value = (double) cubicyardsperfoot; + QuantityValue value = (QuantityValue) cubicyardsperfoot; return new VolumePerLength(value, VolumePerLengthUnit.CubicYardPerFoot); } @@ -289,7 +292,7 @@ public static VolumePerLength FromCubicYardsPerFoot(QuantityValue cubicyardsperf /// If value is NaN or Infinity. public static VolumePerLength FromCubicYardsPerUsSurveyFoot(QuantityValue cubicyardsperussurveyfoot) { - double value = (double) cubicyardsperussurveyfoot; + QuantityValue value = (QuantityValue) cubicyardsperussurveyfoot; return new VolumePerLength(value, VolumePerLengthUnit.CubicYardPerUsSurveyFoot); } @@ -299,7 +302,7 @@ public static VolumePerLength FromCubicYardsPerUsSurveyFoot(QuantityValue cubicy /// If value is NaN or Infinity. public static VolumePerLength FromLitersPerKilometer(QuantityValue litersperkilometer) { - double value = (double) litersperkilometer; + QuantityValue value = (QuantityValue) litersperkilometer; return new VolumePerLength(value, VolumePerLengthUnit.LiterPerKilometer); } @@ -309,7 +312,7 @@ public static VolumePerLength FromLitersPerKilometer(QuantityValue litersperkilo /// If value is NaN or Infinity. public static VolumePerLength FromLitersPerMeter(QuantityValue literspermeter) { - double value = (double) literspermeter; + QuantityValue value = (QuantityValue) literspermeter; return new VolumePerLength(value, VolumePerLengthUnit.LiterPerMeter); } @@ -319,7 +322,7 @@ public static VolumePerLength FromLitersPerMeter(QuantityValue literspermeter) /// If value is NaN or Infinity. public static VolumePerLength FromLitersPerMillimeter(QuantityValue literspermillimeter) { - double value = (double) literspermillimeter; + QuantityValue value = (QuantityValue) literspermillimeter; return new VolumePerLength(value, VolumePerLengthUnit.LiterPerMillimeter); } @@ -329,7 +332,7 @@ public static VolumePerLength FromLitersPerMillimeter(QuantityValue literspermil /// If value is NaN or Infinity. public static VolumePerLength FromOilBarrelsPerFoot(QuantityValue oilbarrelsperfoot) { - double value = (double) oilbarrelsperfoot; + QuantityValue value = (QuantityValue) oilbarrelsperfoot; return new VolumePerLength(value, VolumePerLengthUnit.OilBarrelPerFoot); } @@ -341,7 +344,7 @@ public static VolumePerLength FromOilBarrelsPerFoot(QuantityValue oilbarrelsperf /// VolumePerLength unit value. public static VolumePerLength From(QuantityValue value, VolumePerLengthUnit fromUnit) { - return new VolumePerLength((double)value, fromUnit); + return new VolumePerLength((QuantityValue)value, fromUnit); } #endregion @@ -511,25 +514,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum } /// Get from multiplying value and . - public static VolumePerLength operator *(double left, VolumePerLength right) + public static VolumePerLength operator *(QuantityValue left, VolumePerLength right) { return new VolumePerLength(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static VolumePerLength operator *(VolumePerLength left, double right) + public static VolumePerLength operator *(VolumePerLength left, QuantityValue right) { return new VolumePerLength(left.Value * right, left.Unit); } /// Get from dividing by value. - public static VolumePerLength operator /(VolumePerLength left, double right) + public static VolumePerLength operator /(VolumePerLength left, QuantityValue right) { return new VolumePerLength(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(VolumePerLength left, VolumePerLength right) + public static QuantityValue operator /(VolumePerLength left, VolumePerLength right) { return left.CubicMetersPerMeter / right.CubicMetersPerMeter; } @@ -562,6 +565,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(VolumePerLength left, VolumePerLength right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(VolumePerLength left, VolumePerLength right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -574,7 +590,29 @@ public int CompareTo(object obj) /// public int CompareTo(VolumePerLength other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is VolumePerLength objVolumePerLength)) + return false; + return Equals(objVolumePerLength); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(VolumePerLength other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -617,13 +655,13 @@ public int CompareTo(VolumePerLength other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VolumePerLength other, double tolerance, ComparisonType comparisonType) + public bool Equals(VolumePerLength other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -634,7 +672,7 @@ public bool Equals(VolumePerLength other, double tolerance, ComparisonType compa /// A hash code for the current VolumePerLength. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -645,17 +683,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(VolumePerLengthUnit unit) + public QuantityValue As(VolumePerLengthUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -670,12 +707,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is VolumePerLengthUnit unitAsVolumePerLengthUnit)) + if (!(unit is VolumePerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumePerLengthUnit)} is supported.", nameof(unit)); - return As(unitAsVolumePerLengthUnit); + return (QuantityValue)As(typedUnit); } /// @@ -707,7 +744,7 @@ public VolumePerLength ToUnit(VolumePerLengthUnit unit, UnitConverter unitConver var converted = conversionFunction(this); return (VolumePerLength)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(VolumePerLengthUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -715,17 +752,17 @@ public VolumePerLength ToUnit(VolumePerLengthUnit unit, UnitConverter unitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumePerLengthUnit unitAsVolumePerLengthUnit)) + if (!(unit is VolumePerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumePerLengthUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumePerLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -752,10 +789,10 @@ public VolumePerLength ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(VolumePerLengthUnit unit) + private QuantityValue GetValueAs(VolumePerLengthUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs index 3ca758cbc0..efcc549362 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs @@ -38,13 +38,13 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Volumetric_heat_capacity /// [DataContract] - public partial struct VolumetricHeatCapacity : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct VolumetricHeatCapacity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -83,9 +83,9 @@ static VolumetricHeatCapacity() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public VolumetricHeatCapacity(double value, VolumetricHeatCapacityUnit unit) + public VolumetricHeatCapacity(QuantityValue value, VolumetricHeatCapacityUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -97,14 +97,14 @@ public VolumetricHeatCapacity(double value, VolumetricHeatCapacityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public VolumetricHeatCapacity(double value, UnitSystem unitSystem) + public VolumetricHeatCapacity(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -145,7 +145,10 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -168,49 +171,49 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double BtusPerCubicFootDegreeFahrenheit => As(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); + public QuantityValue BtusPerCubicFootDegreeFahrenheit => As(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); + public QuantityValue CaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); + public QuantityValue JoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double JoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); + public QuantityValue JoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilocaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); + public QuantityValue KilocaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); + public QuantityValue KilojoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double KilojoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); + public QuantityValue KilojoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegajoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); + public QuantityValue MegajoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MegajoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); + public QuantityValue MegajoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); #endregion @@ -290,7 +293,7 @@ public static string GetAbbreviation(VolumetricHeatCapacityUnit unit, IFormatPro /// If value is NaN or Infinity. public static VolumetricHeatCapacity FromBtusPerCubicFootDegreeFahrenheit(QuantityValue btuspercubicfootdegreefahrenheit) { - double value = (double) btuspercubicfootdegreefahrenheit; + QuantityValue value = (QuantityValue) btuspercubicfootdegreefahrenheit; return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); } @@ -300,7 +303,7 @@ public static VolumetricHeatCapacity FromBtusPerCubicFootDegreeFahrenheit(Quanti /// If value is NaN or Infinity. public static VolumetricHeatCapacity FromCaloriesPerCubicCentimeterDegreeCelsius(QuantityValue caloriespercubiccentimeterdegreecelsius) { - double value = (double) caloriespercubiccentimeterdegreecelsius; + QuantityValue value = (QuantityValue) caloriespercubiccentimeterdegreecelsius; return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); } @@ -310,7 +313,7 @@ public static VolumetricHeatCapacity FromCaloriesPerCubicCentimeterDegreeCelsius /// If value is NaN or Infinity. public static VolumetricHeatCapacity FromJoulesPerCubicMeterDegreeCelsius(QuantityValue joulespercubicmeterdegreecelsius) { - double value = (double) joulespercubicmeterdegreecelsius; + QuantityValue value = (QuantityValue) joulespercubicmeterdegreecelsius; return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); } @@ -320,7 +323,7 @@ public static VolumetricHeatCapacity FromJoulesPerCubicMeterDegreeCelsius(Quanti /// If value is NaN or Infinity. public static VolumetricHeatCapacity FromJoulesPerCubicMeterKelvin(QuantityValue joulespercubicmeterkelvin) { - double value = (double) joulespercubicmeterkelvin; + QuantityValue value = (QuantityValue) joulespercubicmeterkelvin; return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); } @@ -330,7 +333,7 @@ public static VolumetricHeatCapacity FromJoulesPerCubicMeterKelvin(QuantityValue /// If value is NaN or Infinity. public static VolumetricHeatCapacity FromKilocaloriesPerCubicCentimeterDegreeCelsius(QuantityValue kilocaloriespercubiccentimeterdegreecelsius) { - double value = (double) kilocaloriespercubiccentimeterdegreecelsius; + QuantityValue value = (QuantityValue) kilocaloriespercubiccentimeterdegreecelsius; return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); } @@ -340,7 +343,7 @@ public static VolumetricHeatCapacity FromKilocaloriesPerCubicCentimeterDegreeCel /// If value is NaN or Infinity. public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterDegreeCelsius(QuantityValue kilojoulespercubicmeterdegreecelsius) { - double value = (double) kilojoulespercubicmeterdegreecelsius; + QuantityValue value = (QuantityValue) kilojoulespercubicmeterdegreecelsius; return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); } @@ -350,7 +353,7 @@ public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterDegreeCelsius(Qu /// If value is NaN or Infinity. public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterKelvin(QuantityValue kilojoulespercubicmeterkelvin) { - double value = (double) kilojoulespercubicmeterkelvin; + QuantityValue value = (QuantityValue) kilojoulespercubicmeterkelvin; return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); } @@ -360,7 +363,7 @@ public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterKelvin(QuantityV /// If value is NaN or Infinity. public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterDegreeCelsius(QuantityValue megajoulespercubicmeterdegreecelsius) { - double value = (double) megajoulespercubicmeterdegreecelsius; + QuantityValue value = (QuantityValue) megajoulespercubicmeterdegreecelsius; return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); } @@ -370,7 +373,7 @@ public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterDegreeCelsius(Qu /// If value is NaN or Infinity. public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterKelvin(QuantityValue megajoulespercubicmeterkelvin) { - double value = (double) megajoulespercubicmeterkelvin; + QuantityValue value = (QuantityValue) megajoulespercubicmeterkelvin; return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); } @@ -382,7 +385,7 @@ public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterKelvin(QuantityV /// VolumetricHeatCapacity unit value. public static VolumetricHeatCapacity From(QuantityValue value, VolumetricHeatCapacityUnit fromUnit) { - return new VolumetricHeatCapacity((double)value, fromUnit); + return new VolumetricHeatCapacity((QuantityValue)value, fromUnit); } #endregion @@ -552,25 +555,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum } /// Get from multiplying value and . - public static VolumetricHeatCapacity operator *(double left, VolumetricHeatCapacity right) + public static VolumetricHeatCapacity operator *(QuantityValue left, VolumetricHeatCapacity right) { return new VolumetricHeatCapacity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static VolumetricHeatCapacity operator *(VolumetricHeatCapacity left, double right) + public static VolumetricHeatCapacity operator *(VolumetricHeatCapacity left, QuantityValue right) { return new VolumetricHeatCapacity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static VolumetricHeatCapacity operator /(VolumetricHeatCapacity left, double right) + public static VolumetricHeatCapacity operator /(VolumetricHeatCapacity left, QuantityValue right) { return new VolumetricHeatCapacity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + public static QuantityValue operator /(VolumetricHeatCapacity left, VolumetricHeatCapacity right) { return left.JoulesPerCubicMeterKelvin / right.JoulesPerCubicMeterKelvin; } @@ -603,6 +606,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -615,7 +631,29 @@ public int CompareTo(object obj) /// public int CompareTo(VolumetricHeatCapacity other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is VolumetricHeatCapacity objVolumetricHeatCapacity)) + return false; + return Equals(objVolumetricHeatCapacity); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(VolumetricHeatCapacity other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -658,13 +696,13 @@ public int CompareTo(VolumetricHeatCapacity other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VolumetricHeatCapacity other, double tolerance, ComparisonType comparisonType) + public bool Equals(VolumetricHeatCapacity other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -675,7 +713,7 @@ public bool Equals(VolumetricHeatCapacity other, double tolerance, ComparisonTyp /// A hash code for the current VolumetricHeatCapacity. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -686,17 +724,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(VolumetricHeatCapacityUnit unit) + public QuantityValue As(VolumetricHeatCapacityUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -711,12 +748,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is VolumetricHeatCapacityUnit unitAsVolumetricHeatCapacityUnit)) + if (!(unit is VolumetricHeatCapacityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumetricHeatCapacityUnit)} is supported.", nameof(unit)); - return As(unitAsVolumetricHeatCapacityUnit); + return (QuantityValue)As(typedUnit); } /// @@ -748,7 +785,7 @@ public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit, UnitConver var converted = conversionFunction(this); return (VolumetricHeatCapacity)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(VolumetricHeatCapacityUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -756,17 +793,17 @@ public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit, UnitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumetricHeatCapacityUnit unitAsVolumetricHeatCapacityUnit)) + if (!(unit is VolumetricHeatCapacityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumetricHeatCapacityUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsVolumetricHeatCapacityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -793,10 +830,10 @@ public VolumetricHeatCapacity ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(VolumetricHeatCapacityUnit unit) + private QuantityValue GetValueAs(VolumetricHeatCapacityUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs index 2ef276467a..5bc210e52b 100644 --- a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs @@ -35,13 +35,13 @@ namespace UnitsNet /// A geometric property of an area that is used to determine the warping stress. /// [DataContract] - public partial struct WarpingMomentOfInertia : IQuantity, IComparable, IComparable, IConvertible, IFormattable + public partial struct WarpingMomentOfInertia : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = "Value", Order = 0)] - private readonly double _value; + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. @@ -77,9 +77,9 @@ static WarpingMomentOfInertia() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public WarpingMomentOfInertia(double value, WarpingMomentOfInertiaUnit unit) + public WarpingMomentOfInertia(QuantityValue value, WarpingMomentOfInertiaUnit unit) { - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = unit; } @@ -91,14 +91,14 @@ public WarpingMomentOfInertia(double value, WarpingMomentOfInertiaUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public WarpingMomentOfInertia(double value, UnitSystem unitSystem) + public WarpingMomentOfInertia(QuantityValue value, UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); - _value = Guard.EnsureValidNumber(value, nameof(value)); + _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } @@ -139,7 +139,10 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + public QuantityValue Value => _value; + + /// + QuantityValue IQuantity.Value => _value; Enum IQuantity.Unit => Unit; @@ -162,34 +165,34 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double CentimetersToTheSixth => As(WarpingMomentOfInertiaUnit.CentimeterToTheSixth); + public QuantityValue CentimetersToTheSixth => As(WarpingMomentOfInertiaUnit.CentimeterToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double DecimetersToTheSixth => As(WarpingMomentOfInertiaUnit.DecimeterToTheSixth); + public QuantityValue DecimetersToTheSixth => As(WarpingMomentOfInertiaUnit.DecimeterToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double FeetToTheSixth => As(WarpingMomentOfInertiaUnit.FootToTheSixth); + public QuantityValue FeetToTheSixth => As(WarpingMomentOfInertiaUnit.FootToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double InchesToTheSixth => As(WarpingMomentOfInertiaUnit.InchToTheSixth); + public QuantityValue InchesToTheSixth => As(WarpingMomentOfInertiaUnit.InchToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MetersToTheSixth => As(WarpingMomentOfInertiaUnit.MeterToTheSixth); + public QuantityValue MetersToTheSixth => As(WarpingMomentOfInertiaUnit.MeterToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets the numeric value of this quantity converted into /// - public double MillimetersToTheSixth => As(WarpingMomentOfInertiaUnit.MillimeterToTheSixth); + public QuantityValue MillimetersToTheSixth => As(WarpingMomentOfInertiaUnit.MillimeterToTheSixth); #endregion @@ -260,7 +263,7 @@ public static string GetAbbreviation(WarpingMomentOfInertiaUnit unit, IFormatPro /// If value is NaN or Infinity. public static WarpingMomentOfInertia FromCentimetersToTheSixth(QuantityValue centimeterstothesixth) { - double value = (double) centimeterstothesixth; + QuantityValue value = (QuantityValue) centimeterstothesixth; return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.CentimeterToTheSixth); } @@ -270,7 +273,7 @@ public static WarpingMomentOfInertia FromCentimetersToTheSixth(QuantityValue cen /// If value is NaN or Infinity. public static WarpingMomentOfInertia FromDecimetersToTheSixth(QuantityValue decimeterstothesixth) { - double value = (double) decimeterstothesixth; + QuantityValue value = (QuantityValue) decimeterstothesixth; return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.DecimeterToTheSixth); } @@ -280,7 +283,7 @@ public static WarpingMomentOfInertia FromDecimetersToTheSixth(QuantityValue deci /// If value is NaN or Infinity. public static WarpingMomentOfInertia FromFeetToTheSixth(QuantityValue feettothesixth) { - double value = (double) feettothesixth; + QuantityValue value = (QuantityValue) feettothesixth; return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.FootToTheSixth); } @@ -290,7 +293,7 @@ public static WarpingMomentOfInertia FromFeetToTheSixth(QuantityValue feettothes /// If value is NaN or Infinity. public static WarpingMomentOfInertia FromInchesToTheSixth(QuantityValue inchestothesixth) { - double value = (double) inchestothesixth; + QuantityValue value = (QuantityValue) inchestothesixth; return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.InchToTheSixth); } @@ -300,7 +303,7 @@ public static WarpingMomentOfInertia FromInchesToTheSixth(QuantityValue inchesto /// If value is NaN or Infinity. public static WarpingMomentOfInertia FromMetersToTheSixth(QuantityValue meterstothesixth) { - double value = (double) meterstothesixth; + QuantityValue value = (QuantityValue) meterstothesixth; return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.MeterToTheSixth); } @@ -310,7 +313,7 @@ public static WarpingMomentOfInertia FromMetersToTheSixth(QuantityValue metersto /// If value is NaN or Infinity. public static WarpingMomentOfInertia FromMillimetersToTheSixth(QuantityValue millimeterstothesixth) { - double value = (double) millimeterstothesixth; + QuantityValue value = (QuantityValue) millimeterstothesixth; return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.MillimeterToTheSixth); } @@ -322,7 +325,7 @@ public static WarpingMomentOfInertia FromMillimetersToTheSixth(QuantityValue mil /// WarpingMomentOfInertia unit value. public static WarpingMomentOfInertia From(QuantityValue value, WarpingMomentOfInertiaUnit fromUnit) { - return new WarpingMomentOfInertia((double)value, fromUnit); + return new WarpingMomentOfInertia((QuantityValue)value, fromUnit); } #endregion @@ -492,25 +495,25 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Warpi } /// Get from multiplying value and . - public static WarpingMomentOfInertia operator *(double left, WarpingMomentOfInertia right) + public static WarpingMomentOfInertia operator *(QuantityValue left, WarpingMomentOfInertia right) { return new WarpingMomentOfInertia(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static WarpingMomentOfInertia operator *(WarpingMomentOfInertia left, double right) + public static WarpingMomentOfInertia operator *(WarpingMomentOfInertia left, QuantityValue right) { return new WarpingMomentOfInertia(left.Value * right, left.Unit); } /// Get from dividing by value. - public static WarpingMomentOfInertia operator /(WarpingMomentOfInertia left, double right) + public static WarpingMomentOfInertia operator /(WarpingMomentOfInertia left, QuantityValue right) { return new WarpingMomentOfInertia(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + public static QuantityValue operator /(WarpingMomentOfInertia left, WarpingMomentOfInertia right) { return left.MetersToTheSixth / right.MetersToTheSixth; } @@ -543,6 +546,19 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Warpi return left.Value > right.GetValueAs(left.Unit); } + /// Returns true if exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator ==(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return left.Equals(right); + } + /// Returns true if not exactly equal. + /// Consider using for safely comparing floating point values. + public static bool operator !=(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return !(left == right); + } + /// public int CompareTo(object obj) { @@ -555,7 +571,29 @@ public int CompareTo(object obj) /// public int CompareTo(WarpingMomentOfInertia other) { - return _value.CompareTo(other.GetValueAs(this.Unit)); + var asFirstUnit = other.GetValueAs(this.Unit); + var asSecondUnit = GetValueAs(other.Unit); + return (_value.CompareTo(asFirstUnit) - other.Value.CompareTo(asSecondUnit)) / 2; + } + + /// + /// Consider using for safely comparing floating point values. + public override bool Equals(object obj) + { + if (obj is null || !(obj is WarpingMomentOfInertia objWarpingMomentOfInertia)) + return false; + return Equals(objWarpingMomentOfInertia); + } + + /// + /// Consider using for safely comparing floating point values. + public bool Equals(WarpingMomentOfInertia other) + { + if (Value.IsDecimal) + return other.Value.Equals(this.GetValueAs(other.Unit)); + if (other.Value.IsDecimal) + return Value.Equals(other.GetValueAs(this.Unit)); + return this.Unit == other.Unit && this.Value.Equals(other.Value); } /// @@ -598,13 +636,13 @@ public int CompareTo(WarpingMomentOfInertia other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(WarpingMomentOfInertia other, double tolerance, ComparisonType comparisonType) + public bool Equals(WarpingMomentOfInertia other, QuantityValue tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + QuantityValue thisValue = this.Value; + QuantityValue otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -615,7 +653,7 @@ public bool Equals(WarpingMomentOfInertia other, double tolerance, ComparisonTyp /// A hash code for the current WarpingMomentOfInertia. public override int GetHashCode() { - return new { Info.Name, Value, Unit }.GetHashCode(); + return Info.Name.GetHashCode(); } #endregion @@ -626,17 +664,16 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(WarpingMomentOfInertiaUnit unit) + public QuantityValue As(WarpingMomentOfInertiaUnit unit) { - if (Unit == unit) - return Convert.ToDouble(Value); + if(Unit == unit) + return Value; - var converted = GetValueAs(unit); - return Convert.ToDouble(converted); + return GetValueAs(unit); } /// - public double As(UnitSystem unitSystem) + public QuantityValue As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -651,12 +688,12 @@ public double As(UnitSystem unitSystem) } /// - double IQuantity.As(Enum unit) + QuantityValue IQuantity.As(Enum unit) { - if (!(unit is WarpingMomentOfInertiaUnit unitAsWarpingMomentOfInertiaUnit)) + if (!(unit is WarpingMomentOfInertiaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(WarpingMomentOfInertiaUnit)} is supported.", nameof(unit)); - return As(unitAsWarpingMomentOfInertiaUnit); + return (QuantityValue)As(typedUnit); } /// @@ -688,7 +725,7 @@ public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit, UnitConver var converted = conversionFunction(this); return (WarpingMomentOfInertia)converted; } - else if (Unit != BaseUnit) + else if (Enum.IsDefined(typeof(WarpingMomentOfInertiaUnit), unit)) { // Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit. var inBaseUnits = ToUnit(BaseUnit); @@ -696,17 +733,17 @@ public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit, UnitConver } else { - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + throw new NotSupportedException($"Can not convert {Unit} to {unit}."); } } /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is WarpingMomentOfInertiaUnit unitAsWarpingMomentOfInertiaUnit)) + if (!(unit is WarpingMomentOfInertiaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(WarpingMomentOfInertiaUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsWarpingMomentOfInertiaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -733,10 +770,10 @@ public WarpingMomentOfInertia ToUnit(UnitSystem unitSystem) /// IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - private double GetValueAs(WarpingMomentOfInertiaUnit unit) + private QuantityValue GetValueAs(WarpingMomentOfInertiaUnit unit) { var converted = ToUnit(unit); - return (double)converted.Value; + return (QuantityValue)converted.Value; } #endregion diff --git a/UnitsNet/IQuantity.cs b/UnitsNet/IQuantity.cs index 48445422fb..c65a61d0dd 100644 --- a/UnitsNet/IQuantity.cs +++ b/UnitsNet/IQuantity.cs @@ -28,7 +28,7 @@ public interface IQuantity : IFormattable /// The unit enum value. The unit must be compatible, so for you should provide a value. /// Value converted to the specified unit. /// Wrong unit enum type was given. - double As(Enum unit); + QuantityValue As(Enum unit); /// /// Gets the value in the unit determined by the given . If multiple units were found for the given , @@ -36,7 +36,7 @@ public interface IQuantity : IFormattable /// /// The to convert the quantity value to. /// The converted value. - double As(UnitSystem unitSystem); + QuantityValue As(UnitSystem unitSystem); /// /// The unit this quantity was constructed with -or- BaseUnit if default ctor was used. @@ -46,7 +46,7 @@ public interface IQuantity : IFormattable /// /// The value this quantity was constructed with. See also . /// - double Value { get; } + QuantityValue Value { get; } /// /// Converts this to an in the given . @@ -89,7 +89,7 @@ public interface IQuantity : IQuantity where TUnitType : Enum /// Convert to a unit representation . /// /// Value converted to the specified unit. - double As(TUnitType unit); + QuantityValue As(TUnitType unit); /// new TUnitType Unit { get; } diff --git a/UnitsNet/QuantityFormatter.cs b/UnitsNet/QuantityFormatter.cs index 8c7fdeb613..b1f52accff 100644 --- a/UnitsNet/QuantityFormatter.cs +++ b/UnitsNet/QuantityFormatter.cs @@ -180,8 +180,9 @@ private static string FormatUntrimmed(IQuantity quantity, private static string ToStringWithSignificantDigitsAfterRadix(IQuantity quantity, IFormatProvider formatProvider, int number) where TUnitType : Enum { - string formatForSignificantDigits = UnitFormatter.GetFormat(quantity.Value, number); - object[] formatArgs = UnitFormatter.GetFormatArgs(quantity.Unit, quantity.Value, formatProvider, Enumerable.Empty()); + // When a fixed number of digits after the dot is expected, double and decimal behave the same + string formatForSignificantDigits = UnitFormatter.GetFormat((double)quantity.Value, number); + object[] formatArgs = UnitFormatter.GetFormatArgs(quantity.Unit, (double)quantity.Value, formatProvider, Enumerable.Empty()); return string.Format(formatProvider, formatForSignificantDigits, formatArgs); } } diff --git a/UnitsNet/QuantityValue.cs b/UnitsNet/QuantityValue.cs index d25d184e98..0fe4d6169f 100644 --- a/UnitsNet/QuantityValue.cs +++ b/UnitsNet/QuantityValue.cs @@ -5,6 +5,8 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; +using System.Globalization; +using System.Runtime.Serialization; using UnitsNet.InternalHelpers; namespace UnitsNet @@ -27,15 +29,36 @@ namespace UnitsNet /// This allows for adding support for smaller data types without increasing the overall size. /// [StructLayout(LayoutKind.Explicit)] - [DebuggerDisplay("{GetDebugRepresentation()}")] - public readonly struct QuantityValue + // [DebuggerDisplay("{GetDebugRepresentation()}")] // TODO replace with a DebuggerTypeProxy? + [DataContract] + public readonly struct QuantityValue : IFormattable, IEquatable, IComparable, IComparable, IConvertible { + private const decimal MinPrecision = 1E-6m; // min number of decimals reserved: as to avoid values that just barely fit the decimal range + private const double DecimalMin = (double)(decimal.MinValue * MinPrecision); + private const double DecimalMax = (double)(decimal.MaxValue * MinPrecision); + + private static bool InDecimalRange(double value) + { + if (value == 0) + { + return true; + } + + return value is >= DecimalMin and <= DecimalMax && 1 / value is >= DecimalMin and <= DecimalMax; + } + + /// + /// The value 0 + /// + public static readonly QuantityValue Zero = default; + /// /// Value assigned when implicitly casting from all numeric types except , since /// has the greatest range. /// - [FieldOffset(8)] // so that it does not interfere with the Type field - private readonly double _doubleValue; + [FieldOffset(4)] // so that it does not interfere with the Nullable // TODO please review this + [DataMember(Name = "Double", Order = 0, EmitDefaultValue = false)] + private readonly double? _doubleValue; /// /// Value assigned when implicitly casting from type, since it has a greater precision than @@ -44,39 +67,59 @@ public readonly struct QuantityValue /// [FieldOffset(0)] // bytes layout: 0-1 unused, 2 exponent, 3 sign (only highest bit), 4-15 number - private readonly decimal _decimalValue; + [DataMember(Name = "Decimal", Order = 1, EmitDefaultValue = false)] + private readonly decimal? _decimalValue; + /// /// Determines the underlying type of this . /// - [FieldOffset(0)] // using unused byte for storing type - public readonly UnderlyingDataType Type; + public QuantityValueType Type => IsDecimal ? QuantityValueType.Decimal : QuantityValueType.Double; private QuantityValue(double val) : this() { _doubleValue = Guard.EnsureValidNumber(val, nameof(val)); - Type = UnderlyingDataType.Double; } private QuantityValue(decimal val) : this() { _decimalValue = val; - Type = UnderlyingDataType.Decimal; } - #region To QuantityValue + /// + /// Returns true if the underlying value is stored as a decimal + /// + /// True for default(QuantityValue) and QuantityValue.Zero + public bool IsDecimal => !_doubleValue.HasValue; + + /// + /// Value assigned when implicitly casting from all numeric types except , since + /// has the greatest range. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private double DoubleValue => _doubleValue.GetValueOrDefault(); + + /// + /// Value assigned when implicitly casting from type, since it has a greater precision than + /// and we want to preserve that when constructing quantities that use + /// as their value type. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private decimal DecimalValue => _decimalValue.GetValueOrDefault(); + + #region Implicit cast to QuantityValue // Prefer double for integer types, since most quantities use that type as of now and // that avoids unnecessary casts back and forth. // If we later change to use decimal more, we should revisit this. /// Implicit cast from to . - public static implicit operator QuantityValue(byte val) => new QuantityValue((double) val); + public static implicit operator QuantityValue(byte val) => new QuantityValue((decimal) val); /// Implicit cast from to . - public static implicit operator QuantityValue(short val) => new QuantityValue((double) val); + public static implicit operator QuantityValue(short val) => new QuantityValue((decimal) val); /// Implicit cast from to . - public static implicit operator QuantityValue(int val) => new QuantityValue((double) val); + public static implicit operator QuantityValue(int val) => new QuantityValue((decimal) val); /// Implicit cast from to . - public static implicit operator QuantityValue(long val) => new QuantityValue((double) val); + public static implicit operator QuantityValue(long val) => new QuantityValue((decimal) val); /// Implicit cast from to . public static implicit operator QuantityValue(float val) => new QuantityValue(val); // double /// Implicit cast from to . @@ -85,42 +128,309 @@ private QuantityValue(decimal val) : this() public static implicit operator QuantityValue(decimal val) => new QuantityValue(val); // decimal #endregion - #region To double + #region Explicit cast to double - /// Explicit cast from to . + /// Explicit cast from to . public static explicit operator double(QuantityValue number) - => number.Type switch - { - UnderlyingDataType.Decimal => (double)number._decimalValue, - UnderlyingDataType.Double => number._doubleValue, - _ => throw new NotImplementedException() - }; + { + return number.IsDecimal ? (double)number.DecimalValue : number.DoubleValue; + } #endregion - #region To decimal + #region Explicit cast to decimal - /// Explicit cast from to . + /// Explicit cast from to . public static explicit operator decimal(QuantityValue number) - => number.Type switch + { + return number.IsDecimal ? number.DecimalValue : (decimal)number.DoubleValue; + } + + #endregion + + #region Operators and Comparators + + /// + public int CompareTo(QuantityValue other) + { + if (IsDecimal && other.IsDecimal) { - UnderlyingDataType.Decimal => number._decimalValue, - UnderlyingDataType.Double => (decimal)number._doubleValue, - _ => throw new NotImplementedException() - }; + return DecimalValue.CompareTo(other.DecimalValue); + } + + if (IsDecimal) + { + var otherValue = other.DoubleValue; + return InDecimalRange(otherValue) ? DecimalValue.CompareTo((decimal)otherValue) : ((double)DecimalValue).CompareTo(otherValue); + } + + if (other.IsDecimal) + { + var thisValue = DoubleValue; + return InDecimalRange(thisValue) ? ((decimal)thisValue).CompareTo(other.DecimalValue) : thisValue.CompareTo((double)other.DecimalValue); + } + + // Both are double + return DoubleValue.CompareTo(other.DoubleValue); + } + + + /// + public int CompareTo(object? obj) + { + return obj is QuantityValue other ? CompareTo(other) : throw new ArgumentException($"Object must be of type {nameof(QuantityValue)}"); + } + + /// + public override bool Equals(object other) + { + if (other is QuantityValue qv) + { + return Equals(qv); + } + + return false; + } + + /// + public override int GetHashCode() + { + if (IsDecimal) + { + return DecimalValue.GetHashCode(); + } + else + { + return DoubleValue.GetHashCode(); + } + } + + /// + /// Performs an equality comparison on two instances of . + /// Note that rounding might occur if the two values don't use the same base type. + /// + /// The value to compare to + /// True on exact equality, false otherwise + public bool Equals(QuantityValue other) + { + if (IsDecimal && other.IsDecimal) + { + return DecimalValue == other.DecimalValue; + } + + if (IsDecimal) + { + var otherValue = other.DoubleValue; + return InDecimalRange(otherValue) && DecimalValue == (decimal)otherValue; + } + + if (other.IsDecimal) + { + var thisValue = DoubleValue; + return InDecimalRange(thisValue) && (decimal)DoubleValue == other.DecimalValue; + } + + return DoubleValue.Equals(other.DoubleValue); + } + + /// Equality comparator + public static bool operator ==(QuantityValue a, QuantityValue b) + { + return a.Equals(b); + } + + /// Inequality comparator + public static bool operator !=(QuantityValue a, QuantityValue b) + { + return !a.Equals(b); + } + + /// + /// Greater-than operator + /// + public static bool operator >(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) == 1; + } + + /// + /// Less-than operator + /// + public static bool operator <(QuantityValue a, QuantityValue b) + { + + return a.CompareTo(b) == -1; + } + + /// + /// Greater-than-or-equal operator + /// + public static bool operator >=(QuantityValue a, QuantityValue b) + { + + return a.CompareTo(b) >= 0; + } + + /// + /// Less-than-or-equal operator + /// + public static bool operator <=(QuantityValue a, QuantityValue b) + { + + return a.CompareTo(b) <= 0; + } + + /// + /// Returns the negated value of the operand + /// + /// Value to negate + /// -v + public static QuantityValue operator -(QuantityValue v) + { + if (v.IsDecimal) + { + return new QuantityValue(-v.DecimalValue); + } + else + { + return new QuantityValue(-v.DoubleValue); + } + } + + /// + /// Addition operator. + /// + /// + /// This performs an operation on the numeric value of a quantity, clamping the decimal representation as necessary. + /// + public static QuantityValue operator +(QuantityValue a, QuantityValue b) + { + if (a.IsDecimal && b.IsDecimal) + { + var doubleResult = (double)a.DecimalValue + (double)b.DecimalValue; + return InDecimalRange(doubleResult) ? new QuantityValue(a.DecimalValue + b.DecimalValue) : new QuantityValue(doubleResult); + } + else if (a.IsDecimal) + { + var doubleResult = (double)a.DecimalValue + b.DoubleValue; + return InDecimalRange(doubleResult) ? new QuantityValue(a.DecimalValue + (decimal)b.DoubleValue): new QuantityValue(doubleResult); + } + else if (b.IsDecimal) + { + var doubleResult = a.DoubleValue + (double)b.DecimalValue; + return InDecimalRange(doubleResult) ? new QuantityValue((decimal)a.DoubleValue + b.DecimalValue): new QuantityValue(doubleResult); + } + else + { + // Both are double + return new QuantityValue(a.DoubleValue + b.DoubleValue); + } + } + + /// + /// Subtraction operator. + /// + /// + /// This performs an operation on the numeric value of a quantity, there is no unit or conversions involved. + /// + public static QuantityValue operator -(QuantityValue a, QuantityValue b) + { + if (a.IsDecimal && b.IsDecimal) + { + var doubleResult = (double)a.DecimalValue - (double)b.DecimalValue; + return InDecimalRange(doubleResult) ? new QuantityValue(a.DecimalValue - b.DecimalValue) : new QuantityValue(doubleResult); + } + else if (a.IsDecimal) + { + var doubleResult = (double)a.DecimalValue - b.DoubleValue; + return InDecimalRange(doubleResult) ? new QuantityValue(a.DecimalValue - (decimal)b.DoubleValue): new QuantityValue(doubleResult); + } + else if (b.IsDecimal) + { + var doubleResult = a.DoubleValue - (double)b.DecimalValue; + return InDecimalRange(doubleResult) ? new QuantityValue((decimal)a.DoubleValue - b.DecimalValue): new QuantityValue(doubleResult); + } + else + { + // Both are double + return new QuantityValue(a.DoubleValue - b.DoubleValue); + } + } + + /// + /// Multiplication operator. + /// + /// + /// This performs an operation on the numeric value of a quantity, there is no unit or conversions involved. + /// + public static QuantityValue operator *(QuantityValue a, QuantityValue b) + { + if (a.IsDecimal && b.IsDecimal) + { + var doubleResult = (double)a.DecimalValue * (double)b.DecimalValue; + return InDecimalRange(doubleResult) ? new QuantityValue(a.DecimalValue * b.DecimalValue) : new QuantityValue(doubleResult); + } + else if (a.IsDecimal) + { + var doubleResult = (double)a.DecimalValue * b.DoubleValue; + return InDecimalRange(doubleResult) ? new QuantityValue(a.DecimalValue * (decimal)b.DoubleValue): new QuantityValue(doubleResult); + } + else if (b.IsDecimal) + { + var doubleResult = a.DoubleValue * (double)b.DecimalValue; + return InDecimalRange(doubleResult) ? new QuantityValue((decimal)a.DoubleValue * b.DecimalValue): new QuantityValue(doubleResult); + } + else + { + // Both are double + return new QuantityValue(a.DoubleValue * b.DoubleValue); + } + } + + /// + /// Division operator. + /// + /// + /// This performs an operation on the numeric value of a quantity, there is no unit or conversions involved. + /// + public static QuantityValue operator /(QuantityValue a, QuantityValue b) + { + if (a.IsDecimal && b.IsDecimal) + { + var doubleResult = (double)a.DecimalValue / (double)b.DecimalValue; + return InDecimalRange(doubleResult) ? new QuantityValue(a.DecimalValue / b.DecimalValue) : new QuantityValue(doubleResult); + } + else if (a.IsDecimal) + { + var doubleResult = (double)a.DecimalValue / b.DoubleValue; + return InDecimalRange(doubleResult) ? new QuantityValue(a.DecimalValue / (decimal)b.DoubleValue): new QuantityValue(doubleResult); + } + else if (b.IsDecimal) + { + var doubleResult = a.DoubleValue / (double)b.DecimalValue; + return InDecimalRange(doubleResult) ? new QuantityValue((decimal)a.DoubleValue / b.DecimalValue): new QuantityValue(doubleResult); + } + else + { + // Both are double + return new QuantityValue(a.DoubleValue / b.DoubleValue); + } + } #endregion + #region ToString + /// Returns the string representation of the numeric value. public override string ToString() => Type switch { - UnderlyingDataType.Decimal => _decimalValue.ToString(), - UnderlyingDataType.Double => _doubleValue.ToString(), + QuantityValueType.Decimal => DecimalValue.ToString(), + QuantityValueType.Double => DoubleValue.ToString(), _ => throw new NotImplementedException() }; - private string GetDebugRepresentation() + private string GetDebugRepresentation() // TODO replace by DebuggerTypeProxy? { StringBuilder builder = new($"{Type} {ToString()} Hex:"); @@ -133,10 +443,132 @@ private string GetDebugRepresentation() return builder.ToString(); } + /// + /// Returns the string representation of the numeric value, formatted using the given standard numeric format string + /// + /// A standard numeric format string (must be valid for either double or decimal, depending on the base type) + /// The string representation + public string ToString(string format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// + /// Returns the string representation of the underlying value + /// + /// Standard format specifiers. Because the underlying value can be double or decimal, the meaning can vary + /// Culture specific settings + /// A string representation of the number + public string ToString(string format, IFormatProvider formatProvider) + { + if (IsDecimal) + { + return DecimalValue.ToString(format, formatProvider); + } + else + { + return DoubleValue.ToString(format, formatProvider); + } + } + + #endregion + + #region IConvertiable interface implmentation + + TypeCode IConvertible.GetTypeCode() + { + return IsDecimal ? TypeCode.Decimal : TypeCode.Double; + } + + bool IConvertible.ToBoolean(IFormatProvider provider) + { + throw new InvalidCastException($"Converting {typeof(QuantityValue)} to Boolean is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider provider) + { + return IsDecimal ? Convert.ToByte(DecimalValue) : Convert.ToByte(DoubleValue); + } + + char IConvertible.ToChar(IFormatProvider provider) + { + throw new InvalidCastException($"Converting {typeof(QuantityValue)} to Char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider provider) + { + throw new InvalidCastException($"Converting {typeof(QuantityValue)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider provider) + { + return IsDecimal ? DecimalValue : Convert.ToDecimal(DoubleValue); + } + + double IConvertible.ToDouble(IFormatProvider provider) + { + return IsDecimal ? Convert.ToDouble(DecimalValue) : DoubleValue; + } + + short IConvertible.ToInt16(IFormatProvider provider) + { + return IsDecimal ? Convert.ToInt16(DecimalValue) : Convert.ToInt16(DoubleValue); + } + + int IConvertible.ToInt32(IFormatProvider provider) + { + return IsDecimal ? Convert.ToInt16(DecimalValue) : Convert.ToInt16(DoubleValue); + } + + long IConvertible.ToInt64(IFormatProvider provider) + { + return IsDecimal ? Convert.ToInt16(DecimalValue) : Convert.ToInt16(DoubleValue); + } + + sbyte IConvertible.ToSByte(IFormatProvider provider) + { + return IsDecimal ? Convert.ToSByte(DecimalValue) : Convert.ToSByte(DoubleValue); + } + + float IConvertible.ToSingle(IFormatProvider provider) + { + return IsDecimal ? Convert.ToSingle(DecimalValue) : Convert.ToSingle(DoubleValue); + } + + /// Converts the numeric value of this instance to its equivalent string representation using the specified culture-specific format information. + /// An object that supplies culture-specific formatting information. + /// The string representation of the value of this instance as specified by . + public string ToString(IFormatProvider provider) + { + return IsDecimal ? Convert.ToString(DecimalValue, provider) : Convert.ToString(DoubleValue, provider); + } + + ushort IConvertible.ToUInt16(IFormatProvider provider) + { + return IsDecimal ? Convert.ToUInt16(DecimalValue) : Convert.ToUInt16(DoubleValue); + } + + uint IConvertible.ToUInt32(IFormatProvider provider) + { + return IsDecimal ? Convert.ToUInt32(DecimalValue) : Convert.ToUInt32(DoubleValue); + } + + ulong IConvertible.ToUInt64(IFormatProvider provider) + { + return IsDecimal ? Convert.ToUInt64(DecimalValue) : Convert.ToUInt64(DoubleValue); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider provider) + { + return IsDecimal ? ((IConvertible)DecimalValue).ToType(conversionType, provider) : ((IConvertible)DoubleValue).ToType(conversionType, provider); + } + + #endregion + /// /// Describes the underlying type of a . /// - public enum UnderlyingDataType : byte + public enum QuantityValueType : byte { /// must have the value 0 due to the bit structure of . Decimal = 0, diff --git a/UnitsNet/UnitConverter.cs b/UnitsNet/UnitConverter.cs index 7b5a93eb0f..b7f639f24d 100644 --- a/UnitsNet/UnitConverter.cs +++ b/UnitsNet/UnitConverter.cs @@ -270,7 +270,7 @@ public bool TryGetConversionFunction(ConversionFunctionLookupKey lookupKey, out /// From unit enum value. /// To unit enum value, must be compatible with . /// The converted value in the new unit representation. - public static double Convert(QuantityValue fromValue, Enum fromUnitValue, Enum toUnitValue) + public static QuantityValue Convert(QuantityValue fromValue, Enum fromUnitValue, Enum toUnitValue) { return Quantity .From(fromValue, fromUnitValue) @@ -285,7 +285,7 @@ public static double Convert(QuantityValue fromValue, Enum fromUnitValue, Enum t /// To unit enum value, must be compatible with . /// The converted value, if successful. Otherwise default. /// True if successful. - public static bool TryConvert(QuantityValue fromValue, Enum fromUnitValue, Enum toUnitValue, out double convertedValue) + public static bool TryConvert(QuantityValue fromValue, Enum fromUnitValue, Enum toUnitValue, out QuantityValue convertedValue) { convertedValue = 0; if (!Quantity.TryFrom(fromValue, fromUnitValue, out IQuantity? fromQuantity)) @@ -331,7 +331,7 @@ public static bool TryConvert(QuantityValue fromValue, Enum fromUnitValue, Enum /// Output value as the result of converting to . /// No units match the abbreviation. /// More than one unit matches the abbreviation. - public static double ConvertByName(QuantityValue fromValue, string quantityName, string fromUnit, string toUnit) + public static QuantityValue ConvertByName(QuantityValue fromValue, string quantityName, string fromUnit, string toUnit) { if (!TryGetUnitType(quantityName, out Type? unitType)) throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); @@ -380,7 +380,7 @@ public static double ConvertByName(QuantityValue fromValue, string quantityName, /// Result if conversion was successful, 0 if not. /// bool ok = TryConvertByName(5, "Length", "Meter", "Centimeter", out double centimeters); // 500 /// True if conversion was successful. - public static bool TryConvertByName(QuantityValue inputValue, string quantityName, string fromUnit, string toUnit, out double result) + public static bool TryConvertByName(QuantityValue inputValue, string quantityName, string fromUnit, string toUnit, out QuantityValue result) { result = 0d; @@ -423,7 +423,7 @@ public static bool TryConvertByName(QuantityValue inputValue, string quantityNam /// /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 /// Output value as the result of converting to . - public static double ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev) + public static QuantityValue ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev) { return ConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, null); } @@ -460,7 +460,7 @@ public static double ConvertByAbbreviation(QuantityValue fromValue, string quant /// are mapped to the abbreviation. /// /// More than one unit matches the abbreviation. - public static double ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string? culture) + public static QuantityValue ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string? culture) { if (!TryGetUnitType(quantityName, out Type? unitType)) throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); @@ -501,7 +501,7 @@ public static double ConvertByAbbreviation(QuantityValue fromValue, string quant /// Result if conversion was successful, 0 if not. /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 /// True if conversion was successful. - public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result) + public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out QuantityValue result) { return TryConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, out result, null); } @@ -534,7 +534,7 @@ public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quan /// Result if conversion was successful, 0 if not. /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 /// True if conversion was successful. - public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result, + public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out QuantityValue result, string? culture) { result = 0d; diff --git a/UnitsNet/UnitMath.cs b/UnitsNet/UnitMath.cs index d684c77e66..b69087b62e 100644 --- a/UnitsNet/UnitMath.cs +++ b/UnitsNet/UnitMath.cs @@ -17,7 +17,7 @@ public static class UnitMath /// A quantity with a value, such that 0 ≤ value ≤ . public static TQuantity Abs(this TQuantity value) where TQuantity : IQuantity { - return value.Value >= 0 ? value : (TQuantity) Quantity.From(-value.Value, value.Unit); + return value.Value >= QuantityValue.Zero ? value : (TQuantity) Quantity.From(-value.Value, value.Unit); } /// Computes the sum of a sequence of values. @@ -33,7 +33,7 @@ public static TQuantity Abs(this TQuantity value) where TQuantity : I public static TQuantity Sum(this IEnumerable source, Enum unitType) where TQuantity : IQuantity { - return (TQuantity) Quantity.From(source.Sum(x => x.As(unitType)), unitType); + return (TQuantity) Quantity.From(source.Aggregate(QuantityValue.Zero, (current, quantity) => current + quantity.As(unitType)), unitType); } /// @@ -172,7 +172,20 @@ public static TQuantity Max(this IEnumerable source public static TQuantity Average(this IEnumerable source, Enum unitType) where TQuantity : IQuantity { - return (TQuantity) Quantity.From(source.Average(x => x.As(unitType)), unitType); + var count = 0; + var total = QuantityValue.Zero; + foreach (var quantity in source) + { + count++; + total += quantity.As(unitType); + } + + if (count == 0) + { + throw new InvalidOperationException($"{nameof(source)} contains no elements."); + } + + return (TQuantity) Quantity.From(total / count, unitType); } /// @@ -197,5 +210,25 @@ public static TQuantity Average(this IEnumerable so { return source.Select(selector).Average(unitType); } + + /// + /// Explicitly create a instance from a double + /// + /// The input value + /// An instance of + public static QuantityValue ToQuantityValue(this double value) + { + return value; // Implicit cast + } + + /// + /// Explicitly create a instance from a decimal + /// + /// The input value + /// An instance of + public static QuantityValue ToQuantityValue(this decimal value) + { + return value; // Implicit cast + } } }